summaryrefslogtreecommitdiffstats
path: root/contrib/libs/grpc/src
diff options
context:
space:
mode:
authororivej <[email protected]>2022-02-10 16:44:49 +0300
committerDaniil Cherednik <[email protected]>2022-02-10 16:44:49 +0300
commit718c552901d703c502ccbefdfc3c9028d608b947 (patch)
tree46534a98bbefcd7b1f3faa5b52c138ab27db75b7 /contrib/libs/grpc/src
parente9656aae26e0358d5378e5b63dcac5c8dbe0e4d0 (diff)
Restoring authorship annotation for <[email protected]>. Commit 1 of 2.
Diffstat (limited to 'contrib/libs/grpc/src')
-rw-r--r--contrib/libs/grpc/src/compiler/README.md2
-rw-r--r--contrib/libs/grpc/src/compiler/config.h34
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_generator.cc1214
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_generator.h62
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_generator_helpers.h24
-rw-r--r--contrib/libs/grpc/src/compiler/cpp_plugin.cc22
-rw-r--r--contrib/libs/grpc/src/compiler/csharp_generator.cc188
-rw-r--r--contrib/libs/grpc/src/compiler/csharp_generator.h20
-rw-r--r--contrib/libs/grpc/src/compiler/csharp_generator_helpers.h22
-rw-r--r--contrib/libs/grpc/src/compiler/generator_helpers.h32
-rw-r--r--contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make2
-rw-r--r--contrib/libs/grpc/src/compiler/node_generator.cc76
-rw-r--r--contrib/libs/grpc/src/compiler/node_generator.h32
-rw-r--r--contrib/libs/grpc/src/compiler/node_generator_helpers.h20
-rw-r--r--contrib/libs/grpc/src/compiler/objective_c_generator.cc158
-rw-r--r--contrib/libs/grpc/src/compiler/objective_c_generator.h36
-rw-r--r--contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h64
-rw-r--r--contrib/libs/grpc/src/compiler/php_generator.cc108
-rw-r--r--contrib/libs/grpc/src/compiler/php_generator_helpers.h76
-rw-r--r--contrib/libs/grpc/src/compiler/protobuf_plugin.h316
-rw-r--r--contrib/libs/grpc/src/compiler/python_generator.cc476
-rw-r--r--contrib/libs/grpc/src/compiler/python_generator.h26
-rw-r--r--contrib/libs/grpc/src/compiler/python_generator_helpers.h222
-rw-r--r--contrib/libs/grpc/src/compiler/python_plugin.cc22
-rw-r--r--contrib/libs/grpc/src/compiler/python_private_generator.h152
-rw-r--r--contrib/libs/grpc/src/compiler/ruby_generator.cc52
-rw-r--r--contrib/libs/grpc/src/compiler/ruby_generator.h20
-rw-r--r--contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h24
-rw-r--r--contrib/libs/grpc/src/compiler/ruby_generator_map-inl.h20
-rw-r--r--contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h44
-rw-r--r--contrib/libs/grpc/src/compiler/schema_interface.h176
-rw-r--r--contrib/libs/grpc/src/core/README.md2
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/README.md82
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.cc308
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/backup_poller.h66
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc484
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc1646
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h108
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.cc66
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_factory.h70
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc112
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h72
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc410
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.h66
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc170
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.h46
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc70
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h136
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc178
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h58
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc1396
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc48
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h66
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc98
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc100
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h68
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc92
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h74
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc438
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc636
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h502
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h80
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc178
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h104
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper.h80
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.cc86
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/proxy_mapper_registry.h60
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc58
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h150
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/README.md8
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc536
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h88
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc114
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc586
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h130
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc102
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/README.md4
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc420
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc312
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h134
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/README.md2
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc228
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h120
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.cc308
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_registry.h140
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.cc372
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/retry_throttle.h150
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc424
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h134
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc646
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h148
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc926
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.h60
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc262
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.h68
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/http_filters_plugin.cc154
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc398
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.h106
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc566
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h56
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc960
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.h52
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc314
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.h52
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc382
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h54
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.cc106
-rw-r--r--contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.h78
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.cc88
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.h28
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.cc84
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.h72
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.cc130
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/chttp2_connector.h26
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create.cc156
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc156
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc180
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc162
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.h26
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc84
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc118
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc142
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc474
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.h36
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.cc438
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_encoder.h26
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc56
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc4338
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h48
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc700
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.h886
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame.h24
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc498
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h58
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.cc344
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_goaway.h42
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.cc240
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_ping.h42
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc188
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.h36
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.cc444
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_settings.h42
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc208
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.h38
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc700
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h60
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc3060
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.h74
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc364
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h36
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.cc124
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.h114
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.cc184
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.h20
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.cc112
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h44
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h662
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc1150
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_lists.cc426
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.cc298
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.h48
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.cc112
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.h20
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc1136
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/inproc/inproc_plugin.cc56
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc1692
-rw-r--r--contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/avl/avl.cc610
-rw-r--r--contrib/libs/grpc/src/core/lib/avl/avl.h188
-rw-r--r--contrib/libs/grpc/src/core/lib/backoff/backoff.cc156
-rw-r--r--contrib/libs/grpc/src/core/lib/backoff/backoff.h178
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_args.cc652
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_args.h96
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_stack.cc450
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_stack.h174
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc618
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h126
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_trace.cc234
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/channel_trace.h186
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/connected_channel.cc416
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/connected_channel.h38
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/context.h22
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker.cc196
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h24
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc98
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h24
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/status_util.cc194
-rw-r--r--contrib/libs/grpc/src/core/lib/channel/status_util.h116
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression.cc324
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression_internal.cc526
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/compression_internal.h174
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/message_compress.cc366
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/message_compress.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression.cc154
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression.h226
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.cc442
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.h56
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.cc174
-rw-r--r--contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.h58
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/stats.cc302
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/stats.h120
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/stats_data.cc1364
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/stats_data.h870
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql192
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/trace.cc276
-rw-r--r--contrib/libs/grpc/src/core/lib/debug/trace.h168
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/README.md16
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/alloc.cc140
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/arena.h68
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/atm.cc70
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/cpu_iphone.cc72
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc162
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc156
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/cpu_windows.cc66
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env.h74
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env_linux.cc122
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env_posix.cc84
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/env_windows.cc134
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log.cc178
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log_android.cc152
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log_linux.cc174
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log_posix.cc170
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/log_windows.cc204
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/murmur_hash.cc160
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/murmur_hash.h58
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/spinlock.h86
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string.cc562
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string.h180
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string_posix.cc144
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string_util_windows.cc164
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string_windows.cc138
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/string_windows.h64
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/sync.cc248
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc194
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/sync_windows.cc232
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time.cc502
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time_posix.cc326
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time_precise.cc84
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time_precise.h58
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/time_windows.cc196
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tls.h136
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tls_gcc.h104
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tls_msvc.h104
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tls_pthread.cc60
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tls_pthread.h112
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tmpfile.h64
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tmpfile_msys.cc116
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tmpfile_posix.cc140
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/tmpfile_windows.cc138
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/useful.h130
-rw-r--r--contrib/libs/grpc/src/core/lib/gpr/wrap_memcpy.cc84
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/README.md22
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/atomic.h62
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/debug_location.h100
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/manual_constructor.h426
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/memory.h76
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/orphanable.h202
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h144
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h200
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/thd.h240
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc264
-rw-r--r--contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc244
-rw-r--r--contrib/libs/grpc/src/core/lib/http/format_request.cc114
-rw-r--r--contrib/libs/grpc/src/core/lib/http/format_request.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/http/httpcli.cc568
-rw-r--r--contrib/libs/grpc/src/core/lib/http/httpcli.h90
-rw-r--r--contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc190
-rw-r--r--contrib/libs/grpc/src/core/lib/http/parser.cc736
-rw-r--r--contrib/libs/grpc/src/core/lib/http/parser.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/block_annotate.h114
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc278
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h86
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/closure.h300
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/combiner.cc576
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/combiner.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc116
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint.h72
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_posix.cc124
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_uv.cc80
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_windows.cc170
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/error.cc1466
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/error.h162
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/error_internal.h120
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc2292
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.h62
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc2606
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc2446
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.h28
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc574
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h108
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc56
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc264
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h278
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor.cc320
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/executor.h30
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc134
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/fork_windows.cc82
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/gethostname.h52
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/gethostname_fallback.cc60
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/gethostname_host_name_max.cc80
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/gethostname_sysconf.cc80
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc296
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.h42
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc330
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr.h34
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc122
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h94
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc86
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc128
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.h24
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc80
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc172
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc208
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.h72
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/load_file.cc160
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/load_file.h28
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc468
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.h144
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/nameser.h212
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc170
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h64
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset.cc112
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset.h88
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc198
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_set.cc110
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_set.h68
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.cc76
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.h52
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.cc102
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.h24
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.cc184
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.h34
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc454
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.h42
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/port.h112
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address.cc100
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h98
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.cc238
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.h82
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc310
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resolve_address_windows.cc264
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc1462
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h86
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sockaddr.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sockaddr_custom.h106
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc526
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.h62
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sockaddr_windows.h74
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc186
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.h132
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc164
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h48
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h44
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc658
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_linux.cc84
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.cc116
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h76
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc88
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc86
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc288
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h54
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/sys_epoll_wrapper.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client.cc72
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client.h56
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc264
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc580
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.h90
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_client_windows.cc428
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc632
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.h160
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc1266
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h38
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc138
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h98
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_custom.cc856
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc1018
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h234
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc392
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc332
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc72
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_server_windows.cc1058
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc820
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc828
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h42
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.cc128
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.h20
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer.cc90
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer.h116
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc176
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_custom.h86
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc1174
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_generic.h40
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc266
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h36
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc654
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h74
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/timer_uv.cc130
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc1388
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/udp_server.h110
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.cc180
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.h34
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix_noop.cc94
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc158
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_nospecial.cc76
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.cc200
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.cc136
-rw-r--r--contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/json/json.h30
-rw-r--r--contrib/libs/grpc/src/core/lib/json/json_reader.cc696
-rw-r--r--contrib/libs/grpc/src/core/lib/json/json_writer.cc268
-rw-r--r--contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc562
-rw-r--r--contrib/libs/grpc/src/core/lib/profiling/stap_timers.cc98
-rw-r--r--contrib/libs/grpc/src/core/lib/profiling/timers.h74
-rw-r--r--contrib/libs/grpc/src/core/lib/security/context/security_context.cc456
-rw-r--r--contrib/libs/grpc/src/core/lib/security/context/security_context.h38
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc138
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h144
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.cc142
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.h114
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc130
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc62
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc114
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc250
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc92
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h150
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc112
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc220
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc288
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/credentials.h84
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/credentials_metadata.cc124
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc134
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h70
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/google_default/credentials_generic.cc70
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc422
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h22
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc94
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h24
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.cc512
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/json_token.h52
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc196
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc1532
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.h72
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc612
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h52
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc348
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc542
-rw-r--r--contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h48
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.cpp18
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.h14
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc174
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h164
-rw-r--r--contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc12
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/auth_filters.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc582
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc748
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.h44
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc472
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc422
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/tsi_error.cc58
-rw-r--r--contrib/libs/grpc/src/core/lib/security/transport/tsi_error.h28
-rw-r--r--contrib/libs/grpc/src/core/lib/security/util/json_util.cc72
-rw-r--r--contrib/libs/grpc/src/core/lib/security/util/json_util.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/b64.cc472
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/b64.h94
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/percent_encoding.cc332
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/percent_encoding.h30
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice.cc684
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc676
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_intern.cc378
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_internal.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.cc234
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_string_helpers.h44
-rw-r--r--contrib/libs/grpc/src/core/lib/slice/slice_traits.h56
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/api_trace.cc48
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/api_trace.h26
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/byte_buffer.cc184
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/byte_buffer_reader.cc164
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call.cc3102
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call.h92
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call_details.cc82
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call_log_batch.cc120
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/call_test_only.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel.cc644
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel.h62
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel_init.cc218
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel_init.h32
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel_ping.cc122
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel_stack_type.cc116
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/channel_stack_type.h28
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/completion_queue.cc2038
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/completion_queue.h86
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc148
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.h76
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/event_string.cc86
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/event_string.h24
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/init.cc314
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/init.h20
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/init_secure.cc154
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/init_unsecure.cc54
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/lame_client.cc290
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/lame_client.h24
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/metadata_array.cc72
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/server.cc464
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/server.h6
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc174
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/validate_metadata.h56
-rw-r--r--contrib/libs/grpc/src/core/lib/surface/version.cc52
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc168
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h182
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/byte_stream.cc304
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/byte_stream.h254
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc132
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/connectivity_state.h30
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/error_utils.cc232
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/error_utils.h92
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/http2_errors.h82
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata.cc492
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata.h140
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc622
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/metadata_batch.h150
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/pid_controller.cc102
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/pid_controller.h194
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/static_metadata.cc160
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/static_metadata.h320
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/status_conversion.cc170
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/status_conversion.h76
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/status_metadata.cc100
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/status_metadata.h60
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc286
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h34
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport.cc376
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport.h342
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport_impl.h54
-rw-r--r--contrib/libs/grpc/src/core/lib/transport/transport_op_string.cc206
-rw-r--r--contrib/libs/grpc/src/core/lib/ya.make8
-rw-r--r--contrib/libs/grpc/src/core/plugin_registry/grpc_plugin_registry.cc174
-rw-r--r--contrib/libs/grpc/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc174
-rw-r--r--contrib/libs/grpc/src/core/tsi/README.md4
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/crypt/aes_gcm.cc1374
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.cc378
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.h908
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.cc236
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.h196
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.cc132
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.h510
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.cc814
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.h110
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc228
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h228
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc210
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc204
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.cc436
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.h472
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc350
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h202
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc568
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h118
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h84
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc102
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.h98
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/altscontext.proto82
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.options4
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.proto448
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/transport_security_common.proto80
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.cc296
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.h272
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h102
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h98
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h182
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc348
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h194
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc952
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h398
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc564
-rw-r--r--contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h100
-rw-r--r--contrib/libs/grpc/src/core/tsi/fake_transport_security.cc1522
-rw-r--r--contrib/libs/grpc/src/core/tsi/fake_transport_security.h90
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session.h138
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc110
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc392
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.h172
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_openssl.cc146
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc3194
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl_transport_security.h602
-rw-r--r--contrib/libs/grpc/src/core/tsi/ssl_types.h84
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/BUILD36
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/README102
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/badclient.key4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/badclient.pem4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/badserver.key4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/badserver.pem4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/ca-openssl.cnf34
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/ca.key4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/ca.pem4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/client.key4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/client.pem4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/server0.key4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/server0.pem4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/server1-openssl.cnf52
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/server1.key4
-rw-r--r--contrib/libs/grpc/src/core/tsi/test_creds/server1.pem4
-rw-r--r--contrib/libs/grpc/src/core/tsi/transport_security.cc652
-rw-r--r--contrib/libs/grpc/src/core/tsi/transport_security.h234
-rw-r--r--contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc132
-rw-r--r--contrib/libs/grpc/src/core/tsi/transport_security_grpc.h142
-rw-r--r--contrib/libs/grpc/src/core/tsi/transport_security_interface.h900
-rwxr-xr-xcontrib/libs/grpc/src/cpp/README.md2
-rw-r--r--contrib/libs/grpc/src/cpp/client/channel_cc.cc88
-rw-r--r--contrib/libs/grpc/src/cpp/client/client_context.cc42
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel.cc28
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel_internal.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel_internal.h22
-rw-r--r--contrib/libs/grpc/src/cpp/client/create_channel_posix.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/client/credentials_cc.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/client/insecure_credentials.cc28
-rw-r--r--contrib/libs/grpc/src/cpp/client/secure_credentials.cc200
-rw-r--r--contrib/libs/grpc/src/cpp/client/secure_credentials.h50
-rw-r--r--contrib/libs/grpc/src/cpp/codegen/codegen_init.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/common/alarm.cc182
-rw-r--r--contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/common/channel_arguments.cc62
-rw-r--r--contrib/libs/grpc/src/cpp/common/channel_filter.cc74
-rw-r--r--contrib/libs/grpc/src/cpp/common/channel_filter.h306
-rw-r--r--contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc84
-rw-r--r--contrib/libs/grpc/src/cpp/common/core_codegen.cc186
-rw-r--r--contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/common/rpc_method.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/common/secure_auth_context.cc20
-rw-r--r--contrib/libs/grpc/src/cpp/common/secure_auth_context.h22
-rw-r--r--contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/common/version_cc.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc32
-rw-r--r--contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h22
-rw-r--r--contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc28
-rw-r--r--contrib/libs/grpc/src/cpp/server/async_generic_service.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/server/channel_argument_option.cc108
-rw-r--r--contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc40
-rw-r--r--contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc46
-rw-r--r--contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h26
-rw-r--r--contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc128
-rw-r--r--contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h100
-rw-r--r--contrib/libs/grpc/src/cpp/server/health/health_check_service.cc62
-rw-r--r--contrib/libs/grpc/src/cpp/server/health/health_check_service_server_builder_option.cc68
-rw-r--r--contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc512
-rw-r--r--contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h550
-rw-r--r--contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc60
-rw-r--r--contrib/libs/grpc/src/cpp/server/secure_server_credentials.h22
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_builder.cc100
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_cc.cc206
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_context.cc52
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_credentials.cc20
-rw-r--r--contrib/libs/grpc/src/cpp/server/server_posix.cc24
-rw-r--r--contrib/libs/grpc/src/cpp/server/thread_pool_interface.h28
-rw-r--r--contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc182
-rw-r--r--contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h38
-rw-r--r--contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc28
-rw-r--r--contrib/libs/grpc/src/cpp/util/error_details.cc66
-rw-r--r--contrib/libs/grpc/src/cpp/util/status.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/util/string_ref.cc22
-rw-r--r--contrib/libs/grpc/src/cpp/util/time_cc.cc34
-rw-r--r--contrib/libs/grpc/src/proto/grpc/binary_log/v1alpha/log.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto830
-rw-r--r--contrib/libs/grpc/src/proto/grpc/core/stats.proto76
-rw-r--r--contrib/libs/grpc/src/proto/grpc/health/v1/health.options2
-rw-r--r--contrib/libs/grpc/src/proto/grpc/health/v1/health.proto18
-rw-r--r--contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto94
-rw-r--r--contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/reflection.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/status/README4
-rw-r--r--contrib/libs/grpc/src/proto/grpc/status/status.proto184
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto88
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto36
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/control.proto78
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/echo.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto40
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/empty.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/messages.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/metrics.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/payloads.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2_extensions.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto62
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto52
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/stats.proto48
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/test.proto20
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto90
-rw-r--r--contrib/libs/grpc/src/proto/math/math.proto20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/README.rst2
-rw-r--r--contrib/libs/grpc/src/python/grpcio/_spawn_patch.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/commands.py28
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/__init__.py1998
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_auth.py24
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_channel.py462
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_common.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi48
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi104
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pxd.pxi20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi50
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi130
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi776
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pxd.pxi32
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi136
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi130
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi352
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pxd.pxi90
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pyx.pxi110
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi270
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi70
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi48
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi120
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi182
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi438
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pxd.pxi26
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi78
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pxd.pxi22
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pyx.pxi154
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi50
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi112
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi158
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi34
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi44
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd36
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx48
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_grpcio_metadata.py32
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py566
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py126
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_server.py318
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py38
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/beta/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/beta/_client_adaptations.py208
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/beta/_metadata.py104
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py70
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/beta/implementations.py58
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/beta/interfaces.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py34
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/experimental/gevent.py54
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/common/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/common/cardinality.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/common/style.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/abandonment.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py24
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/future.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py22
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/base.py48
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/utilities.py42
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/face.py46
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/utilities.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py472
-rw-r--r--contrib/libs/grpc/src/python/grpcio/grpc_version.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio/support.py32
-rw-r--r--contrib/libs/grpc/src/python/grpcio/ya.make64
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/grpc_version.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_health_checking/setup.py114
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/README.rst20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/__init__.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py32
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/grpc_version.py20
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py26
-rw-r--r--contrib/libs/grpc/src/python/grpcio_reflection/setup.py114
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py1392
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/__init__.py50
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel.py174
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_rpc.py238
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_state.py94
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py642
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_multi_callable.py236
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_rpc_state.py378
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_common.py324
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/__init__.py40
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py428
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py302
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server.py268
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server_rpc.py186
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_service.py166
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py152
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py450
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/grpc_version.py32
-rw-r--r--contrib/libs/grpc/src/python/grpcio_testing/setup.py68
809 files changed, 87676 insertions, 87676 deletions
diff --git a/contrib/libs/grpc/src/compiler/README.md b/contrib/libs/grpc/src/compiler/README.md
index d5684af7ff2..bceace0c161 100644
--- a/contrib/libs/grpc/src/compiler/README.md
+++ b/contrib/libs/grpc/src/compiler/README.md
@@ -1,4 +1,4 @@
-# Overview
+# Overview
This directory contains source code for gRPC protocol buffer compiler (*protoc*) plugins. Along with `protoc`,
these plugins are used to generate gRPC client and server stubs from `.proto` files.
diff --git a/contrib/libs/grpc/src/compiler/config.h b/contrib/libs/grpc/src/compiler/config.h
index 95213b0f045..26f6b06df7c 100644
--- a/contrib/libs/grpc/src/compiler/config.h
+++ b/contrib/libs/grpc/src/compiler/config.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -57,11 +57,11 @@ typedef GRPC_CUSTOM_STRINGOUTPUTSTREAM StringOutputStream;
} // namespace protobuf
} // namespace grpc
-namespace grpc_cpp_generator {
-
-static const char* const kCppGeneratorMessageHeaderExt = ".pb.h";
-static const char* const kCppGeneratorServiceHeaderExt = ".grpc.pb.h";
-
-} // namespace grpc_cpp_generator
-
+namespace grpc_cpp_generator {
+
+static const char* const kCppGeneratorMessageHeaderExt = ".pb.h";
+static const char* const kCppGeneratorServiceHeaderExt = ".grpc.pb.h";
+
+} // namespace grpc_cpp_generator
+
#endif // SRC_COMPILER_CONFIG_H
diff --git a/contrib/libs/grpc/src/compiler/cpp_generator.cc b/contrib/libs/grpc/src/compiler/cpp_generator.cc
index 57591774745..340b307bf78 100644
--- a/contrib/libs/grpc/src/compiler/cpp_generator.cc
+++ b/contrib/libs/grpc/src/compiler/cpp_generator.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -34,14 +34,14 @@ TString as_string(T x) {
return out.str();
}
-inline bool ClientOnlyStreaming(const grpc_generator::Method* method) {
- return method->ClientStreaming() && !method->ServerStreaming();
-}
-
-inline bool ServerOnlyStreaming(const grpc_generator::Method* method) {
- return !method->ClientStreaming() && method->ServerStreaming();
-}
-
+inline bool ClientOnlyStreaming(const grpc_generator::Method* method) {
+ return method->ClientStreaming() && !method->ServerStreaming();
+}
+
+inline bool ServerOnlyStreaming(const grpc_generator::Method* method) {
+ return !method->ClientStreaming() && method->ServerStreaming();
+}
+
TString FilenameIdentifier(const TString& filename) {
TString result;
for (unsigned i = 0; i < filename.size(); i++) {
@@ -60,11 +60,11 @@ TString FilenameIdentifier(const TString& filename) {
} // namespace
template <class T, size_t N>
-T* array_end(T (&array)[N]) {
+T* array_end(T (&array)[N]) {
return array + N;
}
-void PrintIncludes(grpc_generator::Printer* printer,
+void PrintIncludes(grpc_generator::Printer* printer,
const std::vector<TString>& headers,
bool use_system_headers, const TString& search_path) {
std::map<TString, TString> vars;
@@ -72,9 +72,9 @@ void PrintIncludes(grpc_generator::Printer* printer,
vars["l"] = use_system_headers ? '<' : '"';
vars["r"] = use_system_headers ? '>' : '"';
- if (!search_path.empty()) {
- vars["l"] += search_path;
- if (search_path[search_path.size() - 1] != '/') {
+ if (!search_path.empty()) {
+ vars["l"] += search_path;
+ if (search_path[search_path.size() - 1] != '/') {
vars["l"] += '/';
}
}
@@ -100,14 +100,14 @@ TString GetHeaderPrologue(grpc_generator::File* file,
? kCppGeneratorMessageHeaderExt
: params.message_header_extension;
- printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
+ printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
printer->Print(vars,
"// If you make any local change, they will be lost.\n");
printer->Print(vars, "// source: $filename$\n");
TString leading_comments = file->GetLeadingComments("//");
if (!leading_comments.empty()) {
printer->Print(vars, "// Original file comments:\n");
- printer->PrintRaw(leading_comments.c_str());
+ printer->PrintRaw(leading_comments.c_str());
}
printer->Print(vars, "#ifndef GRPC_$filename_identifier$__INCLUDED\n");
printer->Print(vars, "#define GRPC_$filename_identifier$__INCLUDED\n");
@@ -117,7 +117,7 @@ TString GetHeaderPrologue(grpc_generator::File* file,
printer->Print(vars, "#endif\n");
printer->Print(vars, "\n");
printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n");
- printer->Print(vars, file->additional_headers().c_str());
+ printer->Print(vars, file->additional_headers().c_str());
printer->Print(vars, "\n");
}
return output;
@@ -138,37 +138,37 @@ TString GetHeaderIncludes(grpc_generator::File* file,
auto printer = file->CreatePrinter(&output);
std::map<TString, TString> vars;
- if (!params.additional_header_includes.empty()) {
- PrintIncludes(printer.get(), params.additional_header_includes, false,
- "");
- }
+ if (!params.additional_header_includes.empty()) {
+ PrintIncludes(printer.get(), params.additional_header_includes, false,
+ "");
+ }
// TODO(vjpai): Remove port_platform.h from header list when callback API is
// fully de-experimentalized since we will no longer be using
// macros from it.
- static const char* headers_strs[] = {
+ static const char* headers_strs[] = {
"functional",
"grpc/impl/codegen/port_platform.h",
"grpcpp/impl/codegen/async_generic_service.h",
- "grpcpp/impl/codegen/async_stream.h",
- "grpcpp/impl/codegen/async_unary_call.h",
+ "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/message_allocator.h",
"grpcpp/impl/codegen/method_handler.h",
- "grpcpp/impl/codegen/proto_utils.h",
- "grpcpp/impl/codegen/rpc_method.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/service_type.h",
- "grpcpp/impl/codegen/status.h",
- "grpcpp/impl/codegen/stub_options.h",
+ "grpcpp/impl/codegen/service_type.h",
+ "grpcpp/impl/codegen/status.h",
+ "grpcpp/impl/codegen/stub_options.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);
+ 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()
@@ -205,38 +205,38 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer,
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
- struct {
+ struct {
TString prefix;
TString method_params; // extra arguments to method
TString raw_args; // extra arguments to raw version of method
- } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
- {"PrepareAsync", "", ""}};
-
+ } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
+ {"PrepareAsync", "", ""}};
+
if (is_public) {
if (method->NoStreaming()) {
printer->Print(
*vars,
"virtual ::grpc::Status $Method$(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response) = 0;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- printer->Print(
- *vars,
- "std::unique_ptr< "
- "::grpc::ClientAsyncResponseReaderInterface< $Response$>> "
- "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
- "const $Request$& request, "
- "::grpc::CompletionQueue* cq) {\n");
- printer->Indent();
- printer->Print(
- *vars,
- "return std::unique_ptr< "
- "::grpc::ClientAsyncResponseReaderInterface< $Response$>>("
- "$AsyncPrefix$$Method$Raw(context, request, cq));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
- } else if (ClientOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ printer->Print(
+ *vars,
+ "std::unique_ptr< "
+ "::grpc::ClientAsyncResponseReaderInterface< $Response$>> "
+ "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
+ "const $Request$& request, "
+ "::grpc::CompletionQueue* cq) {\n");
+ printer->Indent();
+ printer->Print(
+ *vars,
+ "return std::unique_ptr< "
+ "::grpc::ClientAsyncResponseReaderInterface< $Response$>>("
+ "$AsyncPrefix$$Method$Raw(context, request, cq));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
"std::unique_ptr< ::grpc::ClientWriterInterface< $Request$>>"
@@ -249,27 +249,27 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer,
"($Method$Raw(context, response));\n");
printer->Outdent();
printer->Print("}\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(
- *vars,
- "std::unique_ptr< ::grpc::ClientAsyncWriterInterface< $Request$>>"
- " $AsyncPrefix$$Method$(::grpc::ClientContext* context, "
- "$Response$* "
- "response, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Indent();
- printer->Print(*vars,
- "return std::unique_ptr< "
- "::grpc::ClientAsyncWriterInterface< $Request$>>("
- "$AsyncPrefix$$Method$Raw(context, response, "
- "cq$AsyncRawArgs$));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
- } else if (ServerOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(
+ *vars,
+ "std::unique_ptr< ::grpc::ClientAsyncWriterInterface< $Request$>>"
+ " $AsyncPrefix$$Method$(::grpc::ClientContext* context, "
+ "$Response$* "
+ "response, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Indent();
+ printer->Print(*vars,
+ "return std::unique_ptr< "
+ "::grpc::ClientAsyncWriterInterface< $Request$>>("
+ "$AsyncPrefix$$Method$Raw(context, response, "
+ "cq$AsyncRawArgs$));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
"std::unique_ptr< ::grpc::ClientReaderInterface< $Response$>>"
@@ -283,24 +283,24 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer,
printer->Outdent();
printer->Print("}\n");
for (auto& async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(
- *vars,
- "std::unique_ptr< ::grpc::ClientAsyncReaderInterface< $Response$>> "
- "$AsyncPrefix$$Method$("
- "::grpc::ClientContext* context, const $Request$& request, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Indent();
- printer->Print(
- *vars,
- "return std::unique_ptr< "
- "::grpc::ClientAsyncReaderInterface< $Response$>>("
- "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(
+ *vars,
+ "std::unique_ptr< ::grpc::ClientAsyncReaderInterface< $Response$>> "
+ "$AsyncPrefix$$Method$("
+ "::grpc::ClientContext* context, const $Request$& request, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Indent();
+ printer->Print(
+ *vars,
+ "return std::unique_ptr< "
+ "::grpc::ClientAsyncReaderInterface< $Response$>>("
+ "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
} else if (method->BidiStreaming()) {
printer->Print(*vars,
"std::unique_ptr< ::grpc::ClientReaderWriterInterface< "
@@ -314,125 +314,125 @@ void PrintHeaderClientMethodInterfaces(grpc_generator::Printer* printer,
"$Method$Raw(context));\n");
printer->Outdent();
printer->Print("}\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(
- *vars,
- "std::unique_ptr< "
- "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>> "
- "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Indent();
- printer->Print(
- *vars,
- "return std::unique_ptr< "
- "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>>("
- "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(
+ *vars,
+ "std::unique_ptr< "
+ "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>> "
+ "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Indent();
+ printer->Print(
+ *vars,
+ "return std::unique_ptr< "
+ "::grpc::ClientAsyncReaderWriterInterface< $Request$, $Response$>>("
+ "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
}
} else {
if (method->NoStreaming()) {
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- printer->Print(
- *vars,
- "virtual ::grpc::ClientAsyncResponseReaderInterface< $Response$>* "
- "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
- "const $Request$& request, "
- "::grpc::CompletionQueue* cq) = 0;\n");
- }
- } else if (ClientOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ printer->Print(
+ *vars,
+ "virtual ::grpc::ClientAsyncResponseReaderInterface< $Response$>* "
+ "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
+ "const $Request$& request, "
+ "::grpc::CompletionQueue* cq) = 0;\n");
+ }
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
"virtual ::grpc::ClientWriterInterface< $Request$>*"
" $Method$Raw("
"::grpc::ClientContext* context, $Response$* response) = 0;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- printer->Print(
- *vars,
- "virtual ::grpc::ClientAsyncWriterInterface< $Request$>*"
- " $AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
- "$Response$* response, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n");
- }
- } else if (ServerOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ printer->Print(
+ *vars,
+ "virtual ::grpc::ClientAsyncWriterInterface< $Request$>*"
+ " $AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
+ "$Response$* response, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n");
+ }
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
- "virtual ::grpc::ClientReaderInterface< $Response$>* "
- "$Method$Raw("
+ "virtual ::grpc::ClientReaderInterface< $Response$>* "
+ "$Method$Raw("
"::grpc::ClientContext* context, const $Request$& request) = 0;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- printer->Print(
- *vars,
- "virtual ::grpc::ClientAsyncReaderInterface< $Response$>* "
- "$AsyncPrefix$$Method$Raw("
- "::grpc::ClientContext* context, const $Request$& request, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n");
- }
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ printer->Print(
+ *vars,
+ "virtual ::grpc::ClientAsyncReaderInterface< $Response$>* "
+ "$AsyncPrefix$$Method$Raw("
+ "::grpc::ClientContext* context, const $Request$& request, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n");
+ }
} else if (method->BidiStreaming()) {
printer->Print(*vars,
"virtual ::grpc::ClientReaderWriterInterface< $Request$, "
"$Response$>* "
"$Method$Raw(::grpc::ClientContext* context) = 0;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- printer->Print(
- *vars,
- "virtual ::grpc::ClientAsyncReaderWriterInterface< "
- "$Request$, $Response$>* "
- "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n");
- }
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ printer->Print(
+ *vars,
+ "virtual ::grpc::ClientAsyncReaderWriterInterface< "
+ "$Request$, $Response$>* "
+ "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) = 0;\n");
+ }
}
}
}
-void PrintHeaderClientMethod(grpc_generator::Printer* printer,
- const grpc_generator::Method* method,
+void PrintHeaderClientMethod(grpc_generator::Printer* printer,
+ const grpc_generator::Method* method,
std::map<TString, TString>* vars,
bool is_public) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
- struct {
+ struct {
TString prefix;
TString method_params; // extra arguments to method
TString raw_args; // extra arguments to raw version of method
- } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
- {"PrepareAsync", "", ""}};
-
+ } async_prefixes[] = {{"Async", ", void* tag", ", tag"},
+ {"PrepareAsync", "", ""}};
+
if (is_public) {
if (method->NoStreaming()) {
printer->Print(
*vars,
"::grpc::Status $Method$(::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response) override;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- printer->Print(
- *vars,
- "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> "
- "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
- "const $Request$& request, "
- "::grpc::CompletionQueue* cq) {\n");
- printer->Indent();
- printer->Print(*vars,
- "return std::unique_ptr< "
- "::grpc::ClientAsyncResponseReader< $Response$>>("
- "$AsyncPrefix$$Method$Raw(context, request, cq));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
- } else if (ClientOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ printer->Print(
+ *vars,
+ "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> "
+ "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
+ "const $Request$& request, "
+ "::grpc::CompletionQueue* cq) {\n");
+ printer->Indent();
+ printer->Print(*vars,
+ "return std::unique_ptr< "
+ "::grpc::ClientAsyncResponseReader< $Response$>>("
+ "$AsyncPrefix$$Method$Raw(context, request, cq));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
"std::unique_ptr< ::grpc::ClientWriter< $Request$>>"
@@ -444,25 +444,25 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer,
"($Method$Raw(context, response));\n");
printer->Outdent();
printer->Print("}\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(*vars,
- "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>"
- " $AsyncPrefix$$Method$(::grpc::ClientContext* context, "
- "$Response$* response, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Indent();
- printer->Print(
- *vars,
- "return std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>("
- "$AsyncPrefix$$Method$Raw(context, response, "
- "cq$AsyncRawArgs$));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
- } else if (ServerOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(*vars,
+ "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>"
+ " $AsyncPrefix$$Method$(::grpc::ClientContext* context, "
+ "$Response$* response, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Indent();
+ printer->Print(
+ *vars,
+ "return std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>>("
+ "$AsyncPrefix$$Method$Raw(context, response, "
+ "cq$AsyncRawArgs$));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
"std::unique_ptr< ::grpc::ClientReader< $Response$>>"
@@ -475,24 +475,24 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer,
"($Method$Raw(context, request));\n");
printer->Outdent();
printer->Print("}\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(
- *vars,
- "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> "
- "$AsyncPrefix$$Method$("
- "::grpc::ClientContext* context, const $Request$& request, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Indent();
- printer->Print(
- *vars,
- "return std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>>("
- "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(
+ *vars,
+ "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> "
+ "$AsyncPrefix$$Method$("
+ "::grpc::ClientContext* context, const $Request$& request, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Indent();
+ printer->Print(
+ *vars,
+ "return std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>>("
+ "$AsyncPrefix$$Method$Raw(context, request, cq$AsyncRawArgs$));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
} else if (method->BidiStreaming()) {
printer->Print(
*vars,
@@ -505,80 +505,80 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer,
"$Method$Raw(context));\n");
printer->Outdent();
printer->Print("}\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(*vars,
- "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< "
- "$Request$, $Response$>> "
- "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Indent();
- printer->Print(
- *vars,
- "return std::unique_ptr< "
- "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>>("
- "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n");
- printer->Outdent();
- printer->Print("}\n");
- }
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(*vars,
+ "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< "
+ "$Request$, $Response$>> "
+ "$AsyncPrefix$$Method$(::grpc::ClientContext* context, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Indent();
+ printer->Print(
+ *vars,
+ "return std::unique_ptr< "
+ "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>>("
+ "$AsyncPrefix$$Method$Raw(context, cq$AsyncRawArgs$));\n");
+ printer->Outdent();
+ printer->Print("}\n");
+ }
}
} else {
if (method->NoStreaming()) {
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- printer->Print(
- *vars,
- "::grpc::ClientAsyncResponseReader< $Response$>* "
- "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
- "const $Request$& request, "
- "::grpc::CompletionQueue* cq) override;\n");
- }
- } else if (ClientOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ printer->Print(
+ *vars,
+ "::grpc::ClientAsyncResponseReader< $Response$>* "
+ "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
+ "const $Request$& request, "
+ "::grpc::CompletionQueue* cq) override;\n");
+ }
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::ClientWriter< $Request$>* $Method$Raw("
"::grpc::ClientContext* context, $Response$* response) "
"override;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(
- *vars,
- "::grpc::ClientAsyncWriter< $Request$>* $AsyncPrefix$$Method$Raw("
- "::grpc::ClientContext* context, $Response$* response, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n");
- }
- } else if (ServerOnlyStreaming(method)) {
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(
+ *vars,
+ "::grpc::ClientAsyncWriter< $Request$>* $AsyncPrefix$$Method$Raw("
+ "::grpc::ClientContext* context, $Response$* response, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n");
+ }
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::ClientReader< $Response$>* $Method$Raw("
"::grpc::ClientContext* context, const $Request$& request)"
" override;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(
- *vars,
- "::grpc::ClientAsyncReader< $Response$>* $AsyncPrefix$$Method$Raw("
- "::grpc::ClientContext* context, const $Request$& request, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n");
- }
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(
+ *vars,
+ "::grpc::ClientAsyncReader< $Response$>* $AsyncPrefix$$Method$Raw("
+ "::grpc::ClientContext* context, const $Request$& request, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n");
+ }
} else if (method->BidiStreaming()) {
printer->Print(*vars,
"::grpc::ClientReaderWriter< $Request$, $Response$>* "
"$Method$Raw(::grpc::ClientContext* context) override;\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
- printer->Print(
- *vars,
- "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* "
- "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n");
- }
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncRawArgs"] = async_prefix.raw_args;
+ printer->Print(
+ *vars,
+ "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* "
+ "$AsyncPrefix$$Method$Raw(::grpc::ClientContext* context, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) override;\n");
+ }
}
}
}
@@ -780,33 +780,33 @@ void PrintHeaderClientMethodCallbackEnd(
"return &async_stub_; }\n");
}
-void PrintHeaderClientMethodData(grpc_generator::Printer* printer,
- const grpc_generator::Method* method,
+void PrintHeaderClientMethodData(grpc_generator::Printer* printer,
+ const grpc_generator::Method* method,
std::map<TString, TString>* vars) {
(*vars)["Method"] = method->name();
- printer->Print(*vars,
- "const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n");
+ printer->Print(*vars,
+ "const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n");
}
-void PrintHeaderServerMethodSync(grpc_generator::Printer* printer,
- const grpc_generator::Method* method,
+void PrintHeaderServerMethodSync(grpc_generator::Printer* printer,
+ const grpc_generator::Method* method,
std::map<TString, TString>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
- printer->Print(method->GetLeadingComments("//").c_str());
+ printer->Print(method->GetLeadingComments("//").c_str());
if (method->NoStreaming()) {
printer->Print(*vars,
"virtual ::grpc::Status $Method$("
"::grpc::ServerContext* context, const $Request$* request, "
"$Response$* response);\n");
- } else if (ClientOnlyStreaming(method)) {
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"virtual ::grpc::Status $Method$("
"::grpc::ServerContext* context, "
"::grpc::ServerReader< $Request$>* reader, "
"$Response$* response);\n");
- } else if (ServerOnlyStreaming(method)) {
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"virtual ::grpc::Status $Method$("
"::grpc::ServerContext* context, const $Request$* request, "
@@ -819,7 +819,7 @@ void PrintHeaderServerMethodSync(grpc_generator::Printer* printer,
"::grpc::ServerReaderWriter< $Response$, $Request$>* stream);"
"\n");
}
- printer->Print(method->GetTrailingComments("//").c_str());
+ printer->Print(method->GetTrailingComments("//").c_str());
}
// Helper generator. Disables the sync API for Request and Response, then adds
@@ -849,7 +849,7 @@ void PrintHeaderServerAsyncMethodsHelper(
" ::grpc::Service::RequestAsyncUnary($Idx$, context, "
"request, response, new_call_cq, notification_cq, tag);\n");
printer->Print("}\n");
- } else if (ClientOnlyStreaming(method)) {
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
"// disable synchronous version of this method\n"
@@ -871,7 +871,7 @@ void PrintHeaderServerAsyncMethodsHelper(
" ::grpc::Service::RequestAsyncClientStreaming($Idx$, "
"context, reader, new_call_cq, notification_cq, tag);\n");
printer->Print("}\n");
- } else if (ServerOnlyStreaming(method)) {
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
"// disable synchronous version of this method\n"
@@ -1301,7 +1301,7 @@ void PrintHeaderServerMethodRawCallback(
}
void PrintHeaderServerMethodStreamedUnary(
- grpc_generator::Printer* printer, const grpc_generator::Method* method,
+ grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<TString, TString>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
@@ -1355,12 +1355,12 @@ void PrintHeaderServerMethodStreamedUnary(
}
void PrintHeaderServerMethodSplitStreaming(
- grpc_generator::Printer* printer, const grpc_generator::Method* method,
+ grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<TString, TString>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
- if (ServerOnlyStreaming(method)) {
+ if (ServerOnlyStreaming(method)) {
printer->Print(*vars, "template <class BaseClass>\n");
printer->Print(*vars,
"class WithSplitStreamingMethod_$Method$ : "
@@ -1442,7 +1442,7 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer,
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
- } else if (ClientOnlyStreaming(method)) {
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
"// disable synchronous version of this method\n"
@@ -1453,7 +1453,7 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer,
" abort();\n"
" return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n"
"}\n");
- } else if (ServerOnlyStreaming(method)) {
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
"// disable synchronous version of this method\n"
@@ -1511,23 +1511,23 @@ void PrintHeaderServerMethodRaw(grpc_generator::Printer* printer,
printer->Print(*vars, "};\n");
}
-void PrintHeaderService(grpc_generator::Printer* printer,
- const grpc_generator::Service* service,
+void PrintHeaderService(grpc_generator::Printer* printer,
+ const grpc_generator::Service* service,
std::map<TString, TString>* vars) {
(*vars)["Service"] = service->name();
- printer->Print(service->GetLeadingComments("//").c_str());
+ printer->Print(service->GetLeadingComments("//").c_str());
printer->Print(*vars,
"class $Service$ final {\n"
" public:\n");
printer->Indent();
- // Service metadata
- printer->Print(*vars,
- "static constexpr char const* service_full_name() {\n"
- " return \"$Package$$Service$\";\n"
- "}\n");
-
+ // Service metadata
+ printer->Print(*vars,
+ "static constexpr char const* service_full_name() {\n"
+ " return \"$Package$$Service$\";\n"
+ "}\n");
+
// Client side
printer->Print(
"class StubInterface {\n"
@@ -1535,10 +1535,10 @@ void PrintHeaderService(grpc_generator::Printer* printer,
printer->Indent();
printer->Print("virtual ~StubInterface() {}\n");
for (int i = 0; i < service->method_count(); ++i) {
- printer->Print(service->method(i)->GetLeadingComments("//").c_str());
+ printer->Print(service->method(i)->GetLeadingComments("//").c_str());
PrintHeaderClientMethodInterfaces(printer, service->method(i).get(), vars,
true);
- printer->Print(service->method(i)->GetTrailingComments("//").c_str());
+ printer->Print(service->method(i)->GetTrailingComments("//").c_str());
}
PrintHeaderClientMethodCallbackInterfacesStart(printer, vars);
for (int i = 0; i < service->method_count(); ++i) {
@@ -1562,8 +1562,8 @@ void PrintHeaderService(grpc_generator::Printer* printer,
" {\n public:\n");
printer->Indent();
printer->Print(
- "Stub(const std::shared_ptr< ::grpc::ChannelInterface>& "
- "channel);\n");
+ "Stub(const std::shared_ptr< ::grpc::ChannelInterface>& "
+ "channel);\n");
for (int i = 0; i < service->method_count(); ++i) {
PrintHeaderClientMethod(printer, service->method(i).get(), vars, true);
}
@@ -1705,15 +1705,15 @@ void PrintHeaderService(grpc_generator::Printer* printer,
printer->Print("typedef ");
for (int i = 0; i < service->method_count(); ++i) {
(*vars)["method_name"] = service->method(i)->name();
- auto method = service->method(i);
- if (ServerOnlyStreaming(method.get())) {
+ auto method = service->method(i);
+ if (ServerOnlyStreaming(method.get())) {
printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<");
}
}
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
- if (ServerOnlyStreaming(method.get())) {
+ auto method = service->method(i);
+ if (ServerOnlyStreaming(method.get())) {
printer->Print(" >");
}
}
@@ -1723,8 +1723,8 @@ void PrintHeaderService(grpc_generator::Printer* printer,
printer->Print("typedef ");
for (int i = 0; i < service->method_count(); ++i) {
(*vars)["method_name"] = service->method(i)->name();
- auto method = service->method(i);
- if (ServerOnlyStreaming(method.get())) {
+ auto method = service->method(i);
+ if (ServerOnlyStreaming(method.get())) {
printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<");
}
if (service->method(i)->NoStreaming()) {
@@ -1733,9 +1733,9 @@ void PrintHeaderService(grpc_generator::Printer* printer,
}
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
if (service->method(i)->NoStreaming() ||
- ServerOnlyStreaming(method.get())) {
+ ServerOnlyStreaming(method.get())) {
printer->Print(" >");
}
}
@@ -1743,7 +1743,7 @@ void PrintHeaderService(grpc_generator::Printer* printer,
printer->Outdent();
printer->Print("};\n");
- printer->Print(service->GetTrailingComments("//").c_str());
+ printer->Print(service->GetTrailingComments("//").c_str());
}
TString GetHeaderServices(grpc_generator::File* file,
@@ -1801,7 +1801,7 @@ TString GetHeaderEpilogue(grpc_generator::File* file,
printer->Print(vars, "\n");
printer->Print(vars, "#endif // GRPC_$filename_identifier$__INCLUDED\n");
- printer->Print(file->GetTrailingComments("//").c_str());
+ printer->Print(file->GetTrailingComments("//").c_str());
}
return output;
}
@@ -1819,9 +1819,9 @@ TString GetSourcePrologue(grpc_generator::File* file,
vars["message_header_ext"] = params.message_header_extension.empty()
? kCppGeneratorMessageHeaderExt
: params.message_header_extension;
- vars["service_header_ext"] = kCppGeneratorServiceHeaderExt;
+ vars["service_header_ext"] = kCppGeneratorServiceHeaderExt;
- printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
+ printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
printer->Print(vars,
"// If you make any local change, they will be lost.\n");
printer->Print(vars, "// source: $filename$\n\n");
@@ -1840,24 +1840,24 @@ TString GetSourceIncludes(grpc_generator::File* file,
// Scope the output stream so it closes and finalizes output to the string.
auto printer = file->CreatePrinter(&output);
std::map<TString, TString> vars;
- static const char* headers_strs[] = {
+ static const char* headers_strs[] = {
"functional",
- "grpcpp/impl/codegen/async_stream.h",
- "grpcpp/impl/codegen/async_unary_call.h",
- "grpcpp/impl/codegen/channel_interface.h",
- "grpcpp/impl/codegen/client_unary_call.h",
+ "grpcpp/impl/codegen/async_stream.h",
+ "grpcpp/impl/codegen/async_unary_call.h",
+ "grpcpp/impl/codegen/channel_interface.h",
+ "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/rpc_service_method.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/service_type.h",
- "grpcpp/impl/codegen/sync_stream.h"};
+ "grpcpp/impl/codegen/service_type.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);
+ PrintIncludes(printer.get(), headers, params.use_system_headers,
+ params.grpc_search_path);
if (!file->package().empty()) {
std::vector<TString> parts = file->package_parts();
@@ -1873,28 +1873,28 @@ TString GetSourceIncludes(grpc_generator::File* file,
return output;
}
-void PrintSourceClientMethod(grpc_generator::Printer* printer,
- const grpc_generator::Method* method,
+void PrintSourceClientMethod(grpc_generator::Printer* printer,
+ const grpc_generator::Method* method,
std::map<TString, TString>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
- struct {
+ struct {
TString prefix;
TString start; // bool literal expressed as string
TString method_params; // extra arguments to method
TString create_args; // extra arguments to creator
- } async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"},
- {"PrepareAsync", "false", "", ", nullptr"}};
+ } async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"},
+ {"PrepareAsync", "false", "", ", nullptr"}};
if (method->NoStreaming()) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Stub::$Method$("
"::grpc::ClientContext* context, "
"const $Request$& request, $Response$* response) {\n");
printer->Print(*vars,
- " return ::grpc::internal::BlockingUnaryCall"
- "(channel_.get(), rpcmethod_$Method$_, "
- "context, request, response);\n}\n\n");
+ " return ::grpc::internal::BlockingUnaryCall"
+ "(channel_.get(), rpcmethod_$Method$_, "
+ "context, request, response);\n}\n\n");
printer->Print(*vars,
"void $ns$$Service$::Stub::experimental_async::$Method$("
@@ -1941,7 +1941,7 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
" result->StartCall();\n"
" return result;\n"
"}\n\n");
- } else if (ClientOnlyStreaming(method)) {
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::ClientWriter< $Request$>* "
"$ns$$Service$::Stub::$Method$Raw("
@@ -1968,27 +1968,27 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"context, response, reactor);\n"
"}\n\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncStart"] = async_prefix.start;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncCreateArgs"] = async_prefix.create_args;
- printer->Print(*vars,
- "::grpc::ClientAsyncWriter< $Request$>* "
- "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw("
- "::grpc::ClientContext* context, $Response$* response, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Print(
- *vars,
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncStart"] = async_prefix.start;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncCreateArgs"] = async_prefix.create_args;
+ printer->Print(*vars,
+ "::grpc::ClientAsyncWriter< $Request$>* "
+ "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw("
+ "::grpc::ClientContext* context, $Response$* response, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Print(
+ *vars,
" return ::grpc::internal::ClientAsyncWriterFactory< $Request$>"
- "::Create(channel_.get(), cq, "
- "rpcmethod_$Method$_, "
- "context, response, $AsyncStart$$AsyncCreateArgs$);\n"
- "}\n\n");
- }
- } else if (ServerOnlyStreaming(method)) {
- printer->Print(
- *vars,
+ "::Create(channel_.get(), cq, "
+ "rpcmethod_$Method$_, "
+ "context, response, $AsyncStart$$AsyncCreateArgs$);\n"
+ "}\n\n");
+ }
+ } else if (ServerOnlyStreaming(method)) {
+ printer->Print(
+ *vars,
"::grpc::ClientReader< $Response$>* "
"$ns$$Service$::Stub::$Method$Raw("
"::grpc::ClientContext* context, const $Request$& request) {\n");
@@ -2014,17 +2014,17 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"context, request, reactor);\n"
"}\n\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncStart"] = async_prefix.start;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncCreateArgs"] = async_prefix.create_args;
- printer->Print(
- *vars,
- "::grpc::ClientAsyncReader< $Response$>* "
- "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw("
- "::grpc::ClientContext* context, const $Request$& request, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncStart"] = async_prefix.start;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncCreateArgs"] = async_prefix.create_args;
+ printer->Print(
+ *vars,
+ "::grpc::ClientAsyncReader< $Response$>* "
+ "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw("
+ "::grpc::ClientContext* context, const $Request$& request, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
printer->Print(*vars,
" return ::grpc::internal::ClientAsyncReaderFactory< "
"$Response$>"
@@ -2032,7 +2032,7 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"rpcmethod_$Method$_, "
"context, request, $AsyncStart$$AsyncCreateArgs$);\n"
"}\n\n");
- }
+ }
} else if (method->BidiStreaming()) {
printer->Print(
*vars,
@@ -2040,7 +2040,7 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"$ns$$Service$::Stub::$Method$Raw(::grpc::ClientContext* context) {\n");
printer->Print(*vars,
" return ::grpc::internal::ClientReaderWriterFactory< "
- "$Request$, $Response$>::Create("
+ "$Request$, $Response$>::Create("
"channel_.get(), "
"rpcmethod_$Method$_, "
"context);\n"
@@ -2060,30 +2060,30 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer,
"context, reactor);\n"
"}\n\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncStart"] = async_prefix.start;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["AsyncCreateArgs"] = async_prefix.create_args;
- printer->Print(*vars,
- "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* "
- "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(::grpc::"
- "ClientContext* context, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
- printer->Print(*vars,
- " return "
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncStart"] = async_prefix.start;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["AsyncCreateArgs"] = async_prefix.create_args;
+ printer->Print(*vars,
+ "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* "
+ "$ns$$Service$::Stub::$AsyncPrefix$$Method$Raw(::grpc::"
+ "ClientContext* context, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$) {\n");
+ printer->Print(*vars,
+ " return "
"::grpc::internal::ClientAsyncReaderWriterFactory< "
- "$Request$, $Response$>::Create("
- "channel_.get(), cq, "
- "rpcmethod_$Method$_, "
- "context, $AsyncStart$$AsyncCreateArgs$);\n"
- "}\n\n");
- }
+ "$Request$, $Response$>::Create("
+ "channel_.get(), cq, "
+ "rpcmethod_$Method$_, "
+ "context, $AsyncStart$$AsyncCreateArgs$);\n"
+ "}\n\n");
+ }
}
}
-void PrintSourceServerMethod(grpc_generator::Printer* printer,
- const grpc_generator::Method* method,
+void PrintSourceServerMethod(grpc_generator::Printer* printer,
+ const grpc_generator::Method* method,
std::map<TString, TString>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
@@ -2100,7 +2100,7 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer,
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
printer->Print("}\n\n");
- } else if (ClientOnlyStreaming(method)) {
+ } else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
"::grpc::ServerContext* context, "
@@ -2113,7 +2113,7 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer,
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED, \"\");\n");
printer->Print("}\n\n");
- } else if (ServerOnlyStreaming(method)) {
+ } else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Service::$Method$("
"::grpc::ServerContext* context, "
@@ -2141,8 +2141,8 @@ void PrintSourceServerMethod(grpc_generator::Printer* printer,
}
}
-void PrintSourceService(grpc_generator::Printer* printer,
- const grpc_generator::Service* service,
+void PrintSourceService(grpc_generator::Printer* printer,
+ const grpc_generator::Service* service,
std::map<TString, TString>* vars) {
(*vars)["Service"] = service->name();
@@ -2159,8 +2159,8 @@ void PrintSourceService(grpc_generator::Printer* printer,
printer->Print(*vars,
"std::unique_ptr< $ns$$Service$::Stub> $ns$$Service$::NewStub("
"const std::shared_ptr< ::grpc::ChannelInterface>& channel, "
- "const ::grpc::StubOptions& options) {\n"
- " (void)options;\n"
+ "const ::grpc::StubOptions& options) {\n"
+ " (void)options;\n"
" std::unique_ptr< $ns$$Service$::Stub> stub(new "
"$ns$$Service$::Stub(channel));\n"
" return stub;\n"
@@ -2179,9 +2179,9 @@ void PrintSourceService(grpc_generator::Printer* printer,
// NOTE: There is no reason to consider streamed-unary as a separate
// category here since this part is setting up the client-side stub
// and this appears as a NORMAL_RPC from the client-side.
- } else if (ClientOnlyStreaming(method.get())) {
+ } else if (ClientOnlyStreaming(method.get())) {
(*vars)["StreamingType"] = "CLIENT_STREAMING";
- } else if (ServerOnlyStreaming(method.get())) {
+ } else if (ServerOnlyStreaming(method.get())) {
(*vars)["StreamingType"] = "SERVER_STREAMING";
} else {
(*vars)["StreamingType"] = "BIDI_STREAMING";
@@ -2189,7 +2189,7 @@ void PrintSourceService(grpc_generator::Printer* printer,
printer->Print(*vars,
", rpcmethod_$Method$_("
"$prefix$$Service$_method_names[$Idx$], "
- "::grpc::internal::RpcMethod::$StreamingType$, "
+ "::grpc::internal::RpcMethod::$StreamingType$, "
"channel"
")\n");
}
@@ -2212,10 +2212,10 @@ void PrintSourceService(grpc_generator::Printer* printer,
if (method->NoStreaming()) {
printer->Print(
*vars,
- "AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
+ "AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
- " ::grpc::internal::RpcMethod::NORMAL_RPC,\n"
- " new ::grpc::internal::RpcMethodHandler< $ns$$Service$::Service, "
+ " ::grpc::internal::RpcMethod::NORMAL_RPC,\n"
+ " new ::grpc::internal::RpcMethodHandler< $ns$$Service$::Service, "
"$Request$, "
"$Response$>(\n"
" []($ns$$Service$::Service* service,\n"
@@ -2224,13 +2224,13 @@ void PrintSourceService(grpc_generator::Printer* printer,
" $Response$* resp) {\n"
" return service->$Method$(ctx, req, resp);\n"
" }, this)));\n");
- } else if (ClientOnlyStreaming(method.get())) {
+ } else if (ClientOnlyStreaming(method.get())) {
printer->Print(
*vars,
- "AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
+ "AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
- " ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n"
- " new ::grpc::internal::ClientStreamingHandler< "
+ " ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n"
+ " new ::grpc::internal::ClientStreamingHandler< "
"$ns$$Service$::Service, $Request$, $Response$>(\n"
" []($ns$$Service$::Service* service,\n"
" ::grpc::ServerContext* ctx,\n"
@@ -2238,13 +2238,13 @@ void PrintSourceService(grpc_generator::Printer* printer,
" $Response$* resp) {\n"
" return service->$Method$(ctx, reader, resp);\n"
" }, this)));\n");
- } else if (ServerOnlyStreaming(method.get())) {
+ } else if (ServerOnlyStreaming(method.get())) {
printer->Print(
*vars,
- "AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
+ "AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
- " ::grpc::internal::RpcMethod::SERVER_STREAMING,\n"
- " new ::grpc::internal::ServerStreamingHandler< "
+ " ::grpc::internal::RpcMethod::SERVER_STREAMING,\n"
+ " new ::grpc::internal::ServerStreamingHandler< "
"$ns$$Service$::Service, $Request$, $Response$>(\n"
" []($ns$$Service$::Service* service,\n"
" ::grpc::ServerContext* ctx,\n"
@@ -2325,29 +2325,29 @@ TString GetSourceEpilogue(grpc_generator::File* file,
return temp;
}
-// TODO(mmukhi): Make sure we need parameters or not.
+// TODO(mmukhi): Make sure we need parameters or not.
TString GetMockPrologue(grpc_generator::File* file,
const Parameters& params) {
TString output;
- {
- // Scope the output stream so it closes and finalizes output to the string.
- auto printer = file->CreatePrinter(&output);
+ {
+ // Scope the output stream so it closes and finalizes output to the string.
+ auto printer = file->CreatePrinter(&output);
std::map<TString, TString> vars;
-
- vars["filename"] = file->filename();
- vars["filename_base"] = file->filename_without_ext();
+
+ 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["service_header_ext"] = kCppGeneratorServiceHeaderExt;
-
- printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
- printer->Print(vars,
- "// If you make any local change, they will be lost.\n");
- printer->Print(vars, "// source: $filename$\n\n");
-
- printer->Print(vars, "#include \"$filename_base$$message_header_ext$\"\n");
- printer->Print(vars, "#include \"$filename_base$$service_header_ext$\"\n");
+ vars["service_header_ext"] = kCppGeneratorServiceHeaderExt;
+
+ printer->Print(vars, "// Generated by the gRPC C++ plugin.\n");
+ printer->Print(vars,
+ "// If you make any local change, they will be lost.\n");
+ printer->Print(vars, "// source: $filename$\n\n");
+
+ 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) {
const std::vector<TString> import_names = file->GetImportNames();
for (const auto& import_name : import_names) {
@@ -2356,202 +2356,202 @@ TString GetMockPrologue(grpc_generator::File* file,
}
printer->PrintRaw("\n");
}
- printer->Print(vars, file->additional_headers().c_str());
- printer->Print(vars, "\n");
- }
- return output;
-}
-
-// TODO(mmukhi): Add client-stream and completion-queue headers.
+ printer->Print(vars, file->additional_headers().c_str());
+ printer->Print(vars, "\n");
+ }
+ return output;
+}
+
+// TODO(mmukhi): Add client-stream and completion-queue headers.
TString GetMockIncludes(grpc_generator::File* file,
const Parameters& params) {
TString output;
- {
- // Scope the output stream so it closes and finalizes output to the string.
- auto printer = file->CreatePrinter(&output);
+ {
+ // Scope the output stream so it closes and finalizes output to the string.
+ auto printer = file->CreatePrinter(&output);
std::map<TString, TString> vars;
-
- static const char* headers_strs[] = {
- "grpcpp/impl/codegen/async_stream.h",
- "grpcpp/impl/codegen/sync_stream.h",
- };
+
+ static const char* headers_strs[] = {
+ "grpcpp/impl/codegen/async_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);
-
+ PrintIncludes(printer.get(), headers, params.use_system_headers,
+ params.grpc_search_path);
+
std::vector<TString> gmock_header;
- if (params.gmock_search_path.empty()) {
- gmock_header.push_back("gmock/gmock.h");
- PrintIncludes(printer.get(), gmock_header, params.use_system_headers,
- params.grpc_search_path);
- } else {
- gmock_header.push_back("gmock.h");
- // We use local includes when a gmock_search_path is given
- PrintIncludes(printer.get(), gmock_header, false,
- params.gmock_search_path);
- }
-
- if (!file->package().empty()) {
+ if (params.gmock_search_path.empty()) {
+ gmock_header.push_back("gmock/gmock.h");
+ PrintIncludes(printer.get(), gmock_header, params.use_system_headers,
+ params.grpc_search_path);
+ } else {
+ gmock_header.push_back("gmock.h");
+ // We use local includes when a gmock_search_path is given
+ PrintIncludes(printer.get(), gmock_header, false,
+ params.gmock_search_path);
+ }
+
+ if (!file->package().empty()) {
std::vector<TString> parts = file->package_parts();
-
- for (auto part = parts.begin(); part != parts.end(); part++) {
- vars["part"] = *part;
- printer->Print(vars, "namespace $part$ {\n");
- }
- }
-
- printer->Print(vars, "\n");
- }
- return output;
-}
-
-void PrintMockClientMethods(grpc_generator::Printer* printer,
- const grpc_generator::Method* method,
+
+ for (auto part = parts.begin(); part != parts.end(); part++) {
+ vars["part"] = *part;
+ printer->Print(vars, "namespace $part$ {\n");
+ }
+ }
+
+ printer->Print(vars, "\n");
+ }
+ return output;
+}
+
+void PrintMockClientMethods(grpc_generator::Printer* printer,
+ const grpc_generator::Method* method,
std::map<TString, TString>* vars) {
- (*vars)["Method"] = method->name();
- (*vars)["Request"] = method->input_type_name();
- (*vars)["Response"] = method->output_type_name();
-
- struct {
+ (*vars)["Method"] = method->name();
+ (*vars)["Request"] = method->input_type_name();
+ (*vars)["Response"] = method->output_type_name();
+
+ struct {
TString prefix;
TString method_params; // extra arguments to method
- int extra_method_param_count;
- } async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}};
-
- if (method->NoStreaming()) {
- printer->Print(
- *vars,
- "MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, "
- "const $Request$& request, $Response$* response));\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- printer->Print(
- *vars,
- "MOCK_METHOD3($AsyncPrefix$$Method$Raw, "
- "::grpc::ClientAsyncResponseReaderInterface< $Response$>*"
- "(::grpc::ClientContext* context, const $Request$& request, "
- "::grpc::CompletionQueue* cq));\n");
- }
- } else if (ClientOnlyStreaming(method)) {
- printer->Print(
- *vars,
- "MOCK_METHOD2($Method$Raw, "
- "::grpc::ClientWriterInterface< $Request$>*"
- "(::grpc::ClientContext* context, $Response$* response));\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["MockArgs"] =
+ int extra_method_param_count;
+ } async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}};
+
+ if (method->NoStreaming()) {
+ printer->Print(
+ *vars,
+ "MOCK_METHOD3($Method$, ::grpc::Status(::grpc::ClientContext* context, "
+ "const $Request$& request, $Response$* response));\n");
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ printer->Print(
+ *vars,
+ "MOCK_METHOD3($AsyncPrefix$$Method$Raw, "
+ "::grpc::ClientAsyncResponseReaderInterface< $Response$>*"
+ "(::grpc::ClientContext* context, const $Request$& request, "
+ "::grpc::CompletionQueue* cq));\n");
+ }
+ } else if (ClientOnlyStreaming(method)) {
+ printer->Print(
+ *vars,
+ "MOCK_METHOD2($Method$Raw, "
+ "::grpc::ClientWriterInterface< $Request$>*"
+ "(::grpc::ClientContext* context, $Response$* response));\n");
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["MockArgs"] =
ToString(3 + async_prefix.extra_method_param_count);
- printer->Print(*vars,
- "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
- "::grpc::ClientAsyncWriterInterface< $Request$>*"
- "(::grpc::ClientContext* context, $Response$* response, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n");
- }
- } else if (ServerOnlyStreaming(method)) {
- printer->Print(
- *vars,
- "MOCK_METHOD2($Method$Raw, "
- "::grpc::ClientReaderInterface< $Response$>*"
- "(::grpc::ClientContext* context, const $Request$& request));\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["MockArgs"] =
+ printer->Print(*vars,
+ "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
+ "::grpc::ClientAsyncWriterInterface< $Request$>*"
+ "(::grpc::ClientContext* context, $Response$* response, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n");
+ }
+ } else if (ServerOnlyStreaming(method)) {
+ printer->Print(
+ *vars,
+ "MOCK_METHOD2($Method$Raw, "
+ "::grpc::ClientReaderInterface< $Response$>*"
+ "(::grpc::ClientContext* context, const $Request$& request));\n");
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["MockArgs"] =
ToString(3 + async_prefix.extra_method_param_count);
- printer->Print(
- *vars,
- "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
- "::grpc::ClientAsyncReaderInterface< $Response$>*"
- "(::grpc::ClientContext* context, const $Request$& request, "
- "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n");
- }
- } else if (method->BidiStreaming()) {
- printer->Print(
- *vars,
- "MOCK_METHOD1($Method$Raw, "
- "::grpc::ClientReaderWriterInterface< $Request$, $Response$>*"
- "(::grpc::ClientContext* context));\n");
- for (auto async_prefix : async_prefixes) {
- (*vars)["AsyncPrefix"] = async_prefix.prefix;
- (*vars)["AsyncMethodParams"] = async_prefix.method_params;
- (*vars)["MockArgs"] =
+ printer->Print(
+ *vars,
+ "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
+ "::grpc::ClientAsyncReaderInterface< $Response$>*"
+ "(::grpc::ClientContext* context, const $Request$& request, "
+ "::grpc::CompletionQueue* cq$AsyncMethodParams$));\n");
+ }
+ } else if (method->BidiStreaming()) {
+ printer->Print(
+ *vars,
+ "MOCK_METHOD1($Method$Raw, "
+ "::grpc::ClientReaderWriterInterface< $Request$, $Response$>*"
+ "(::grpc::ClientContext* context));\n");
+ for (auto async_prefix : async_prefixes) {
+ (*vars)["AsyncPrefix"] = async_prefix.prefix;
+ (*vars)["AsyncMethodParams"] = async_prefix.method_params;
+ (*vars)["MockArgs"] =
ToString(2 + async_prefix.extra_method_param_count);
- printer->Print(
- *vars,
- "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
+ printer->Print(
+ *vars,
+ "MOCK_METHOD$MockArgs$($AsyncPrefix$$Method$Raw, "
"::grpc::ClientAsyncReaderWriterInterface<$Request$, "
"$Response$>*"
- "(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq"
- "$AsyncMethodParams$));\n");
- }
- }
-}
-
-void PrintMockService(grpc_generator::Printer* printer,
- const grpc_generator::Service* service,
+ "(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq"
+ "$AsyncMethodParams$));\n");
+ }
+ }
+}
+
+void PrintMockService(grpc_generator::Printer* printer,
+ const grpc_generator::Service* service,
std::map<TString, TString>* vars) {
- (*vars)["Service"] = service->name();
-
- printer->Print(*vars,
- "class Mock$Service$Stub : public $Service$::StubInterface {\n"
- " public:\n");
- printer->Indent();
- for (int i = 0; i < service->method_count(); ++i) {
- PrintMockClientMethods(printer, service->method(i).get(), vars);
- }
- printer->Outdent();
- printer->Print("};\n");
-}
-
+ (*vars)["Service"] = service->name();
+
+ printer->Print(*vars,
+ "class Mock$Service$Stub : public $Service$::StubInterface {\n"
+ " public:\n");
+ printer->Indent();
+ for (int i = 0; i < service->method_count(); ++i) {
+ PrintMockClientMethods(printer, service->method(i).get(), vars);
+ }
+ printer->Outdent();
+ printer->Print("};\n");
+}
+
TString GetMockServices(grpc_generator::File* file,
const Parameters& params) {
TString output;
- {
- // Scope the output stream so it closes and finalizes output to the string.
- auto printer = file->CreatePrinter(&output);
+ {
+ // Scope the output stream so it closes and finalizes output to the string.
+ auto printer = file->CreatePrinter(&output);
std::map<TString, TString> vars;
- // Package string is empty or ends with a dot. It is used to fully qualify
- // method names.
- vars["Package"] = file->package();
- if (!file->package().empty()) {
- vars["Package"].append(".");
- }
-
- if (!params.services_namespace.empty()) {
- vars["services_namespace"] = params.services_namespace;
- printer->Print(vars, "\nnamespace $services_namespace$ {\n\n");
- }
-
- for (int i = 0; i < file->service_count(); i++) {
- PrintMockService(printer.get(), file->service(i).get(), &vars);
- printer->Print("\n");
- }
-
- if (!params.services_namespace.empty()) {
- printer->Print(vars, "} // namespace $services_namespace$\n\n");
- }
- }
- return output;
-}
-
+ // Package string is empty or ends with a dot. It is used to fully qualify
+ // method names.
+ vars["Package"] = file->package();
+ if (!file->package().empty()) {
+ vars["Package"].append(".");
+ }
+
+ if (!params.services_namespace.empty()) {
+ vars["services_namespace"] = params.services_namespace;
+ printer->Print(vars, "\nnamespace $services_namespace$ {\n\n");
+ }
+
+ for (int i = 0; i < file->service_count(); i++) {
+ PrintMockService(printer.get(), file->service(i).get(), &vars);
+ printer->Print("\n");
+ }
+
+ if (!params.services_namespace.empty()) {
+ printer->Print(vars, "} // namespace $services_namespace$\n\n");
+ }
+ }
+ return output;
+}
+
TString GetMockEpilogue(grpc_generator::File* file,
const Parameters& /*params*/) {
TString temp;
-
- if (!file->package().empty()) {
+
+ if (!file->package().empty()) {
std::vector<TString> parts = file->package_parts();
-
- for (auto part = parts.begin(); part != parts.end(); part++) {
- temp.append("} // namespace ");
- temp.append(*part);
- temp.append("\n");
- }
- temp.append("\n");
- }
-
- return temp;
-}
-
+
+ for (auto part = parts.begin(); part != parts.end(); part++) {
+ temp.append("} // namespace ");
+ temp.append(*part);
+ temp.append("\n");
+ }
+ temp.append("\n");
+ }
+
+ return temp;
+}
+
} // namespace grpc_cpp_generator
diff --git a/contrib/libs/grpc/src/compiler/cpp_generator.h b/contrib/libs/grpc/src/compiler/cpp_generator.h
index 606b850a874..331a932bf9d 100644
--- a/contrib/libs/grpc/src/compiler/cpp_generator.h
+++ b/contrib/libs/grpc/src/compiler/cpp_generator.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -28,7 +28,7 @@
#include <vector>
#include "src/compiler/config.h"
-#include "src/compiler/schema_interface.h"
+#include "src/compiler/schema_interface.h"
#ifdef GRPC_CUSTOM_STRING
#warning GRPC_CUSTOM_STRING is no longer supported. Please use TString.
@@ -53,11 +53,11 @@ struct Parameters {
bool use_system_headers;
// Prefix to any grpc include
TString grpc_search_path;
- // Generate Google Mock code to facilitate unit testing.
- bool generate_mock_code;
- // Google Mock search path, when non-empty, local includes will be used.
+ // Generate Google Mock code to facilitate unit testing.
+ bool generate_mock_code;
+ // Google Mock search path, when non-empty, local includes will be used.
TString gmock_search_path;
- // *EXPERIMENTAL* Additional include files in grpc.pb.h
+ // *EXPERIMENTAL* Additional include files in grpc.pb.h
std::vector<TString> additional_header_includes;
// By default, use "pb.h"
TString message_header_extension;
@@ -65,67 +65,67 @@ struct Parameters {
bool include_import_headers;
};
-// Return the prologue of the generated header file.
+// Return the prologue of the generated header file.
TString GetHeaderPrologue(grpc_generator::File* file,
const Parameters& params);
-// Return the includes needed for generated header file.
+// Return the includes needed for generated header file.
TString GetHeaderIncludes(grpc_generator::File* file,
const Parameters& params);
-// Return the includes needed for generated source file.
+// Return the includes needed for generated source file.
TString GetSourceIncludes(grpc_generator::File* file,
const Parameters& params);
-// Return the epilogue of the generated header file.
+// Return the epilogue of the generated header file.
TString GetHeaderEpilogue(grpc_generator::File* file,
const Parameters& params);
-// Return the prologue of the generated source file.
+// Return the prologue of the generated source file.
TString GetSourcePrologue(grpc_generator::File* file,
const Parameters& params);
-// Return the services for generated header file.
+// Return the services for generated header file.
TString GetHeaderServices(grpc_generator::File* file,
const Parameters& params);
-// Return the services for generated source file.
+// Return the services for generated source file.
TString GetSourceServices(grpc_generator::File* file,
const Parameters& params);
-// Return the epilogue of the generated source file.
+// Return the epilogue of the generated source file.
TString GetSourceEpilogue(grpc_generator::File* file,
const Parameters& params);
-// Return the prologue of the generated mock file.
+// Return the prologue of the generated mock file.
TString GetMockPrologue(grpc_generator::File* file,
const Parameters& params);
-// Return the includes needed for generated mock file.
+// Return the includes needed for generated mock file.
TString GetMockIncludes(grpc_generator::File* file,
const Parameters& params);
-// Return the services for generated mock file.
+// Return the services for generated mock file.
TString GetMockServices(grpc_generator::File* file,
const Parameters& params);
-// Return the epilogue of generated mock file.
+// Return the epilogue of generated mock file.
TString GetMockEpilogue(grpc_generator::File* file,
const Parameters& params);
-// Return the prologue of the generated mock file.
+// Return the prologue of the generated mock file.
TString GetMockPrologue(grpc_generator::File* file,
const Parameters& params);
-// Return the includes needed for generated mock file.
+// Return the includes needed for generated mock file.
TString GetMockIncludes(grpc_generator::File* file,
const Parameters& params);
-// Return the services for generated mock file.
+// Return the services for generated mock file.
TString GetMockServices(grpc_generator::File* file,
const Parameters& params);
-// Return the epilogue of generated mock file.
+// Return the epilogue of generated mock file.
TString GetMockEpilogue(grpc_generator::File* file,
const Parameters& params);
diff --git a/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h b/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h
index 2e34d53a65d..9605e4dd74e 100644
--- a/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/cpp_generator_helpers.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -20,7 +20,7 @@
#define GRPC_INTERNAL_COMPILER_CPP_GENERATOR_HELPERS_H
#include <map>
-
+
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
@@ -38,7 +38,7 @@ inline TString ClassName(const grpc::protobuf::Descriptor* descriptor,
bool qualified) {
// Find "outer", the descriptor of the top-level message in which
// "descriptor" is embedded.
- const grpc::protobuf::Descriptor* outer = descriptor;
+ const grpc::protobuf::Descriptor* outer = descriptor;
while (outer->containing_type() != NULL) outer = outer->containing_type();
const TString& outer_name = outer->full_name();
diff --git a/contrib/libs/grpc/src/compiler/cpp_plugin.cc b/contrib/libs/grpc/src/compiler/cpp_plugin.cc
index 2de2745445f..15a2bcaf24a 100644
--- a/contrib/libs/grpc/src/compiler/cpp_plugin.cc
+++ b/contrib/libs/grpc/src/compiler/cpp_plugin.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -20,7 +20,7 @@
//
#include "src/compiler/cpp_plugin.h"
-int main(int argc, char* argv[]) {
+int main(int argc, char* argv[]) {
CppGrpcGenerator generator;
return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
}
diff --git a/contrib/libs/grpc/src/compiler/csharp_generator.cc b/contrib/libs/grpc/src/compiler/csharp_generator.cc
index 3b7107c4c48..cfc757a00c5 100644
--- a/contrib/libs/grpc/src/compiler/csharp_generator.cc
+++ b/contrib/libs/grpc/src/compiler/csharp_generator.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -25,19 +25,19 @@
#include "src/compiler/csharp_generator.h"
#include "src/compiler/csharp_generator_helpers.h"
-using google::protobuf::compiler::csharp::GetClassName;
+using google::protobuf::compiler::csharp::GetClassName;
using google::protobuf::compiler::csharp::GetFileNamespace;
using google::protobuf::compiler::csharp::GetReflectionClassName;
-using grpc::protobuf::Descriptor;
+using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
-using grpc::protobuf::MethodDescriptor;
+using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using grpc_generator::GetMethodType;
using grpc_generator::MethodType;
-using grpc_generator::METHODTYPE_BIDI_STREAMING;
-using grpc_generator::METHODTYPE_CLIENT_STREAMING;
+using grpc_generator::METHODTYPE_BIDI_STREAMING;
+using grpc_generator::METHODTYPE_CLIENT_STREAMING;
using grpc_generator::METHODTYPE_NO_STREAMING;
using grpc_generator::METHODTYPE_SERVER_STREAMING;
using grpc_generator::StringReplace;
@@ -52,7 +52,7 @@ namespace {
// Currently, we cannot easily reuse the functionality as
// google/protobuf/compiler/csharp/csharp_doc_comment.h is not a public header.
// TODO(jtattermusch): reuse the functionality from google/protobuf.
-bool GenerateDocCommentBodyImpl(grpc::protobuf::io::Printer* printer,
+bool GenerateDocCommentBodyImpl(grpc::protobuf::io::Printer* printer,
grpc::protobuf::SourceLocation location) {
TString comments = location.leading_comments.empty()
? location.trailing_comments
@@ -99,8 +99,8 @@ bool GenerateDocCommentBodyImpl(grpc::protobuf::io::Printer* printer,
}
template <typename DescriptorType>
-bool GenerateDocCommentBody(grpc::protobuf::io::Printer* printer,
- const DescriptorType* descriptor) {
+bool GenerateDocCommentBody(grpc::protobuf::io::Printer* printer,
+ const DescriptorType* descriptor) {
grpc::protobuf::SourceLocation location;
if (!descriptor->GetSourceLocation(&location)) {
return false;
@@ -108,8 +108,8 @@ bool GenerateDocCommentBody(grpc::protobuf::io::Printer* printer,
return GenerateDocCommentBodyImpl(printer, location);
}
-void GenerateDocCommentServerMethod(grpc::protobuf::io::Printer* printer,
- const MethodDescriptor* method) {
+void GenerateDocCommentServerMethod(grpc::protobuf::io::Printer* printer,
+ const MethodDescriptor* method) {
if (GenerateDocCommentBody(printer, method)) {
if (method->client_streaming()) {
printer->Print(
@@ -140,8 +140,8 @@ void GenerateDocCommentServerMethod(grpc::protobuf::io::Printer* printer,
}
}
-void GenerateDocCommentClientMethod(grpc::protobuf::io::Printer* printer,
- const MethodDescriptor* method,
+void GenerateDocCommentClientMethod(grpc::protobuf::io::Printer* printer,
+ const MethodDescriptor* method,
bool is_sync, bool use_call_options) {
if (GenerateDocCommentBody(printer, method)) {
if (!method->client_streaming()) {
@@ -187,13 +187,13 @@ TString GetServerClassName(const ServiceDescriptor* service) {
TString GetCSharpMethodType(MethodType method_type) {
switch (method_type) {
case METHODTYPE_NO_STREAMING:
- return "grpc::MethodType.Unary";
+ return "grpc::MethodType.Unary";
case METHODTYPE_CLIENT_STREAMING:
- return "grpc::MethodType.ClientStreaming";
+ return "grpc::MethodType.ClientStreaming";
case METHODTYPE_SERVER_STREAMING:
- return "grpc::MethodType.ServerStreaming";
+ return "grpc::MethodType.ServerStreaming";
case METHODTYPE_BIDI_STREAMING:
- return "grpc::MethodType.DuplexStreaming";
+ return "grpc::MethodType.DuplexStreaming";
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return "";
@@ -243,19 +243,19 @@ TString GetAccessLevel(bool internal_access) {
TString GetMethodReturnTypeClient(const MethodDescriptor* method) {
switch (GetMethodType(method)) {
case METHODTYPE_NO_STREAMING:
- return "grpc::AsyncUnaryCall<" + GetClassName(method->output_type()) +
- ">";
+ return "grpc::AsyncUnaryCall<" + GetClassName(method->output_type()) +
+ ">";
case METHODTYPE_CLIENT_STREAMING:
- return "grpc::AsyncClientStreamingCall<" +
- GetClassName(method->input_type()) + ", " +
- GetClassName(method->output_type()) + ">";
+ return "grpc::AsyncClientStreamingCall<" +
+ GetClassName(method->input_type()) + ", " +
+ GetClassName(method->output_type()) + ">";
case METHODTYPE_SERVER_STREAMING:
- return "grpc::AsyncServerStreamingCall<" +
- GetClassName(method->output_type()) + ">";
+ return "grpc::AsyncServerStreamingCall<" +
+ GetClassName(method->output_type()) + ">";
case METHODTYPE_BIDI_STREAMING:
- return "grpc::AsyncDuplexStreamingCall<" +
- GetClassName(method->input_type()) + ", " +
- GetClassName(method->output_type()) + ">";
+ return "grpc::AsyncDuplexStreamingCall<" +
+ GetClassName(method->input_type()) + ", " +
+ GetClassName(method->output_type()) + ">";
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return "";
@@ -268,7 +268,7 @@ TString GetMethodRequestParamServer(const MethodDescriptor* method) {
return GetClassName(method->input_type()) + " request";
case METHODTYPE_CLIENT_STREAMING:
case METHODTYPE_BIDI_STREAMING:
- return "grpc::IAsyncStreamReader<" + GetClassName(method->input_type()) +
+ return "grpc::IAsyncStreamReader<" + GetClassName(method->input_type()) +
"> requestStream";
}
GOOGLE_LOG(FATAL) << "Can't get here.";
@@ -296,21 +296,21 @@ TString GetMethodResponseStreamMaybe(const MethodDescriptor* method) {
return "";
case METHODTYPE_SERVER_STREAMING:
case METHODTYPE_BIDI_STREAMING:
- return ", grpc::IServerStreamWriter<" +
- GetClassName(method->output_type()) + "> responseStream";
+ return ", grpc::IServerStreamWriter<" +
+ GetClassName(method->output_type()) + "> responseStream";
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return "";
}
// Gets vector of all messages used as input or output types.
-std::vector<const Descriptor*> GetUsedMessages(
- const ServiceDescriptor* service) {
- std::set<const Descriptor*> descriptor_set;
- std::vector<const Descriptor*>
+std::vector<const Descriptor*> GetUsedMessages(
+ const ServiceDescriptor* service) {
+ std::set<const Descriptor*> descriptor_set;
+ std::vector<const Descriptor*>
result; // vector is to maintain stable ordering
for (int i = 0; i < service->method_count(); i++) {
- const MethodDescriptor* method = service->method(i);
+ const MethodDescriptor* method = service->method(i);
if (descriptor_set.find(method->input_type()) == descriptor_set.end()) {
descriptor_set.insert(method->input_type());
result.push_back(method->input_type());
@@ -323,8 +323,8 @@ std::vector<const Descriptor*> GetUsedMessages(
return result;
}
-void GenerateMarshallerFields(Printer* out, const ServiceDescriptor* service) {
- std::vector<const Descriptor*> used_messages = GetUsedMessages(service);
+void GenerateMarshallerFields(Printer* out, const ServiceDescriptor* service) {
+ std::vector<const Descriptor*> used_messages = GetUsedMessages(service);
if (used_messages.size() != 0) {
// Generate static helper methods for serialization/deserialization
out->Print(
@@ -390,9 +390,9 @@ void GenerateMarshallerFields(Printer* out, const ServiceDescriptor* service) {
}
for (size_t i = 0; i < used_messages.size(); i++) {
- const Descriptor* message = used_messages[i];
+ const Descriptor* message = used_messages[i];
out->Print(
- "static readonly grpc::Marshaller<$type$> $fieldname$ = "
+ "static readonly grpc::Marshaller<$type$> $fieldname$ = "
"grpc::Marshallers.Create(__Helper_SerializeMessage, "
"context => __Helper_DeserializeMessage(context, $type$.Parser));\n",
"fieldname", GetMarshallerFieldName(message), "type",
@@ -401,10 +401,10 @@ void GenerateMarshallerFields(Printer* out, const ServiceDescriptor* service) {
out->Print("\n");
}
-void GenerateStaticMethodField(Printer* out, const MethodDescriptor* method) {
+void GenerateStaticMethodField(Printer* out, const MethodDescriptor* method) {
out->Print(
- "static readonly grpc::Method<$request$, $response$> $fieldname$ = new "
- "grpc::Method<$request$, $response$>(\n",
+ "static readonly grpc::Method<$request$, $response$> $fieldname$ = new "
+ "grpc::Method<$request$, $response$>(\n",
"fieldname", GetMethodFieldName(method), "request",
GetClassName(method->input_type()), "response",
GetClassName(method->output_type()));
@@ -424,8 +424,8 @@ void GenerateStaticMethodField(Printer* out, const MethodDescriptor* method) {
out->Outdent();
}
-void GenerateServiceDescriptorProperty(Printer* out,
- const ServiceDescriptor* service) {
+void GenerateServiceDescriptorProperty(Printer* out,
+ const ServiceDescriptor* service) {
std::ostringstream index;
index << service->index();
out->Print("/// <summary>Service descriptor</summary>\n");
@@ -440,7 +440,7 @@ void GenerateServiceDescriptorProperty(Printer* out,
out->Print("\n");
}
-void GenerateServerClass(Printer* out, const ServiceDescriptor* service) {
+void GenerateServerClass(Printer* out, const ServiceDescriptor* service) {
out->Print(
"/// <summary>Base class for server-side implementations of "
"$servicename$</summary>\n",
@@ -454,12 +454,12 @@ void GenerateServerClass(Printer* out, const ServiceDescriptor* service) {
out->Print("{\n");
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
- const MethodDescriptor* method = service->method(i);
+ const MethodDescriptor* method = service->method(i);
GenerateDocCommentServerMethod(out, method);
out->Print(
"public virtual $returntype$ "
"$methodname$($request$$response_stream_maybe$, "
- "grpc::ServerCallContext context)\n",
+ "grpc::ServerCallContext context)\n",
"methodname", method->name(), "returntype",
GetMethodReturnTypeServer(method), "request",
GetMethodRequestParamServer(method), "response_stream_maybe",
@@ -467,8 +467,8 @@ void GenerateServerClass(Printer* out, const ServiceDescriptor* service) {
out->Print("{\n");
out->Indent();
out->Print(
- "throw new grpc::RpcException("
- "new grpc::Status(grpc::StatusCode.Unimplemented, \"\"));\n");
+ "throw new grpc::RpcException("
+ "new grpc::Status(grpc::StatusCode.Unimplemented, \"\"));\n");
out->Outdent();
out->Print("}\n\n");
}
@@ -477,10 +477,10 @@ void GenerateServerClass(Printer* out, const ServiceDescriptor* service) {
out->Print("\n");
}
-void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
+void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
out->Print("/// <summary>Client for $servicename$</summary>\n", "servicename",
GetServiceClassName(service));
- out->Print("public partial class $name$ : grpc::ClientBase<$name$>\n", "name",
+ out->Print("public partial class $name$ : grpc::ClientBase<$name$>\n", "name",
GetClientClassName(service));
out->Print("{\n");
out->Indent();
@@ -501,9 +501,9 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
"/// <param name=\"callInvoker\">The callInvoker to use to make remote "
"calls.</param>\n",
"servicename", GetServiceClassName(service));
- out->Print(
- "public $name$(grpc::CallInvoker callInvoker) : base(callInvoker)\n",
- "name", GetClientClassName(service));
+ out->Print(
+ "public $name$(grpc::CallInvoker callInvoker) : base(callInvoker)\n",
+ "name", GetClientClassName(service));
out->Print("{\n");
out->Print("}\n");
out->Print(
@@ -525,27 +525,27 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
out->Print("}\n\n");
for (int i = 0; i < service->method_count(); i++) {
- const MethodDescriptor* method = service->method(i);
+ const MethodDescriptor* method = service->method(i);
MethodType method_type = GetMethodType(method);
if (method_type == METHODTYPE_NO_STREAMING) {
// unary calls have an extra synchronous stub method
GenerateDocCommentClientMethod(out, method, true, false);
out->Print(
- "public virtual $response$ $methodname$($request$ request, "
- "grpc::Metadata "
- "headers = null, global::System.DateTime? deadline = null, "
- "global::System.Threading.CancellationToken "
- "cancellationToken = "
- "default(global::System.Threading.CancellationToken))\n",
+ "public virtual $response$ $methodname$($request$ request, "
+ "grpc::Metadata "
+ "headers = null, global::System.DateTime? deadline = null, "
+ "global::System.Threading.CancellationToken "
+ "cancellationToken = "
+ "default(global::System.Threading.CancellationToken))\n",
"methodname", method->name(), "request",
GetClassName(method->input_type()), "response",
GetClassName(method->output_type()));
out->Print("{\n");
out->Indent();
out->Print(
- "return $methodname$(request, new grpc::CallOptions(headers, "
- "deadline, "
+ "return $methodname$(request, new grpc::CallOptions(headers, "
+ "deadline, "
"cancellationToken));\n",
"methodname", method->name());
out->Outdent();
@@ -555,7 +555,7 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
GenerateDocCommentClientMethod(out, method, true, true);
out->Print(
"public virtual $response$ $methodname$($request$ request, "
- "grpc::CallOptions options)\n",
+ "grpc::CallOptions options)\n",
"methodname", method->name(), "request",
GetClassName(method->input_type()), "response",
GetClassName(method->output_type()));
@@ -575,12 +575,12 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
}
GenerateDocCommentClientMethod(out, method, false, false);
out->Print(
- "public virtual $returntype$ "
- "$methodname$($request_maybe$grpc::Metadata "
- "headers = null, global::System.DateTime? deadline = null, "
- "global::System.Threading.CancellationToken "
- "cancellationToken = "
- "default(global::System.Threading.CancellationToken))\n",
+ "public virtual $returntype$ "
+ "$methodname$($request_maybe$grpc::Metadata "
+ "headers = null, global::System.DateTime? deadline = null, "
+ "global::System.Threading.CancellationToken "
+ "cancellationToken = "
+ "default(global::System.Threading.CancellationToken))\n",
"methodname", method_name, "request_maybe",
GetMethodRequestParamMaybe(method), "returntype",
GetMethodReturnTypeClient(method));
@@ -588,8 +588,8 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
out->Indent();
out->Print(
- "return $methodname$($request_maybe$new grpc::CallOptions(headers, "
- "deadline, "
+ "return $methodname$($request_maybe$new grpc::CallOptions(headers, "
+ "deadline, "
"cancellationToken));\n",
"methodname", method_name, "request_maybe",
GetMethodRequestParamMaybe(method, true));
@@ -599,8 +599,8 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
// overload taking CallOptions as a param
GenerateDocCommentClientMethod(out, method, false, true);
out->Print(
- "public virtual $returntype$ "
- "$methodname$($request_maybe$grpc::CallOptions "
+ "public virtual $returntype$ "
+ "$methodname$($request_maybe$grpc::CallOptions "
"options)\n",
"methodname", method_name, "request_maybe",
GetMethodRequestParamMaybe(method), "returntype",
@@ -659,7 +659,7 @@ void GenerateClientStub(Printer* out, const ServiceDescriptor* service) {
out->Print("\n");
}
-void GenerateBindServiceMethod(Printer* out, const ServiceDescriptor* service) {
+void GenerateBindServiceMethod(Printer* out, const ServiceDescriptor* service) {
out->Print(
"/// <summary>Creates service definition that can be registered with a "
"server</summary>\n");
@@ -667,7 +667,7 @@ void GenerateBindServiceMethod(Printer* out, const ServiceDescriptor* service) {
"/// <param name=\"serviceImpl\">An object implementing the server-side"
" handling logic.</param>\n");
out->Print(
- "public static grpc::ServerServiceDefinition BindService($implclass$ "
+ "public static grpc::ServerServiceDefinition BindService($implclass$ "
"serviceImpl)\n",
"implclass", GetServerClassName(service));
out->Print("{\n");
@@ -677,7 +677,7 @@ void GenerateBindServiceMethod(Printer* out, const ServiceDescriptor* service) {
out->Indent();
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
- const MethodDescriptor* method = service->method(i);
+ const MethodDescriptor* method = service->method(i);
out->Print("\n.AddMethod($methodfield$, serviceImpl.$methodname$)",
"methodfield", GetMethodFieldName(method), "methodname",
method->name());
@@ -732,7 +732,7 @@ void GenerateBindServiceWithBinderMethod(Printer* out,
out->Print("\n");
}
-void GenerateService(Printer* out, const ServiceDescriptor* service,
+void GenerateService(Printer* out, const ServiceDescriptor* service,
bool generate_client, bool generate_server,
bool internal_access) {
GenerateDocCommentBody(out, service);
@@ -785,24 +785,24 @@ TString GetServices(const FileDescriptor* file, bool generate_client,
}
// Write out a file header.
- out.Print("// <auto-generated>\n");
- out.Print(
- "// Generated by the protocol buffer compiler. DO NOT EDIT!\n");
- out.Print("// source: $filename$\n", "filename", file->name());
- out.Print("// </auto-generated>\n");
+ out.Print("// <auto-generated>\n");
+ out.Print(
+ "// Generated by the protocol buffer compiler. DO NOT EDIT!\n");
+ out.Print("// source: $filename$\n", "filename", file->name());
+ out.Print("// </auto-generated>\n");
// use C++ style as there are no file-level XML comments in .NET
TString leading_comments = GetCsharpComments(file, true);
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
- out.PrintRaw(leading_comments.c_str());
+ out.PrintRaw(leading_comments.c_str());
}
out.Print("#pragma warning disable 0414, 1591\n");
out.Print("#region Designer generated code\n");
out.Print("\n");
- out.Print("using grpc = global::Grpc.Core;\n");
+ out.Print("using grpc = global::Grpc.Core;\n");
out.Print("\n");
TString file_namespace = GetFileNamespace(file);
diff --git a/contrib/libs/grpc/src/compiler/csharp_generator.h b/contrib/libs/grpc/src/compiler/csharp_generator.h
index c13da4657f3..82bdbf5e95f 100644
--- a/contrib/libs/grpc/src/compiler/csharp_generator.h
+++ b/contrib/libs/grpc/src/compiler/csharp_generator.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/compiler/csharp_generator_helpers.h b/contrib/libs/grpc/src/compiler/csharp_generator_helpers.h
index a8af7f3ccd1..12b143f1bd8 100644
--- a/contrib/libs/grpc/src/compiler/csharp_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/csharp_generator_helpers.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -24,7 +24,7 @@
namespace grpc_csharp_generator {
-inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file,
+inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file,
TString* file_name_or_error) {
*file_name_or_error =
grpc_generator::FileNameInUpperCamel(file, false) + "Grpc.cs";
diff --git a/contrib/libs/grpc/src/compiler/generator_helpers.h b/contrib/libs/grpc/src/compiler/generator_helpers.h
index 265713a16b3..c8b748b900b 100644
--- a/contrib/libs/grpc/src/compiler/generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/generator_helpers.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -129,7 +129,7 @@ inline TString LowerUnderscoreToUpperCamel(TString str) {
}
inline TString FileNameInUpperCamel(
- const grpc::protobuf::FileDescriptor* file, bool include_package_path) {
+ const grpc::protobuf::FileDescriptor* file, bool include_package_path) {
std::vector<TString> tokens = tokenize(StripProto(file->name()), "/");
TString result = "";
if (include_package_path) {
@@ -142,7 +142,7 @@ inline TString FileNameInUpperCamel(
}
inline TString FileNameInUpperCamel(
- const grpc::protobuf::FileDescriptor* file) {
+ const grpc::protobuf::FileDescriptor* file) {
return FileNameInUpperCamel(file, true);
}
@@ -154,7 +154,7 @@ enum MethodType {
};
inline MethodType GetMethodType(
- const grpc::protobuf::MethodDescriptor* method) {
+ const grpc::protobuf::MethodDescriptor* method) {
if (method->client_streaming()) {
if (method->server_streaming()) {
return METHODTYPE_BIDI_STREAMING;
@@ -172,7 +172,7 @@ inline MethodType GetMethodType(
template <typename TStringType>
inline void Split(const TStringType& s, char /*delim*/,
- std::vector<TStringType>* append_to) {
+ std::vector<TStringType>* append_to) {
std::istringstream iss(s);
TStringType piece;
while (std::getline(iss, piece)) {
@@ -198,7 +198,7 @@ enum CommentType {
// Get all the raw comments and append each line without newline to out.
template <typename DescriptorType>
-inline void GetComment(const DescriptorType* desc, CommentType type,
+inline void GetComment(const DescriptorType* desc, CommentType type,
std::vector<TString>* out) {
grpc::protobuf::SourceLocation location;
if (!desc->GetSourceLocation(&location)) {
@@ -225,7 +225,7 @@ inline void GetComment(const DescriptorType* desc, CommentType type,
// For file level leading and detached leading comments, we return comments
// above syntax line. Return nothing for trailing comments.
template <>
-inline void GetComment(const grpc::protobuf::FileDescriptor* desc,
+inline void GetComment(const grpc::protobuf::FileDescriptor* desc,
CommentType type, std::vector<TString>* out) {
if (type == COMMENTTYPE_TRAILING) {
return;
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 068ae1ead6d..41d358a7ad3 100644
--- a/contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make
+++ b/contrib/libs/grpc/src/compiler/grpc_plugin_support/ya.make
@@ -5,7 +5,7 @@ LIBRARY()
WITHOUT_LICENSE_TEXTS()
OWNER(g:cpp-contrib)
-
+
LICENSE(Apache-2.0)
PEERDIR(
diff --git a/contrib/libs/grpc/src/compiler/node_generator.cc b/contrib/libs/grpc/src/compiler/node_generator.cc
index 89e4871a660..06c19806755 100644
--- a/contrib/libs/grpc/src/compiler/node_generator.cc
+++ b/contrib/libs/grpc/src/compiler/node_generator.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -20,12 +20,12 @@
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
-#include "src/compiler/node_generator.h"
+#include "src/compiler/node_generator.h"
#include "src/compiler/node_generator_helpers.h"
-using grpc::protobuf::Descriptor;
+using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
-using grpc::protobuf::MethodDescriptor;
+using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
@@ -48,7 +48,7 @@ TString ModuleAlias(const TString filename) {
TString basename = grpc_generator::StripProto(filename);
basename = grpc_generator::StringReplace(basename, "-", "$");
basename = grpc_generator::StringReplace(basename, "/", "_");
- basename = grpc_generator::StringReplace(basename, ".", "_");
+ basename = grpc_generator::StringReplace(basename, ".", "_");
return basename + "_pb";
}
@@ -94,12 +94,12 @@ map<TString, const Descriptor*> GetAllMessages(const FileDescriptor* file) {
map<TString, const Descriptor*> message_types;
for (int service_num = 0; service_num < file->service_count();
service_num++) {
- const ServiceDescriptor* service = file->service(service_num);
+ const ServiceDescriptor* service = file->service(service_num);
for (int method_num = 0; method_num < service->method_count();
method_num++) {
- const MethodDescriptor* method = service->method(method_num);
- const Descriptor* input_type = method->input_type();
- const Descriptor* output_type = method->output_type();
+ const MethodDescriptor* method = service->method(method_num);
+ const Descriptor* input_type = method->input_type();
+ const Descriptor* output_type = method->output_type();
message_types[input_type->full_name()] = input_type;
message_types[output_type->full_name()] = output_type;
}
@@ -119,8 +119,8 @@ TString NodeObjectPath(const Descriptor* descriptor) {
}
// Prints out the message serializer and deserializer functions
-void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
- const Parameters& params) {
+void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
+ const Parameters& params) {
map<TString, TString> template_vars;
TString full_name = descriptor->full_name();
template_vars["identifier_name"] = MessageIdentifierName(full_name);
@@ -135,12 +135,12 @@ void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
"throw new Error('Expected argument of type $name$');\n");
out->Outdent();
out->Print("}\n");
- if (params.minimum_node_version > 5) {
- // Node version is > 5, we should use Buffer.from
- out->Print("return Buffer.from(arg.serializeBinary());\n");
- } else {
- out->Print("return new Buffer(arg.serializeBinary());\n");
- }
+ if (params.minimum_node_version > 5) {
+ // Node version is > 5, we should use Buffer.from
+ out->Print("return Buffer.from(arg.serializeBinary());\n");
+ } else {
+ out->Print("return new Buffer(arg.serializeBinary());\n");
+ }
out->Outdent();
out->Print("}\n\n");
@@ -155,9 +155,9 @@ void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
out->Print("}\n\n");
}
-void PrintMethod(const MethodDescriptor* method, Printer* out) {
- const Descriptor* input_type = method->input_type();
- const Descriptor* output_type = method->output_type();
+void PrintMethod(const MethodDescriptor* method, Printer* out) {
+ const Descriptor* input_type = method->input_type();
+ const Descriptor* output_type = method->output_type();
map<TString, TString> vars;
vars["service_name"] = method->service()->full_name();
vars["name"] = method->name();
@@ -183,7 +183,7 @@ void PrintMethod(const MethodDescriptor* method, Printer* out) {
}
// Prints out the service descriptor object
-void PrintService(const ServiceDescriptor* service, Printer* out) {
+void PrintService(const ServiceDescriptor* service, Printer* out) {
map<TString, TString> template_vars;
out->Print(GetNodeComments(service, true).c_str());
template_vars["name"] = service->name();
@@ -206,7 +206,7 @@ void PrintService(const ServiceDescriptor* service, Printer* out) {
out->Print(GetNodeComments(service, false).c_str());
}
-void PrintImports(const FileDescriptor* file, Printer* out) {
+void PrintImports(const FileDescriptor* file, Printer* out) {
out->Print("var grpc = require('grpc');\n");
if (file->message_type_count() > 0) {
TString file_path =
@@ -225,22 +225,22 @@ void PrintImports(const FileDescriptor* file, Printer* out) {
out->Print("\n");
}
-void PrintTransformers(const FileDescriptor* file, Printer* out,
- const Parameters& params) {
+void PrintTransformers(const FileDescriptor* file, Printer* out,
+ const Parameters& params) {
map<TString, const Descriptor*> messages = GetAllMessages(file);
for (std::map<TString, const Descriptor*>::iterator it = messages.begin();
it != messages.end(); it++) {
- PrintMessageTransformer(it->second, out, params);
+ PrintMessageTransformer(it->second, out, params);
}
out->Print("\n");
}
-void PrintServices(const FileDescriptor* file, Printer* out) {
+void PrintServices(const FileDescriptor* file, Printer* out) {
for (int i = 0; i < file->service_count(); i++) {
PrintService(file->service(i), out);
}
}
-} // namespace
+} // namespace
TString GenerateFile(const FileDescriptor* file, const Parameters& params) {
TString output;
@@ -256,14 +256,14 @@ TString GenerateFile(const FileDescriptor* file, const Parameters& params) {
TString leading_comments = GetNodeComments(file, true);
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
- out.PrintRaw(leading_comments.c_str());
+ out.PrintRaw(leading_comments.c_str());
}
out.Print("'use strict';\n");
PrintImports(file, &out);
- PrintTransformers(file, &out, params);
+ PrintTransformers(file, &out, params);
PrintServices(file, &out);
diff --git a/contrib/libs/grpc/src/compiler/node_generator.h b/contrib/libs/grpc/src/compiler/node_generator.h
index 959df436ea5..70297d7aef7 100644
--- a/contrib/libs/grpc/src/compiler/node_generator.h
+++ b/contrib/libs/grpc/src/compiler/node_generator.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -23,15 +23,15 @@
namespace grpc_node_generator {
-// Contains all the parameters that are parsed from the command line.
-struct Parameters {
- // Sets the earliest version of nodejs that needs to be supported.
- int minimum_node_version;
-};
+// Contains all the parameters that are parsed from the command line.
+struct Parameters {
+ // Sets the earliest version of nodejs that needs to be supported.
+ int minimum_node_version;
+};
TString GenerateFile(const grpc::protobuf::FileDescriptor* file,
const Parameters& params);
-
+
} // namespace grpc_node_generator
#endif // GRPC_INTERNAL_COMPILER_NODE_GENERATOR_H
diff --git a/contrib/libs/grpc/src/compiler/node_generator_helpers.h b/contrib/libs/grpc/src/compiler/node_generator_helpers.h
index ccf57ec8a62..a294e261610 100644
--- a/contrib/libs/grpc/src/compiler/node_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/node_generator_helpers.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/compiler/objective_c_generator.cc b/contrib/libs/grpc/src/compiler/objective_c_generator.cc
index 07826b6a8d8..158e4c3aa2d 100644
--- a/contrib/libs/grpc/src/compiler/objective_c_generator.cc
+++ b/contrib/libs/grpc/src/compiler/objective_c_generator.cc
@@ -1,23 +1,23 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 <map>
-#include <set>
+#include <set>
#include <sstream>
#include "src/compiler/config.h"
@@ -27,12 +27,12 @@
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
using ::google::protobuf::compiler::objectivec::ClassName;
-using ::grpc::protobuf::FileDescriptor;
+using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::MethodDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
-using ::grpc::protobuf::io::Printer;
+using ::grpc::protobuf::io::Printer;
using ::std::map;
-using ::std::set;
+using ::std::set;
namespace grpc_objective_c_generator {
namespace {
@@ -66,7 +66,7 @@ static void PrintAllComments(const DescriptorType* desc, Printer* printer,
printer->Print(" * ");
size_t start_pos = it->find_first_not_of(' ');
if (start_pos != TString::npos) {
- printer->PrintRaw(it->c_str() + start_pos);
+ printer->PrintRaw(it->c_str() + start_pos);
}
printer->Print("\n");
}
@@ -80,7 +80,7 @@ static void PrintAllComments(const DescriptorType* desc, Printer* printer,
printer->Print(" */\n");
}
-void PrintMethodSignature(Printer* printer, const MethodDescriptor* method,
+void PrintMethodSignature(Printer* printer, const MethodDescriptor* method,
const map< ::TString, ::TString>& vars) {
// Print comment
PrintAllComments(method, printer, true);
@@ -105,7 +105,7 @@ void PrintMethodSignature(Printer* printer, const MethodDescriptor* method,
}
}
-void PrintSimpleSignature(Printer* printer, const MethodDescriptor* method,
+void PrintSimpleSignature(Printer* printer, const MethodDescriptor* method,
map< ::TString, ::TString> vars) {
vars["method_name"] =
grpc_generator::LowercaseFirstLetter(vars["method_name"]);
@@ -113,7 +113,7 @@ void PrintSimpleSignature(Printer* printer, const MethodDescriptor* method,
PrintMethodSignature(printer, method, vars);
}
-void PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method,
+void PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method,
map< ::TString, ::TString> vars) {
vars["method_name"] = "RPCTo" + vars["method_name"];
vars["return_type"] = "GRPCProtoCall *";
@@ -144,7 +144,7 @@ void PrintV2Signature(Printer* printer, const MethodDescriptor* method,
}
inline map< ::TString, ::TString> GetMethodVars(
- const MethodDescriptor* method) {
+ const MethodDescriptor* method) {
map< ::TString, ::TString> res;
res["method_name"] = method->name();
res["request_type"] = method->input_type()->name();
@@ -154,7 +154,7 @@ inline map< ::TString, ::TString> GetMethodVars(
return res;
}
-void PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) {
+void PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) {
map< ::TString, ::TString> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
@@ -175,7 +175,7 @@ void PrintV2MethodDeclarations(Printer* printer,
printer->Print(";\n\n");
}
-void PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method,
+void PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method,
map< ::TString, ::TString> vars) {
printer->Print("{\n");
printer->Print(vars, " [[self RPCTo$method_name$With");
@@ -192,8 +192,8 @@ void PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method,
printer->Print("}\n");
}
-void PrintAdvancedImplementation(Printer* printer,
- const MethodDescriptor* method,
+void PrintAdvancedImplementation(Printer* printer,
+ const MethodDescriptor* method,
map< ::TString, ::TString> vars) {
printer->Print("{\n");
printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n");
@@ -236,7 +236,7 @@ void PrintV2Implementation(Printer* printer, const MethodDescriptor* method,
}
}
-void PrintMethodImplementations(Printer* printer,
+void PrintMethodImplementations(Printer* printer,
const MethodDescriptor* method,
const Parameters& generator_params) {
map< ::TString, ::TString> vars = GetMethodVars(method);
@@ -262,20 +262,20 @@ void PrintMethodImplementations(Printer* printer,
::TString GetAllMessageClasses(const FileDescriptor* file) {
::TString output;
set< ::TString> classes;
- for (int i = 0; i < file->service_count(); i++) {
- const auto service = file->service(i);
- for (int i = 0; i < service->method_count(); i++) {
- const auto method = service->method(i);
- classes.insert(ClassName(method->input_type()));
- classes.insert(ClassName(method->output_type()));
- }
- }
- for (auto one_class : classes) {
- output += "@class " + one_class + ";\n";
- }
-
- return output;
-}
+ for (int i = 0; i < file->service_count(); i++) {
+ const auto service = file->service(i);
+ for (int i = 0; i < service->method_count(); i++) {
+ const auto method = service->method(i);
+ classes.insert(ClassName(method->input_type()));
+ classes.insert(ClassName(method->output_type()));
+ }
+ }
+ for (auto one_class : classes) {
+ output += "@class " + one_class + ";\n";
+ }
+
+ return output;
+}
::TString GetProtocol(const ServiceDescriptor* service,
const Parameters& generator_params) {
@@ -283,13 +283,13 @@ void PrintMethodImplementations(Printer* printer,
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, '$');
+ // Scope the output stream so it closes and finalizes output to the string.
+ grpc::protobuf::io::StringOutputStream output_stream(&output);
+ Printer printer(&output_stream, '$');
map< ::TString, ::TString> vars = {
- {"service_class", ServiceClassName(service)}};
-
+ {"service_class", ServiceClassName(service)}};
+
printer.Print(vars,
"/**\n"
" * The methods in this protocol belong to a set of old APIs "
@@ -298,11 +298,11 @@ void PrintMethodImplementations(Printer* printer,
"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));
+ for (int i = 0; i < service->method_count(); i++) {
+ PrintMethodDeclarations(&printer, service->method(i));
}
- printer.Print("@end\n\n");
-
+ printer.Print("@end\n\n");
+
return output;
}
@@ -328,31 +328,31 @@ void PrintMethodImplementations(Printer* printer,
::TString GetInterface(const ServiceDescriptor* service,
const Parameters& generator_params) {
::TString 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, '$');
-
+
+ // Scope the output stream so it closes and finalizes output to the string.
+ grpc::protobuf::io::StringOutputStream output_stream(&output);
+ Printer printer(&output_stream, '$');
+
map< ::TString, ::TString> vars = {
- {"service_class", ServiceClassName(service)}};
-
- printer.Print(vars,
- "/**\n"
- " * Basic service implementation, over gRPC, that only does\n"
- " * marshalling and parsing.\n"
- " */\n");
- printer.Print(vars,
- "@interface $service_class$ :"
+ {"service_class", ServiceClassName(service)}};
+
+ printer.Print(vars,
+ "/**\n"
+ " * Basic service implementation, over gRPC, that only does\n"
+ " * marshalling and parsing.\n"
+ " */\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");
- printer.Print(
+ printer.Print(
"- (instancetype)initWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions "
"*_Nullable)callOptions"
- " NS_DESIGNATED_INITIALIZER;\n");
+ " NS_DESIGNATED_INITIALIZER;\n");
printer.Print(
"+ (instancetype)serviceWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions *_Nullable)callOptions;\n");
@@ -363,11 +363,11 @@ void PrintMethodImplementations(Printer* printer,
printer.Print("- (instancetype)initWithHost:(NSString *)host;\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
}
- printer.Print("@end\n");
-
- return output;
-}
-
+ printer.Print("@end\n");
+
+ return output;
+}
+
::TString GetSource(const ServiceDescriptor* service,
const Parameters& generator_params) {
::TString output;
@@ -381,12 +381,12 @@ void PrintMethodImplementations(Printer* printer,
{"service_class", ServiceClassName(service)},
{"package", service->file()->package()}};
- printer.Print(vars,
- "@implementation $service_class$\n\n"
+ printer.Print(vars,
+ "@implementation $service_class$\n\n"
"#pragma clang diagnostic push\n"
"#pragma clang diagnostic ignored "
"\"-Wobjc-designated-initializers\"\n\n"
- "// Designated initializer\n"
+ "// Designated initializer\n"
"- (instancetype)initWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions *_Nullable)callOptions {\n"
" return [super initWithHost:host\n"
@@ -415,12 +415,12 @@ void PrintMethodImplementations(Printer* printer,
"}\n\n");
}
printer.Print(
- "- (instancetype)initWithHost:(NSString *)host\n"
- " packageName:(NSString *)packageName\n"
+ "- (instancetype)initWithHost:(NSString *)host\n"
+ " packageName:(NSString *)packageName\n"
" serviceName:(NSString *)serviceName\n"
" callOptions:(GRPCCallOptions *)callOptions {\n"
" return [self initWithHost:host callOptions:callOptions];\n"
- "}\n\n");
+ "}\n\n");
printer.Print("#pragma mark - Class Methods\n\n");
if (!generator_params.no_v1_compatibility) {
@@ -429,14 +429,14 @@ void PrintMethodImplementations(Printer* printer,
" return [[self alloc] initWithHost:host];\n"
"}\n\n");
}
- printer.Print(
+ printer.Print(
"+ (instancetype)serviceWithHost:(NSString *)host "
"callOptions:(GRPCCallOptions *_Nullable)callOptions {\n"
" return [[self alloc] initWithHost:host callOptions:callOptions];\n"
- "}\n\n");
-
- printer.Print("#pragma mark - Method Implementations\n\n");
-
+ "}\n\n");
+
+ printer.Print("#pragma mark - Method Implementations\n\n");
+
for (int i = 0; i < service->method_count(); i++) {
PrintMethodImplementations(&printer, service->method(i),
generator_params);
diff --git a/contrib/libs/grpc/src/compiler/objective_c_generator.h b/contrib/libs/grpc/src/compiler/objective_c_generator.h
index 9770f65436d..ce0d0eeb3fd 100644
--- a/contrib/libs/grpc/src/compiler/objective_c_generator.h
+++ b/contrib/libs/grpc/src/compiler/objective_c_generator.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -28,28 +28,28 @@ struct Parameters {
bool no_v1_compatibility;
};
-using ::grpc::protobuf::FileDescriptor;
+using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
using ::TString;
-// Returns forward declaration of classes in the generated header file.
-string GetAllMessageClasses(const FileDescriptor* file);
+// Returns forward declaration of classes in the generated header file.
+string GetAllMessageClasses(const FileDescriptor* file);
-// Returns the content to be included defining the @protocol segment at the
+// 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);
-
+
// Returns the content to be included defining the @protocol segment at the
// insertion point of the generated implementation file.
string GetV2Protocol(const ServiceDescriptor* service);
-// Returns the content to be included defining the @interface segment at the
-// insertion point of the generated implementation file.
+// 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);
-
+
// Returns the content to be included in the "global_scope" insertion point of
// the generated implementation file.
string GetSource(const ServiceDescriptor* service,
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 ae296741cec..54c15a21641 100644
--- a/contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/objective_c_generator_helpers.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -24,27 +24,27 @@
#include "src/compiler/generator_helpers.h"
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
-
+
namespace grpc_objective_c_generator {
using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
using ::TString;
-inline string MessageHeaderName(const FileDescriptor* file) {
- return google::protobuf::compiler::objectivec::FilePath(file) + ".pbobjc.h";
+inline string MessageHeaderName(const FileDescriptor* file) {
+ return google::protobuf::compiler::objectivec::FilePath(file) + ".pbobjc.h";
}
-inline string ServiceClassName(const ServiceDescriptor* service) {
- const FileDescriptor* file = service->file();
+inline string ServiceClassName(const ServiceDescriptor* service) {
+ const FileDescriptor* file = service->file();
string prefix = file->options().objc_class_prefix();
return prefix + service->name();
}
-
+
inline ::TString LocalImport(const ::TString& import) {
return ::TString("#import \"" + import + "\"\n");
}
-
+
inline ::TString FrameworkImport(const ::TString& import,
const ::TString& framework) {
// Flattens the directory structure: grab the file name only
@@ -57,38 +57,38 @@ inline ::TString FrameworkImport(const ::TString& import,
inline ::TString SystemImport(const ::TString& import) {
return ::TString("#import <" + import + ">\n");
-}
-
+}
+
inline ::TString PreprocConditional(::TString symbol, bool invert) {
- return invert ? "!defined(" + symbol + ") || !" + symbol
- : "defined(" + symbol + ") && " + symbol;
-}
-
+ return invert ? "!defined(" + symbol + ") || !" + symbol
+ : "defined(" + symbol + ") && " + symbol;
+}
+
inline ::TString PreprocIf(const ::TString& symbol,
const ::TString& if_true) {
return ::TString("#if " + PreprocConditional(symbol, false) + "\n" +
if_true + "#endif\n");
-}
-
+}
+
inline ::TString PreprocIfNot(const ::TString& symbol,
const ::TString& if_true) {
return ::TString("#if " + PreprocConditional(symbol, true) + "\n" +
if_true + "#endif\n");
-}
-
+}
+
inline ::TString PreprocIfElse(const ::TString& symbol,
const ::TString& if_true,
const ::TString& if_false) {
return ::TString("#if " + PreprocConditional(symbol, false) + "\n" +
if_true + "#else\n" + if_false + "#endif\n");
-}
-
+}
+
inline ::TString PreprocIfNotElse(const ::TString& symbol,
const ::TString& if_true,
const ::TString& if_false) {
return ::TString("#if " + PreprocConditional(symbol, true) + "\n" +
if_true + "#else\n" + if_false + "#endif\n");
-}
-
-} // namespace grpc_objective_c_generator
+}
+
+} // namespace grpc_objective_c_generator
#endif // GRPC_INTERNAL_COMPILER_OBJECTIVE_C_GENERATOR_HELPERS_H
diff --git a/contrib/libs/grpc/src/compiler/php_generator.cc b/contrib/libs/grpc/src/compiler/php_generator.cc
index b35d3f2a02e..da18f9ccb8c 100644
--- a/contrib/libs/grpc/src/compiler/php_generator.cc
+++ b/contrib/libs/grpc/src/compiler/php_generator.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -23,10 +23,10 @@
#include "src/compiler/generator_helpers.h"
#include "src/compiler/php_generator_helpers.h"
-using google::protobuf::compiler::php::GeneratedClassName;
-using grpc::protobuf::Descriptor;
+using google::protobuf::compiler::php::GeneratedClassName;
+using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
-using grpc::protobuf::MethodDescriptor;
+using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
@@ -46,34 +46,34 @@ TString ConvertToPhpNamespace(const TString& name) {
}
TString PackageName(const FileDescriptor* file) {
- if (file->options().has_php_namespace()) {
- return file->options().php_namespace();
- } else {
- return ConvertToPhpNamespace(file->package());
- }
-}
-
+ if (file->options().has_php_namespace()) {
+ return file->options().php_namespace();
+ } else {
+ return ConvertToPhpNamespace(file->package());
+ }
+}
+
TString MessageIdentifierName(const TString& name,
const FileDescriptor* file) {
std::vector<TString> tokens = grpc_generator::tokenize(name, ".");
- std::ostringstream oss;
- if (PackageName(file) != "") {
- oss << PackageName(file) << "\\";
- }
- oss << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);
- return oss.str();
-}
-
-void PrintMethod(const MethodDescriptor* method, Printer* out) {
- const Descriptor* input_type = method->input_type();
- const Descriptor* output_type = method->output_type();
+ std::ostringstream oss;
+ if (PackageName(file) != "") {
+ oss << PackageName(file) << "\\";
+ }
+ oss << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);
+ return oss.str();
+}
+
+void PrintMethod(const MethodDescriptor* method, Printer* out) {
+ const Descriptor* input_type = method->input_type();
+ const Descriptor* output_type = method->output_type();
map<TString, TString> vars;
vars["service_name"] = method->service()->full_name();
vars["name"] = method->name();
- vars["input_type_id"] =
- MessageIdentifierName(GeneratedClassName(input_type), input_type->file());
- vars["output_type_id"] = MessageIdentifierName(
- GeneratedClassName(output_type), output_type->file());
+ vars["input_type_id"] =
+ MessageIdentifierName(GeneratedClassName(input_type), input_type->file());
+ vars["output_type_id"] = MessageIdentifierName(
+ GeneratedClassName(output_type), output_type->file());
out->Print("/**\n");
out->Print(GetPHPComments(method, " *").c_str());
@@ -90,7 +90,7 @@ void PrintMethod(const MethodDescriptor* method, Printer* out) {
"public function $name$($$metadata = [], "
"$$options = []) {\n");
out->Indent();
- out->Indent();
+ out->Indent();
if (method->server_streaming()) {
out->Print("return $$this->_bidiRequest(");
} else {
@@ -114,7 +114,7 @@ void PrintMethod(const MethodDescriptor* method, Printer* out) {
"public function $name$(\\$input_type_id$ $$argument,\n"
" $$metadata = [], $$options = []) {\n");
out->Indent();
- out->Indent();
+ out->Indent();
if (method->server_streaming()) {
out->Print("return $$this->_serverStreamRequest(");
} else {
@@ -127,33 +127,33 @@ void PrintMethod(const MethodDescriptor* method, Printer* out) {
"$$metadata, $$options);\n");
}
out->Outdent();
- out->Outdent();
+ out->Outdent();
out->Print("}\n\n");
}
// Prints out the service descriptor object
-void PrintService(const ServiceDescriptor* service,
+void PrintService(const ServiceDescriptor* service,
const TString& class_suffix, Printer* out) {
map<TString, TString> vars;
- out->Print("/**\n");
- out->Print(GetPHPComments(service, " *").c_str());
- out->Print(" */\n");
- vars["name"] = GetPHPServiceClassname(service, class_suffix);
- out->Print(vars, "class $name$ extends \\Grpc\\BaseStub {\n\n");
- out->Indent();
+ out->Print("/**\n");
+ out->Print(GetPHPComments(service, " *").c_str());
+ out->Print(" */\n");
+ vars["name"] = GetPHPServiceClassname(service, class_suffix);
+ out->Print(vars, "class $name$ extends \\Grpc\\BaseStub {\n\n");
out->Indent();
+ out->Indent();
out->Print(
"/**\n * @param string $$hostname hostname\n"
" * @param array $$opts channel options\n"
- " * @param \\Grpc\\Channel $$channel (optional) re-use channel "
+ " * @param \\Grpc\\Channel $$channel (optional) re-use channel "
"object\n */\n"
"public function __construct($$hostname, $$opts, "
"$$channel = null) {\n");
out->Indent();
- out->Indent();
+ out->Indent();
out->Print("parent::__construct($$hostname, $$opts, $$channel);\n");
out->Outdent();
- out->Outdent();
+ out->Outdent();
out->Print("}\n\n");
for (int i = 0; i < service->method_count(); i++) {
TString method_name =
@@ -164,7 +164,7 @@ void PrintService(const ServiceDescriptor* service,
out->Outdent();
out->Print("}\n");
}
-} // namespace
+} // namespace
TString GenerateFile(const FileDescriptor* file,
const ServiceDescriptor* service,
@@ -180,15 +180,15 @@ TString GenerateFile(const FileDescriptor* file,
TString leading_comments = GetPHPComments(file, "//");
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
- out.PrintRaw(leading_comments.c_str());
+ out.PrintRaw(leading_comments.c_str());
}
map<TString, TString> vars;
TString php_namespace = PackageName(file);
- vars["package"] = php_namespace;
- out.Print(vars, "namespace $package$;\n\n");
-
- PrintService(service, class_suffix, &out);
+ vars["package"] = php_namespace;
+ out.Print(vars, "namespace $package$;\n\n");
+
+ PrintService(service, class_suffix, &out);
}
return output;
}
diff --git a/contrib/libs/grpc/src/compiler/php_generator_helpers.h b/contrib/libs/grpc/src/compiler/php_generator_helpers.h
index 70a31eaf75e..569261d6bda 100644
--- a/contrib/libs/grpc/src/compiler/php_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/php_generator_helpers.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -27,48 +27,48 @@
namespace grpc_php_generator {
inline TString GetPHPServiceClassname(
- const grpc::protobuf::ServiceDescriptor* service,
+ const grpc::protobuf::ServiceDescriptor* service,
const TString& class_suffix) {
- return service->name() + (class_suffix == "" ? "Client" : class_suffix);
+ return service->name() + (class_suffix == "" ? "Client" : class_suffix);
}
-// ReplaceAll replaces all instances of search with replace in s.
+// ReplaceAll replaces all instances of search with replace in s.
inline TString ReplaceAll(TString s, const TString& search,
const TString& replace) {
- size_t pos = 0;
+ size_t pos = 0;
while ((pos = s.find(search, pos)) != TString::npos) {
- s.replace(pos, search.length(), replace);
- pos += replace.length();
- }
- return s;
-}
-
+ s.replace(pos, search.length(), replace);
+ pos += replace.length();
+ }
+ return s;
+}
+
inline TString GetPHPServiceFilename(
- const grpc::protobuf::FileDescriptor* file,
- const grpc::protobuf::ServiceDescriptor* service,
+ const grpc::protobuf::FileDescriptor* file,
+ const grpc::protobuf::ServiceDescriptor* service,
const TString& class_suffix) {
- std::ostringstream oss;
- if (file->options().has_php_namespace()) {
- oss << ReplaceAll(file->options().php_namespace(), "\\", "/");
- } else {
+ std::ostringstream oss;
+ if (file->options().has_php_namespace()) {
+ oss << ReplaceAll(file->options().php_namespace(), "\\", "/");
+ } else {
std::vector<TString> tokens =
- grpc_generator::tokenize(file->package(), ".");
- for (unsigned int i = 0; i < tokens.size(); i++) {
- oss << (i == 0 ? "" : "/")
- << grpc_generator::CapitalizeFirstLetter(tokens[i]);
- }
- }
- return oss.str() + "/" + GetPHPServiceClassname(service, class_suffix) +
- ".php";
-}
-
+ grpc_generator::tokenize(file->package(), ".");
+ for (unsigned int i = 0; i < tokens.size(); i++) {
+ oss << (i == 0 ? "" : "/")
+ << grpc_generator::CapitalizeFirstLetter(tokens[i]);
+ }
+ }
+ return oss.str() + "/" + GetPHPServiceClassname(service, class_suffix) +
+ ".php";
+}
+
// Get leading or trailing comments in a string. Comment lines start with "// ".
// Leading detached comments are put in front of leading comments.
template <typename DescriptorType>
inline TString GetPHPComments(const DescriptorType* desc,
TString prefix) {
- return ReplaceAll(grpc_generator::GetPrefixedComments(desc, true, prefix),
- "*/", "&#42;/");
+ return ReplaceAll(grpc_generator::GetPrefixedComments(desc, true, prefix),
+ "*/", "&#42;/");
}
} // namespace grpc_php_generator
diff --git a/contrib/libs/grpc/src/compiler/protobuf_plugin.h b/contrib/libs/grpc/src/compiler/protobuf_plugin.h
index ef844ea0551..2c0b4c4134a 100644
--- a/contrib/libs/grpc/src/compiler/protobuf_plugin.h
+++ b/contrib/libs/grpc/src/compiler/protobuf_plugin.h
@@ -1,195 +1,195 @@
-/*
- *
- * 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_INTERNAL_COMPILER_PROTOBUF_PLUGIN_H
-#define GRPC_INTERNAL_COMPILER_PROTOBUF_PLUGIN_H
-
-#include "src/compiler/config.h"
-#include "src/compiler/cpp_generator_helpers.h"
-#include "src/compiler/python_generator_helpers.h"
-#include "src/compiler/python_private_generator.h"
-#include "src/compiler/schema_interface.h"
-
-#include <vector>
-
-// Get leading or trailing comments in a string.
-template <typename DescriptorType>
+/*
+ *
+ * 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_INTERNAL_COMPILER_PROTOBUF_PLUGIN_H
+#define GRPC_INTERNAL_COMPILER_PROTOBUF_PLUGIN_H
+
+#include "src/compiler/config.h"
+#include "src/compiler/cpp_generator_helpers.h"
+#include "src/compiler/python_generator_helpers.h"
+#include "src/compiler/python_private_generator.h"
+#include "src/compiler/schema_interface.h"
+
+#include <vector>
+
+// Get leading or trailing comments in a string.
+template <typename DescriptorType>
inline TString GetCommentsHelper(const DescriptorType* desc, bool leading,
const TString& prefix) {
- return grpc_generator::GetPrefixedComments(desc, leading, prefix);
-}
-
-class ProtoBufMethod : public grpc_generator::Method {
- public:
- ProtoBufMethod(const grpc::protobuf::MethodDescriptor* method)
- : method_(method) {}
-
+ return grpc_generator::GetPrefixedComments(desc, leading, prefix);
+}
+
+class ProtoBufMethod : public grpc_generator::Method {
+ public:
+ ProtoBufMethod(const grpc::protobuf::MethodDescriptor* method)
+ : method_(method) {}
+
TString name() const { return method_->name(); }
-
+
TString input_type_name() const {
- return grpc_cpp_generator::ClassName(method_->input_type(), true);
- }
+ return grpc_cpp_generator::ClassName(method_->input_type(), true);
+ }
TString output_type_name() const {
- return grpc_cpp_generator::ClassName(method_->output_type(), true);
- }
-
+ return grpc_cpp_generator::ClassName(method_->output_type(), true);
+ }
+
TString get_input_type_name() const {
- return method_->input_type()->file()->name();
- }
+ return method_->input_type()->file()->name();
+ }
TString get_output_type_name() const {
- return method_->output_type()->file()->name();
- }
-
+ return method_->output_type()->file()->name();
+ }
+
// 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,
+ return grpc_python_generator::GetModuleAndMessagePath(
+ method_->input_type(), str, generator_file_name, generate_in_pb2_grpc,
import_prefix, prefixes_to_filter);
- }
-
+ }
+
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,
+ return grpc_python_generator::GetModuleAndMessagePath(
+ method_->output_type(), str, generator_file_name, generate_in_pb2_grpc,
import_prefix, prefixes_to_filter);
- }
-
- bool NoStreaming() const {
- return !method_->client_streaming() && !method_->server_streaming();
- }
-
- bool ClientStreaming() const { return method_->client_streaming(); }
-
- bool ServerStreaming() const { return method_->server_streaming(); }
-
- bool BidiStreaming() const {
- return method_->client_streaming() && method_->server_streaming();
- }
-
+ }
+
+ bool NoStreaming() const {
+ return !method_->client_streaming() && !method_->server_streaming();
+ }
+
+ bool ClientStreaming() const { return method_->client_streaming(); }
+
+ bool ServerStreaming() const { return method_->server_streaming(); }
+
+ bool BidiStreaming() const {
+ return method_->client_streaming() && method_->server_streaming();
+ }
+
TString GetLeadingComments(const TString prefix) const {
- return GetCommentsHelper(method_, true, prefix);
- }
-
+ return GetCommentsHelper(method_, true, prefix);
+ }
+
TString GetTrailingComments(const TString prefix) const {
- return GetCommentsHelper(method_, false, prefix);
- }
-
+ return GetCommentsHelper(method_, false, prefix);
+ }
+
vector<TString> GetAllComments() const {
- return grpc_python_generator::get_all_comments(method_);
- }
-
- private:
- const grpc::protobuf::MethodDescriptor* method_;
-};
-
-class ProtoBufService : public grpc_generator::Service {
- public:
- ProtoBufService(const grpc::protobuf::ServiceDescriptor* service)
- : service_(service) {}
-
+ return grpc_python_generator::get_all_comments(method_);
+ }
+
+ private:
+ const grpc::protobuf::MethodDescriptor* method_;
+};
+
+class ProtoBufService : public grpc_generator::Service {
+ public:
+ ProtoBufService(const grpc::protobuf::ServiceDescriptor* service)
+ : service_(service) {}
+
TString name() const { return service_->name(); }
-
+
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)));
+ 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);
- }
-
+ return GetCommentsHelper(service_, true, prefix);
+ }
+
TString GetTrailingComments(const TString prefix) const {
- return GetCommentsHelper(service_, false, prefix);
- }
-
+ return GetCommentsHelper(service_, false, prefix);
+ }
+
vector<TString> GetAllComments() const {
- return grpc_python_generator::get_all_comments(service_);
- }
-
- private:
- const grpc::protobuf::ServiceDescriptor* service_;
-};
-
-class ProtoBufPrinter : public grpc_generator::Printer {
- public:
+ return grpc_python_generator::get_all_comments(service_);
+ }
+
+ private:
+ const grpc::protobuf::ServiceDescriptor* service_;
+};
+
+class ProtoBufPrinter : public grpc_generator::Printer {
+ public:
ProtoBufPrinter(TString* str)
- : output_stream_(str), printer_(&output_stream_, '$') {}
-
+ : output_stream_(str), printer_(&output_stream_, '$') {}
+
void Print(const std::map<TString, TString>& vars,
- const char* string_template) {
- printer_.Print(vars, string_template);
- }
-
- void Print(const char* string) { printer_.Print(string); }
- void PrintRaw(const char* string) { printer_.PrintRaw(string); }
- void Indent() { printer_.Indent(); }
- void Outdent() { printer_.Outdent(); }
-
- private:
- grpc::protobuf::io::StringOutputStream output_stream_;
- grpc::protobuf::io::Printer printer_;
-};
-
-class ProtoBufFile : public grpc_generator::File {
- public:
- ProtoBufFile(const grpc::protobuf::FileDescriptor* file) : file_(file) {}
-
+ const char* string_template) {
+ printer_.Print(vars, string_template);
+ }
+
+ void Print(const char* string) { printer_.Print(string); }
+ void PrintRaw(const char* string) { printer_.PrintRaw(string); }
+ void Indent() { printer_.Indent(); }
+ void Outdent() { printer_.Outdent(); }
+
+ private:
+ grpc::protobuf::io::StringOutputStream output_stream_;
+ grpc::protobuf::io::Printer printer_;
+};
+
+class ProtoBufFile : public grpc_generator::File {
+ public:
+ ProtoBufFile(const grpc::protobuf::FileDescriptor* file) : file_(file) {}
+
TString filename() const { return file_->name(); }
TString filename_without_ext() const {
- return grpc_generator::StripProto(filename());
- }
-
+ return grpc_generator::StripProto(filename());
+ }
+
TString package() const { return file_->package(); }
std::vector<TString> package_parts() const {
- return grpc_generator::tokenize(package(), ".");
- }
-
+ return grpc_generator::tokenize(package(), ".");
+ }
+
TString additional_headers() const { return ""; }
-
+
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)));
- }
-
- std::unique_ptr<grpc_generator::Printer> CreatePrinter(
+ std::unique_ptr<const grpc_generator::Service> service(int i) const {
+ return std::unique_ptr<const grpc_generator::Service>(
+ new ProtoBufService(file_->service(i)));
+ }
+
+ std::unique_ptr<grpc_generator::Printer> CreatePrinter(
TString* str) const {
- return std::unique_ptr<grpc_generator::Printer>(new ProtoBufPrinter(str));
- }
-
+ return std::unique_ptr<grpc_generator::Printer>(new ProtoBufPrinter(str));
+ }
+
TString GetLeadingComments(const TString prefix) const {
- return GetCommentsHelper(file_, true, prefix);
- }
-
+ return GetCommentsHelper(file_, true, prefix);
+ }
+
TString GetTrailingComments(const TString prefix) const {
- return GetCommentsHelper(file_, false, prefix);
- }
-
+ return GetCommentsHelper(file_, false, prefix);
+ }
+
vector<TString> GetAllComments() const {
- return grpc_python_generator::get_all_comments(file_);
- }
-
+ return grpc_python_generator::get_all_comments(file_);
+ }
+
vector<TString> GetImportNames() const {
vector<TString> proto_names;
for (int i = 0; i < file_->dependency_count(); ++i) {
@@ -199,8 +199,8 @@ class ProtoBufFile : public grpc_generator::File {
return proto_names;
}
- private:
- const grpc::protobuf::FileDescriptor* file_;
-};
-
-#endif // GRPC_INTERNAL_COMPILER_PROTOBUF_PLUGIN_H
+ private:
+ const grpc::protobuf::FileDescriptor* file_;
+};
+
+#endif // GRPC_INTERNAL_COMPILER_PROTOBUF_PLUGIN_H
diff --git a/contrib/libs/grpc/src/compiler/python_generator.cc b/contrib/libs/grpc/src/compiler/python_generator.cc
index d083d19f0b3..149f3a1e78a 100644
--- a/contrib/libs/grpc/src/compiler/python_generator.cc
+++ b/contrib/libs/grpc/src/compiler/python_generator.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -32,10 +32,10 @@
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
-#include "src/compiler/protobuf_plugin.h"
+#include "src/compiler/protobuf_plugin.h"
#include "src/compiler/python_generator.h"
-#include "src/compiler/python_generator_helpers.h"
-#include "src/compiler/python_private_generator.h"
+#include "src/compiler/python_generator_helpers.h"
+#include "src/compiler/python_private_generator.h"
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::compiler::GeneratorContext;
@@ -45,14 +45,14 @@ using std::make_pair;
using std::map;
using std::pair;
using std::replace;
-using std::set;
+using std::set;
using std::tuple;
using std::vector;
namespace grpc_python_generator {
TString generator_file_name;
-
+
namespace {
typedef map<TString, TString> StringMap;
@@ -69,7 +69,7 @@ typedef set<StringPair> StringPairSet;
// }
class IndentScope {
public:
- explicit IndentScope(grpc_generator::Printer* printer) : printer_(printer) {
+ explicit IndentScope(grpc_generator::Printer* printer) : printer_(printer) {
// NOTE(rbellevi): Two-space tabs are hard-coded in the protocol compiler.
// Doubling our indents and outdents guarantees compliance with PEP8.
printer_->Indent();
@@ -82,22 +82,22 @@ class IndentScope {
}
private:
- grpc_generator::Printer* printer_;
+ grpc_generator::Printer* printer_;
};
PrivateGenerator::PrivateGenerator(const GeneratorConfiguration& config,
- const grpc_generator::File* file)
+ const grpc_generator::File* file)
: config(config), file(file) {}
-void PrivateGenerator::PrintAllComments(StringVector comments,
- grpc_generator::Printer* out) {
+void PrivateGenerator::PrintAllComments(StringVector comments,
+ grpc_generator::Printer* out) {
if (comments.empty()) {
- // Python requires code structures like class and def to have
- // a body, even if it is just "pass" or a docstring. We need
- // to ensure not to generate empty bodies. We could do something
- // smarter and more sophisticated, but at the moment, if there is
- // no docstring to print, we simply emit "pass" to ensure validity
- // of the generated code.
+ // Python requires code structures like class and def to have
+ // a body, even if it is just "pass" or a docstring. We need
+ // to ensure not to generate empty bodies. We could do something
+ // smarter and more sophisticated, but at the moment, if there is
+ // no docstring to print, we simply emit "pass" to ensure validity
+ // of the generated code.
out->Print(
"\"\"\"Missing associated documentation comment in .proto "
"file.\"\"\"\n");
@@ -108,19 +108,19 @@ void PrivateGenerator::PrintAllComments(StringVector comments,
++it) {
size_t start_pos = it->find_first_not_of(' ');
if (start_pos != TString::npos) {
- out->PrintRaw(it->c_str() + start_pos);
+ out->PrintRaw(it->c_str() + start_pos);
}
out->Print("\n");
}
out->Print("\"\"\"\n");
}
-bool PrivateGenerator::PrintBetaServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
+bool PrivateGenerator::PrintBetaServicer(const grpc_generator::Service* service,
+ grpc_generator::Printer* out) {
+ StringMap service_dict;
+ service_dict["Service"] = service->name();
out->Print("\n\n");
- out->Print(service_dict, "class Beta$Service$Servicer(object):\n");
+ out->Print(service_dict, "class Beta$Service$Servicer(object):\n");
{
IndentScope raii_class_indent(out);
out->Print(
@@ -130,20 +130,20 @@ bool PrivateGenerator::PrintBetaServicer(const grpc_generator::Service* service,
"generated\n"
"only to ease transition from grpcio<0.15.0 to "
"grpcio>=0.15.0.\"\"\"\n");
- StringVector service_comments = service->GetAllComments();
- PrintAllComments(service_comments, out);
+ StringVector service_comments = service->GetAllComments();
+ PrintAllComments(service_comments, out);
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
TString arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
- out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
+ method->ClientStreaming() ? "request_iterator" : "request";
+ StringMap method_dict;
+ method_dict["Method"] = method->name();
+ method_dict["ArgName"] = arg_name;
+ out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
{
IndentScope raii_method_indent(out);
- StringVector method_comments = method->GetAllComments();
- PrintAllComments(method_comments, out);
+ StringVector method_comments = method->GetAllComments();
+ PrintAllComments(method_comments, out);
out->Print("context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)\n");
}
}
@@ -151,12 +151,12 @@ bool PrivateGenerator::PrintBetaServicer(const grpc_generator::Service* service,
return true;
}
-bool PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
+bool PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
+ grpc_generator::Printer* out) {
+ StringMap service_dict;
+ service_dict["Service"] = service->name();
out->Print("\n\n");
- out->Print(service_dict, "class Beta$Service$Stub(object):\n");
+ out->Print(service_dict, "class Beta$Service$Stub(object):\n");
{
IndentScope raii_class_indent(out);
out->Print(
@@ -166,12 +166,12 @@ bool PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
"generated\n"
"only to ease transition from grpcio<0.15.0 to "
"grpcio>=0.15.0.\"\"\"\n");
- StringVector service_comments = service->GetAllComments();
- PrintAllComments(service_comments, out);
+ StringVector service_comments = service->GetAllComments();
+ PrintAllComments(service_comments, out);
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
TString arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
+ method->ClientStreaming() ? "request_iterator" : "request";
StringMap method_dict;
method_dict["Method"] = method->name();
method_dict["ArgName"] = arg_name;
@@ -180,11 +180,11 @@ bool PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
"with_call=False, protocol_options=None):\n");
{
IndentScope raii_method_indent(out);
- StringVector method_comments = method->GetAllComments();
- PrintAllComments(method_comments, out);
+ StringVector method_comments = method->GetAllComments();
+ PrintAllComments(method_comments, out);
out->Print("raise NotImplementedError()\n");
}
- if (!method->ServerStreaming()) {
+ if (!method->ServerStreaming()) {
out->Print(method_dict, "$Method$.future = None\n");
}
}
@@ -194,13 +194,13 @@ bool PrivateGenerator::PrintBetaStub(const grpc_generator::Service* service,
bool PrivateGenerator::PrintBetaServerFactory(
const TString& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
+ const grpc_generator::Service* service, grpc_generator::Printer* out) {
+ StringMap service_dict;
+ service_dict["Service"] = service->name();
out->Print("\n\n");
- out->Print(service_dict,
- "def beta_create_$Service$_server(servicer, pool=None, "
- "pool_size=None, default_timeout=None, maximum_timeout=None):\n");
+ out->Print(service_dict,
+ "def beta_create_$Service$_server(servicer, pool=None, "
+ "pool_size=None, default_timeout=None, maximum_timeout=None):\n");
{
IndentScope raii_create_server_indent(out);
out->Print(
@@ -213,21 +213,21 @@ bool PrivateGenerator::PrintBetaServerFactory(
StringMap input_message_modules_and_classes;
StringMap output_message_modules_and_classes;
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
const TString method_implementation_constructor =
TString(method->ClientStreaming() ? "stream_" : "unary_") +
TString(method->ServerStreaming() ? "stream_" : "unary_") +
"inline";
TString input_message_module_and_class;
- if (!method->get_module_and_message_path_input(
- &input_message_module_and_class, generator_file_name,
+ 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)) {
return false;
}
TString output_message_module_and_class;
- if (!method->get_module_and_message_path_output(
- &output_message_module_and_class, generator_file_name,
+ 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)) {
return false;
@@ -239,21 +239,21 @@ bool PrivateGenerator::PrintBetaServerFactory(
output_message_modules_and_classes.insert(
make_pair(method->name(), output_message_module_and_class));
}
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
+ StringMap method_dict;
+ method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
out->Print("request_deserializers = {\n");
for (StringMap::iterator name_and_input_module_class_pair =
input_message_modules_and_classes.begin();
name_and_input_module_class_pair !=
input_message_modules_and_classes.end();
name_and_input_module_class_pair++) {
- method_dict["MethodName"] = name_and_input_module_class_pair->first;
- method_dict["InputTypeModuleAndClass"] =
- name_and_input_module_class_pair->second;
+ method_dict["MethodName"] = name_and_input_module_class_pair->first;
+ method_dict["InputTypeModuleAndClass"] =
+ name_and_input_module_class_pair->second;
IndentScope raii_indent(out);
- out->Print(method_dict,
- "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
- "$InputTypeModuleAndClass$.FromString,\n");
+ out->Print(method_dict,
+ "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
+ "$InputTypeModuleAndClass$.FromString,\n");
}
out->Print("}\n");
out->Print("response_serializers = {\n");
@@ -262,13 +262,13 @@ bool PrivateGenerator::PrintBetaServerFactory(
name_and_output_module_class_pair !=
output_message_modules_and_classes.end();
name_and_output_module_class_pair++) {
- method_dict["MethodName"] = name_and_output_module_class_pair->first;
- method_dict["OutputTypeModuleAndClass"] =
- name_and_output_module_class_pair->second;
+ method_dict["MethodName"] = name_and_output_module_class_pair->first;
+ method_dict["OutputTypeModuleAndClass"] =
+ name_and_output_module_class_pair->second;
IndentScope raii_indent(out);
- out->Print(method_dict,
- "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
- "$OutputTypeModuleAndClass$.SerializeToString,\n");
+ out->Print(method_dict,
+ "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
+ "$OutputTypeModuleAndClass$.SerializeToString,\n");
}
out->Print("}\n");
out->Print("method_implementations = {\n");
@@ -277,14 +277,14 @@ bool PrivateGenerator::PrintBetaServerFactory(
name_and_implementation_constructor !=
method_implementation_constructors.end();
name_and_implementation_constructor++) {
- method_dict["Method"] = name_and_implementation_constructor->first;
- method_dict["Constructor"] = name_and_implementation_constructor->second;
+ method_dict["Method"] = name_and_implementation_constructor->first;
+ method_dict["Constructor"] = name_and_implementation_constructor->second;
IndentScope raii_descriptions_indent(out);
const TString method_name =
name_and_implementation_constructor->first;
- out->Print(method_dict,
- "(\'$PackageQualifiedServiceName$\', \'$Method$\'): "
- "face_utilities.$Constructor$(servicer.$Method$),\n");
+ out->Print(method_dict,
+ "(\'$PackageQualifiedServiceName$\', \'$Method$\'): "
+ "face_utilities.$Constructor$(servicer.$Method$),\n");
}
out->Print("}\n");
out->Print(
@@ -303,7 +303,7 @@ bool PrivateGenerator::PrintBetaServerFactory(
bool PrivateGenerator::PrintBetaStubFactory(
const TString& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
+ const grpc_generator::Service* service, grpc_generator::Printer* out) {
StringMap dict;
dict["Service"] = service->name();
out->Print("\n\n");
@@ -322,20 +322,20 @@ bool PrivateGenerator::PrintBetaStubFactory(
StringMap input_message_modules_and_classes;
StringMap output_message_modules_and_classes;
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
const TString method_cardinality =
TString(method->ClientStreaming() ? "STREAM" : "UNARY") + "_" +
TString(method->ServerStreaming() ? "STREAM" : "UNARY");
TString input_message_module_and_class;
- if (!method->get_module_and_message_path_input(
- &input_message_module_and_class, generator_file_name,
+ 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)) {
return false;
}
TString output_message_module_and_class;
- if (!method->get_module_and_message_path_output(
- &output_message_module_and_class, generator_file_name,
+ 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)) {
return false;
@@ -347,21 +347,21 @@ bool PrivateGenerator::PrintBetaStubFactory(
output_message_modules_and_classes.insert(
make_pair(method->name(), output_message_module_and_class));
}
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
+ StringMap method_dict;
+ method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
out->Print("request_serializers = {\n");
for (StringMap::iterator name_and_input_module_class_pair =
input_message_modules_and_classes.begin();
name_and_input_module_class_pair !=
input_message_modules_and_classes.end();
name_and_input_module_class_pair++) {
- method_dict["MethodName"] = name_and_input_module_class_pair->first;
- method_dict["InputTypeModuleAndClass"] =
- name_and_input_module_class_pair->second;
+ method_dict["MethodName"] = name_and_input_module_class_pair->first;
+ method_dict["InputTypeModuleAndClass"] =
+ name_and_input_module_class_pair->second;
IndentScope raii_indent(out);
- out->Print(method_dict,
- "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
- "$InputTypeModuleAndClass$.SerializeToString,\n");
+ out->Print(method_dict,
+ "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
+ "$InputTypeModuleAndClass$.SerializeToString,\n");
}
out->Print("}\n");
out->Print("response_deserializers = {\n");
@@ -370,13 +370,13 @@ bool PrivateGenerator::PrintBetaStubFactory(
name_and_output_module_class_pair !=
output_message_modules_and_classes.end();
name_and_output_module_class_pair++) {
- method_dict["MethodName"] = name_and_output_module_class_pair->first;
- method_dict["OutputTypeModuleAndClass"] =
- name_and_output_module_class_pair->second;
+ method_dict["MethodName"] = name_and_output_module_class_pair->first;
+ method_dict["OutputTypeModuleAndClass"] =
+ name_and_output_module_class_pair->second;
IndentScope raii_indent(out);
- out->Print(method_dict,
- "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
- "$OutputTypeModuleAndClass$.FromString,\n");
+ out->Print(method_dict,
+ "(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
+ "$OutputTypeModuleAndClass$.FromString,\n");
}
out->Print("}\n");
out->Print("cardinalities = {\n");
@@ -384,11 +384,11 @@ bool PrivateGenerator::PrintBetaStubFactory(
method_cardinalities.begin();
name_and_cardinality != method_cardinalities.end();
name_and_cardinality++) {
- method_dict["Method"] = name_and_cardinality->first;
- method_dict["Cardinality"] = name_and_cardinality->second;
+ method_dict["Method"] = name_and_cardinality->first;
+ method_dict["Cardinality"] = name_and_cardinality->second;
IndentScope raii_descriptions_indent(out);
- out->Print(method_dict,
- "\'$Method$\': cardinality.Cardinality.$Cardinality$,\n");
+ out->Print(method_dict,
+ "\'$Method$\': cardinality.Cardinality.$Cardinality$,\n");
}
out->Print("}\n");
out->Print(
@@ -397,25 +397,25 @@ bool PrivateGenerator::PrintBetaStubFactory(
"request_serializers=request_serializers, "
"response_deserializers=response_deserializers, "
"thread_pool=pool, thread_pool_size=pool_size)\n");
- out->Print(method_dict,
- "return beta_implementations.dynamic_stub(channel, "
- "\'$PackageQualifiedServiceName$\', "
- "cardinalities, options=stub_options)\n");
+ out->Print(method_dict,
+ "return beta_implementations.dynamic_stub(channel, "
+ "\'$PackageQualifiedServiceName$\', "
+ "cardinalities, options=stub_options)\n");
}
return true;
}
bool PrivateGenerator::PrintStub(
const TString& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap dict;
- dict["Service"] = service->name();
+ const grpc_generator::Service* service, grpc_generator::Printer* out) {
+ StringMap dict;
+ dict["Service"] = service->name();
out->Print("\n\n");
- out->Print(dict, "class $Service$Stub(object):\n");
+ out->Print(dict, "class $Service$Stub(object):\n");
{
IndentScope raii_class_indent(out);
- StringVector service_comments = service->GetAllComments();
- PrintAllComments(service_comments, out);
+ StringVector service_comments = service->GetAllComments();
+ PrintAllComments(service_comments, out);
out->Print("\n");
out->Print("def __init__(self, channel):\n");
{
@@ -429,43 +429,43 @@ bool PrivateGenerator::PrintStub(
}
out->Print("\"\"\"\n");
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
TString multi_callable_constructor =
TString(method->ClientStreaming() ? "stream" : "unary") + "_" +
TString(method->ServerStreaming() ? "stream" : "unary");
TString request_module_and_class;
- if (!method->get_module_and_message_path_input(
- &request_module_and_class, generator_file_name,
+ 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)) {
return false;
}
TString response_module_and_class;
- if (!method->get_module_and_message_path_output(
- &response_module_and_class, generator_file_name,
+ 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)) {
return false;
}
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["MultiCallableConstructor"] = multi_callable_constructor;
- out->Print(method_dict,
- "self.$Method$ = channel.$MultiCallableConstructor$(\n");
+ StringMap method_dict;
+ method_dict["Method"] = method->name();
+ method_dict["MultiCallableConstructor"] = multi_callable_constructor;
+ out->Print(method_dict,
+ "self.$Method$ = channel.$MultiCallableConstructor$(\n");
{
- method_dict["PackageQualifiedService"] =
- package_qualified_service_name;
- method_dict["RequestModuleAndClass"] = request_module_and_class;
- method_dict["ResponseModuleAndClass"] = response_module_and_class;
+ method_dict["PackageQualifiedService"] =
+ package_qualified_service_name;
+ method_dict["RequestModuleAndClass"] = request_module_and_class;
+ method_dict["ResponseModuleAndClass"] = response_module_and_class;
IndentScope raii_first_attribute_indent(out);
IndentScope raii_second_attribute_indent(out);
- out->Print(method_dict, "'/$PackageQualifiedService$/$Method$',\n");
- out->Print(method_dict,
- "request_serializer=$RequestModuleAndClass$."
- "SerializeToString,\n");
+ out->Print(method_dict, "'/$PackageQualifiedService$/$Method$',\n");
+ out->Print(method_dict,
+ "request_serializer=$RequestModuleAndClass$."
+ "SerializeToString,\n");
out->Print(
- method_dict,
- "response_deserializer=$ResponseModuleAndClass$.FromString,\n");
+ method_dict,
+ "response_deserializer=$ResponseModuleAndClass$.FromString,\n");
out->Print(")\n");
}
}
@@ -474,29 +474,29 @@ bool PrivateGenerator::PrintStub(
return true;
}
-bool PrivateGenerator::PrintServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
+bool PrivateGenerator::PrintServicer(const grpc_generator::Service* service,
+ grpc_generator::Printer* out) {
+ StringMap service_dict;
+ service_dict["Service"] = service->name();
out->Print("\n\n");
- out->Print(service_dict, "class $Service$Servicer(object):\n");
+ out->Print(service_dict, "class $Service$Servicer(object):\n");
{
IndentScope raii_class_indent(out);
- StringVector service_comments = service->GetAllComments();
- PrintAllComments(service_comments, out);
+ StringVector service_comments = service->GetAllComments();
+ PrintAllComments(service_comments, out);
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
TString arg_name =
- method->ClientStreaming() ? "request_iterator" : "request";
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["ArgName"] = arg_name;
+ method->ClientStreaming() ? "request_iterator" : "request";
+ StringMap method_dict;
+ method_dict["Method"] = method->name();
+ method_dict["ArgName"] = arg_name;
out->Print("\n");
- out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
+ out->Print(method_dict, "def $Method$(self, $ArgName$, context):\n");
{
IndentScope raii_method_indent(out);
- StringVector method_comments = method->GetAllComments();
- PrintAllComments(method_comments, out);
+ StringVector method_comments = method->GetAllComments();
+ PrintAllComments(method_comments, out);
out->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n");
out->Print("context.set_details('Method not implemented!')\n");
out->Print("raise NotImplementedError('Method not implemented!')\n");
@@ -508,12 +508,12 @@ bool PrivateGenerator::PrintServicer(const grpc_generator::Service* service,
bool PrivateGenerator::PrintAddServicerToServer(
const TString& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out) {
- StringMap service_dict;
- service_dict["Service"] = service->name();
+ const grpc_generator::Service* service, grpc_generator::Printer* out) {
+ StringMap service_dict;
+ service_dict["Service"] = service->name();
out->Print("\n\n");
- out->Print(service_dict,
- "def add_$Service$Servicer_to_server(servicer, server):\n");
+ out->Print(service_dict,
+ "def add_$Service$Servicer_to_server(servicer, server):\n");
{
IndentScope raii_class_indent(out);
out->Print("rpc_method_handlers = {\n");
@@ -521,56 +521,56 @@ bool PrivateGenerator::PrintAddServicerToServer(
IndentScope raii_dict_first_indent(out);
IndentScope raii_dict_second_indent(out);
for (int i = 0; i < service->method_count(); ++i) {
- auto method = service->method(i);
+ auto method = service->method(i);
TString method_handler_constructor =
TString(method->ClientStreaming() ? "stream" : "unary") + "_" +
TString(method->ServerStreaming() ? "stream" : "unary") +
"_rpc_method_handler";
TString request_module_and_class;
- if (!method->get_module_and_message_path_input(
- &request_module_and_class, generator_file_name,
+ 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)) {
return false;
}
TString response_module_and_class;
- if (!method->get_module_and_message_path_output(
- &response_module_and_class, generator_file_name,
+ 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)) {
return false;
}
- StringMap method_dict;
- method_dict["Method"] = method->name();
- method_dict["MethodHandlerConstructor"] = method_handler_constructor;
- method_dict["RequestModuleAndClass"] = request_module_and_class;
- method_dict["ResponseModuleAndClass"] = response_module_and_class;
- out->Print(method_dict,
- "'$Method$': grpc.$MethodHandlerConstructor$(\n");
+ StringMap method_dict;
+ method_dict["Method"] = method->name();
+ method_dict["MethodHandlerConstructor"] = method_handler_constructor;
+ method_dict["RequestModuleAndClass"] = request_module_and_class;
+ method_dict["ResponseModuleAndClass"] = response_module_and_class;
+ out->Print(method_dict,
+ "'$Method$': grpc.$MethodHandlerConstructor$(\n");
{
IndentScope raii_call_first_indent(out);
IndentScope raii_call_second_indent(out);
- out->Print(method_dict, "servicer.$Method$,\n");
+ out->Print(method_dict, "servicer.$Method$,\n");
out->Print(
- method_dict,
- "request_deserializer=$RequestModuleAndClass$.FromString,\n");
+ method_dict,
+ "request_deserializer=$RequestModuleAndClass$.FromString,\n");
out->Print(
- method_dict,
+ method_dict,
"response_serializer=$ResponseModuleAndClass$.SerializeToString,"
- "\n");
+ "\n");
}
out->Print("),\n");
}
}
- StringMap method_dict;
- method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
+ StringMap method_dict;
+ method_dict["PackageQualifiedServiceName"] = package_qualified_service_name;
out->Print("}\n");
out->Print("generic_handler = grpc.method_handlers_generic_handler(\n");
{
IndentScope raii_call_first_indent(out);
IndentScope raii_call_second_indent(out);
- out->Print(method_dict,
- "'$PackageQualifiedServiceName$', rpc_method_handlers)\n");
+ out->Print(method_dict,
+ "'$PackageQualifiedServiceName$', rpc_method_handlers)\n");
}
out->Print("server.add_generic_rpc_handlers((generic_handler,))\n");
}
@@ -665,31 +665,31 @@ bool PrivateGenerator::PrintServiceClass(
return true;
}
-bool PrivateGenerator::PrintBetaPreamble(grpc_generator::Printer* out) {
- StringMap var;
- var["Package"] = config.beta_package_root;
- out->Print(var,
- "from $Package$ import implementations as beta_implementations\n");
- out->Print(var, "from $Package$ import interfaces as beta_interfaces\n");
+bool PrivateGenerator::PrintBetaPreamble(grpc_generator::Printer* out) {
+ StringMap var;
+ var["Package"] = config.beta_package_root;
+ out->Print(var,
+ "from $Package$ import implementations as beta_implementations\n");
+ out->Print(var, "from $Package$ import interfaces as beta_interfaces\n");
out->Print("from grpc.framework.common import cardinality\n");
out->Print(
"from grpc.framework.interfaces.face import utilities as "
"face_utilities\n");
- return true;
-}
-
-bool PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
- StringMap var;
- var["Package"] = config.grpc_package_root;
- out->Print(var, "import $Package$\n");
+ return true;
+}
+
+bool PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
+ StringMap var;
+ var["Package"] = config.grpc_package_root;
+ out->Print(var, "import $Package$\n");
if (generate_in_pb2_grpc) {
out->Print("\n");
StringPairSet imports_set;
for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
+ auto service = file->service(i);
for (int j = 0; j < service->method_count(); ++j) {
- auto method = service.get()->method(j);
-
+ auto method = service.get()->method(j);
+
TString input_type_file_name = method->get_input_type_name();
TString input_module_name =
ModuleName(input_type_file_name, config.import_prefix,
@@ -697,9 +697,9 @@ bool PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
TString input_module_alias =
ModuleAlias(input_type_file_name, config.import_prefix,
config.prefixes_to_filter);
- imports_set.insert(
- std::make_tuple(input_module_name, input_module_alias));
-
+ 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,
@@ -707,40 +707,40 @@ bool PrivateGenerator::PrintPreamble(grpc_generator::Printer* out) {
TString output_module_alias =
ModuleAlias(output_type_file_name, config.import_prefix,
config.prefixes_to_filter);
- imports_set.insert(
- std::make_tuple(output_module_name, output_module_alias));
+ imports_set.insert(
+ std::make_tuple(output_module_name, output_module_alias));
}
}
-
+
for (StringPairSet::iterator it = imports_set.begin();
it != imports_set.end(); ++it) {
- auto module_name = std::get<0>(*it);
- var["ModuleAlias"] = std::get<1>(*it);
- const size_t last_dot_pos = module_name.rfind('.');
+ auto module_name = std::get<0>(*it);
+ var["ModuleAlias"] = std::get<1>(*it);
+ const size_t last_dot_pos = module_name.rfind('.');
if (last_dot_pos == TString::npos) {
- var["ImportStatement"] = "import " + module_name;
- } else {
- var["ImportStatement"] = "from " + module_name.substr(0, last_dot_pos) +
- " import " +
- module_name.substr(last_dot_pos + 1);
- }
- out->Print(var, "$ImportStatement$ as $ModuleAlias$\n");
+ var["ImportStatement"] = "import " + module_name;
+ } else {
+ var["ImportStatement"] = "from " + module_name.substr(0, last_dot_pos) +
+ " import " +
+ module_name.substr(last_dot_pos + 1);
+ }
+ out->Print(var, "$ImportStatement$ as $ModuleAlias$\n");
}
}
return true;
}
-bool PrivateGenerator::PrintGAServices(grpc_generator::Printer* out) {
+bool PrivateGenerator::PrintGAServices(grpc_generator::Printer* out) {
TString package = file->package();
if (!package.empty()) {
package = package.append(".");
}
for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
+ auto service = file->service(i);
TString package_qualified_service_name = package + service->name();
- if (!(PrintStub(package_qualified_service_name, service.get(), out) &&
- PrintServicer(service.get(), out) &&
- PrintAddServicerToServer(package_qualified_service_name,
+ if (!(PrintStub(package_qualified_service_name, service.get(), out) &&
+ PrintServicer(service.get(), out) &&
+ PrintAddServicerToServer(package_qualified_service_name,
service.get(), out) &&
PrintServiceClass(package_qualified_service_name, service.get(),
out))) {
@@ -750,20 +750,20 @@ bool PrivateGenerator::PrintGAServices(grpc_generator::Printer* out) {
return true;
}
-bool PrivateGenerator::PrintBetaServices(grpc_generator::Printer* out) {
+bool PrivateGenerator::PrintBetaServices(grpc_generator::Printer* out) {
TString package = file->package();
if (!package.empty()) {
package = package.append(".");
}
for (int i = 0; i < file->service_count(); ++i) {
- auto service = file->service(i);
+ auto service = file->service(i);
TString package_qualified_service_name = package + service->name();
- if (!(PrintBetaServicer(service.get(), out) &&
- PrintBetaStub(service.get(), out) &&
- PrintBetaServerFactory(package_qualified_service_name, service.get(),
- out) &&
- PrintBetaStubFactory(package_qualified_service_name, service.get(),
- out))) {
+ if (!(PrintBetaServicer(service.get(), out) &&
+ PrintBetaStub(service.get(), out) &&
+ PrintBetaServerFactory(package_qualified_service_name, service.get(),
+ out) &&
+ PrintBetaStubFactory(package_qualified_service_name, service.get(),
+ out))) {
return false;
}
}
@@ -774,42 +774,42 @@ pair<bool, TString> PrivateGenerator::GetGrpcServices() {
TString output;
{
// Scope the output stream so it closes and finalizes output to the string.
- auto out = file->CreatePrinter(&output);
+ auto out = file->CreatePrinter(&output);
if (generate_in_pb2_grpc) {
out->Print(
"# Generated by the gRPC Python protocol compiler plugin. "
"DO NOT EDIT!\n\"\"\""
"Client and server classes corresponding to protobuf-defined "
"services.\"\"\"\n");
- if (!PrintPreamble(out.get())) {
+ if (!PrintPreamble(out.get())) {
return make_pair(false, "");
}
- if (!PrintGAServices(out.get())) {
+ if (!PrintGAServices(out.get())) {
return make_pair(false, "");
}
} else {
out->Print("try:\n");
{
- IndentScope raii_dict_try_indent(out.get());
+ IndentScope raii_dict_try_indent(out.get());
out->Print(
"# THESE ELEMENTS WILL BE DEPRECATED.\n"
"# Please use the generated *_pb2_grpc.py files instead.\n");
- if (!PrintPreamble(out.get())) {
+ if (!PrintPreamble(out.get())) {
return make_pair(false, "");
}
- if (!PrintBetaPreamble(out.get())) {
+ if (!PrintBetaPreamble(out.get())) {
return make_pair(false, "");
}
- if (!PrintGAServices(out.get())) {
+ if (!PrintGAServices(out.get())) {
return make_pair(false, "");
}
- if (!PrintBetaServices(out.get())) {
+ if (!PrintBetaServices(out.get())) {
return make_pair(false, "");
}
}
out->Print("except ImportError:\n");
{
- IndentScope raii_dict_except_indent(out.get());
+ IndentScope raii_dict_except_indent(out.get());
out->Print("pass");
}
}
@@ -820,9 +820,9 @@ pair<bool, TString> PrivateGenerator::GetGrpcServices() {
} // namespace
GeneratorConfiguration::GeneratorConfiguration()
- : grpc_package_root("grpc"),
- beta_package_root("grpc.beta"),
- import_prefix("") {}
+ : grpc_package_root("grpc"),
+ beta_package_root("grpc.beta"),
+ import_prefix("") {}
PythonGrpcGenerator::PythonGrpcGenerator(const GeneratorConfiguration& config)
: config_(config) {}
@@ -900,9 +900,9 @@ bool PythonGrpcGenerator::Generate(const FileDescriptor* file,
*error = "Invalid proto file name. Proto file must end with .proto";
return false;
}
- generator_file_name = file->name();
+ generator_file_name = file->name();
- ProtoBufFile pbfile(file);
+ ProtoBufFile pbfile(file);
TString grpc_version;
GeneratorConfiguration extended_config(config_);
bool success = ParseParameters(parameter, &grpc_version,
diff --git a/contrib/libs/grpc/src/compiler/python_generator.h b/contrib/libs/grpc/src/compiler/python_generator.h
index bcde0a5e358..045e26c06bd 100644
--- a/contrib/libs/grpc/src/compiler/python_generator.h
+++ b/contrib/libs/grpc/src/compiler/python_generator.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -23,7 +23,7 @@
#include <vector>
#include "src/compiler/config.h"
-#include "src/compiler/schema_interface.h"
+#include "src/compiler/schema_interface.h"
namespace grpc_python_generator {
@@ -32,9 +32,9 @@ namespace grpc_python_generator {
struct GeneratorConfiguration {
GeneratorConfiguration();
TString grpc_package_root;
- // TODO(https://github.com/grpc/grpc/issues/8622): Drop this.
+ // TODO(https://github.com/grpc/grpc/issues/8622): Drop this.
TString beta_package_root;
- // TODO(https://github.com/google/protobuf/issues/888): Drop this.
+ // TODO(https://github.com/google/protobuf/issues/888): Drop this.
TString import_prefix;
std::vector<TString> prefixes_to_filter;
};
diff --git a/contrib/libs/grpc/src/compiler/python_generator_helpers.h b/contrib/libs/grpc/src/compiler/python_generator_helpers.h
index 78e7efd7e0d..c453ca0f67e 100644
--- a/contrib/libs/grpc/src/compiler/python_generator_helpers.h
+++ b/contrib/libs/grpc/src/compiler/python_generator_helpers.h
@@ -1,54 +1,54 @@
-/*
- *
- * 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_INTERNAL_COMPILER_PYTHON_GENERATOR_HELPERS_H
-#define GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_HELPERS_H
-
-#include <cstring>
-#include <fstream>
-#include <iostream>
-#include <vector>
-
-#include "src/compiler/config.h"
-#include "src/compiler/generator_helpers.h"
-#include "src/compiler/python_generator.h"
-#include "src/compiler/python_private_generator.h"
-
-using grpc::protobuf::Descriptor;
-using grpc::protobuf::FileDescriptor;
-using grpc::protobuf::MethodDescriptor;
-using grpc::protobuf::ServiceDescriptor;
-using grpc::protobuf::compiler::GeneratorContext;
-using grpc::protobuf::io::CodedOutputStream;
-using grpc::protobuf::io::Printer;
-using grpc::protobuf::io::StringOutputStream;
-using grpc::protobuf::io::ZeroCopyOutputStream;
-using grpc_generator::StringReplace;
-using grpc_generator::StripProto;
-using std::vector;
-
-namespace grpc_python_generator {
-
-namespace {
-
-typedef vector<const Descriptor*> DescriptorVector;
+/*
+ *
+ * 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_INTERNAL_COMPILER_PYTHON_GENERATOR_HELPERS_H
+#define GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_HELPERS_H
+
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <vector>
+
+#include "src/compiler/config.h"
+#include "src/compiler/generator_helpers.h"
+#include "src/compiler/python_generator.h"
+#include "src/compiler/python_private_generator.h"
+
+using grpc::protobuf::Descriptor;
+using grpc::protobuf::FileDescriptor;
+using grpc::protobuf::MethodDescriptor;
+using grpc::protobuf::ServiceDescriptor;
+using grpc::protobuf::compiler::GeneratorContext;
+using grpc::protobuf::io::CodedOutputStream;
+using grpc::protobuf::io::Printer;
+using grpc::protobuf::io::StringOutputStream;
+using grpc::protobuf::io::ZeroCopyOutputStream;
+using grpc_generator::StringReplace;
+using grpc_generator::StripProto;
+using std::vector;
+
+namespace grpc_python_generator {
+
+namespace {
+
+typedef vector<const Descriptor*> DescriptorVector;
typedef vector<TString> StringVector;
-
+
static TString StripModulePrefixes(
const TString& raw_module_name,
const std::vector<TString>& prefixes_to_filter) {
@@ -61,81 +61,81 @@ static TString StripModulePrefixes(
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.
+// TODO(https://github.com/google/protobuf/issues/888):
+// Export `ModuleName` from protobuf's
+// `src/google/protobuf/compiler/python/python_generator.cc` file.
TString ModuleName(const TString& filename,
const TString& import_prefix,
const std::vector<TString>& prefixes_to_filter) {
TString basename = StripProto(filename);
- basename = StringReplace(basename, "-", "_");
- basename = StringReplace(basename, "/", ".");
+ basename = StringReplace(basename, "-", "_");
+ basename = StringReplace(basename, "/", ".");
return StripModulePrefixes(import_prefix + basename + "_pb2",
prefixes_to_filter);
-}
-
-// TODO(https://github.com/google/protobuf/issues/888):
-// Export `ModuleAlias` from protobuf's
-// `src/google/protobuf/compiler/python/python_generator.cc` file.
+}
+
+// TODO(https://github.com/google/protobuf/issues/888):
+// Export `ModuleAlias` from protobuf's
+// `src/google/protobuf/compiler/python/python_generator.cc` file.
TString ModuleAlias(const TString& filename,
const TString& import_prefix,
const std::vector<TString>& prefixes_to_filter) {
TString module_name =
ModuleName(filename, import_prefix, prefixes_to_filter);
- // We can't have dots in the module name, so we replace each with _dot_.
- // But that could lead to a collision between a.b and a_dot_b, so we also
- // duplicate each underscore.
- module_name = StringReplace(module_name, "_", "__");
- module_name = StringReplace(module_name, ".", "_dot_");
- return module_name;
-}
-
+ // We can't have dots in the module name, so we replace each with _dot_.
+ // But that could lead to a collision between a.b and a_dot_b, so we also
+ // duplicate each underscore.
+ module_name = StringReplace(module_name, "_", "__");
+ module_name = StringReplace(module_name, ".", "_dot_");
+ return module_name;
+}
+
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) {
- const Descriptor* path_elem_type = type;
- DescriptorVector message_path;
- do {
- message_path.push_back(path_elem_type);
- path_elem_type = path_elem_type->containing_type();
- } while (path_elem_type); // implicit nullptr comparison; don't be explicit
+ const Descriptor* path_elem_type = type;
+ DescriptorVector message_path;
+ do {
+ message_path.push_back(path_elem_type);
+ path_elem_type = path_elem_type->containing_type();
+ } while (path_elem_type); // implicit nullptr comparison; don't be explicit
TString file_name = type->file()->name();
- static const int proto_suffix_length = strlen(".proto");
- if (!(file_name.size() > static_cast<size_t>(proto_suffix_length) &&
- file_name.find_last_of(".proto") == file_name.size() - 1)) {
- return false;
- }
-
+ static const int proto_suffix_length = strlen(".proto");
+ if (!(file_name.size() > static_cast<size_t>(proto_suffix_length) &&
+ file_name.find_last_of(".proto") == file_name.size() - 1)) {
+ return false;
+ }
+
TString module;
- if (generator_file_name != file_name || generate_in_pb2_grpc) {
+ if (generator_file_name != file_name || generate_in_pb2_grpc) {
module = ModuleAlias(file_name, import_prefix, prefixes_to_filter) + ".";
- } else {
- module = "";
- }
+ } else {
+ module = "";
+ }
TString message_type;
- for (DescriptorVector::reverse_iterator path_iter = message_path.rbegin();
- path_iter != message_path.rend(); ++path_iter) {
- message_type += (*path_iter)->name() + ".";
- }
- // no pop_back prior to C++11
- message_type.resize(message_type.size() - 1);
- *out = module + message_type;
- return true;
-}
-
-template <typename DescriptorType>
-StringVector get_all_comments(const DescriptorType* descriptor) {
- StringVector comments;
- grpc_generator::GetComment(
- descriptor, grpc_generator::COMMENTTYPE_LEADING_DETACHED, &comments);
- grpc_generator::GetComment(descriptor, grpc_generator::COMMENTTYPE_LEADING,
- &comments);
- grpc_generator::GetComment(descriptor, grpc_generator::COMMENTTYPE_TRAILING,
- &comments);
- return comments;
-}
-
+ for (DescriptorVector::reverse_iterator path_iter = message_path.rbegin();
+ path_iter != message_path.rend(); ++path_iter) {
+ message_type += (*path_iter)->name() + ".";
+ }
+ // no pop_back prior to C++11
+ message_type.resize(message_type.size() - 1);
+ *out = module + message_type;
+ return true;
+}
+
+template <typename DescriptorType>
+StringVector get_all_comments(const DescriptorType* descriptor) {
+ StringVector comments;
+ grpc_generator::GetComment(
+ descriptor, grpc_generator::COMMENTTYPE_LEADING_DETACHED, &comments);
+ grpc_generator::GetComment(descriptor, grpc_generator::COMMENTTYPE_LEADING,
+ &comments);
+ grpc_generator::GetComment(descriptor, grpc_generator::COMMENTTYPE_TRAILING,
+ &comments);
+ return comments;
+}
+
inline void Split(const TString& s, char delim,
std::vector<TString>* append_to) {
auto current = s.begin();
@@ -146,8 +146,8 @@ inline void Split(const TString& s, char delim,
}
}
-} // namespace
-
-} // namespace grpc_python_generator
-
-#endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_HELPERS_H
+} // namespace
+
+} // namespace grpc_python_generator
+
+#endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_HELPERS_H
diff --git a/contrib/libs/grpc/src/compiler/python_plugin.cc b/contrib/libs/grpc/src/compiler/python_plugin.cc
index 81eb1d4fc2e..75e1b769a51 100644
--- a/contrib/libs/grpc/src/compiler/python_plugin.cc
+++ b/contrib/libs/grpc/src/compiler/python_plugin.cc
@@ -1,25 +1,25 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 a Python gRPC service interface out of Protobuf IDL.
#include "src/compiler/config.h"
-#include "src/compiler/protobuf_plugin.h"
+#include "src/compiler/protobuf_plugin.h"
#include "src/compiler/python_generator.h"
int main(int argc, char* argv[]) {
diff --git a/contrib/libs/grpc/src/compiler/python_private_generator.h b/contrib/libs/grpc/src/compiler/python_private_generator.h
index 3039a38e122..85c84ab6bd8 100644
--- a/contrib/libs/grpc/src/compiler/python_private_generator.h
+++ b/contrib/libs/grpc/src/compiler/python_private_generator.h
@@ -1,87 +1,87 @@
-/*
- *
- * 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_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
-#define GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
-
-#include <iostream>
-#include <vector>
-
-#include "src/compiler/python_generator.h"
-#include "src/compiler/schema_interface.h"
-
-namespace grpc_python_generator {
-
-namespace {
-
-// Tucks all generator state in an anonymous namespace away from
-// PythonGrpcGenerator and the header file, mostly to encourage future changes
-// to not require updates to the grpcio-tools C++ code part. Assumes that it is
-// only ever used from a single thread.
-struct PrivateGenerator {
- const GeneratorConfiguration& config;
- const grpc_generator::File* file;
-
- bool generate_in_pb2_grpc;
-
- PrivateGenerator(const GeneratorConfiguration& config,
- const grpc_generator::File* file);
-
+/*
+ *
+ * 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_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
+#define GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
+
+#include <iostream>
+#include <vector>
+
+#include "src/compiler/python_generator.h"
+#include "src/compiler/schema_interface.h"
+
+namespace grpc_python_generator {
+
+namespace {
+
+// Tucks all generator state in an anonymous namespace away from
+// PythonGrpcGenerator and the header file, mostly to encourage future changes
+// to not require updates to the grpcio-tools C++ code part. Assumes that it is
+// only ever used from a single thread.
+struct PrivateGenerator {
+ const GeneratorConfiguration& config;
+ const grpc_generator::File* file;
+
+ bool generate_in_pb2_grpc;
+
+ PrivateGenerator(const GeneratorConfiguration& config,
+ const grpc_generator::File* file);
+
std::pair<bool, TString> GetGrpcServices();
-
- private:
- bool PrintPreamble(grpc_generator::Printer* out);
- bool PrintBetaPreamble(grpc_generator::Printer* out);
- bool PrintGAServices(grpc_generator::Printer* out);
- bool PrintBetaServices(grpc_generator::Printer* out);
-
- bool PrintAddServicerToServer(
+
+ private:
+ bool PrintPreamble(grpc_generator::Printer* out);
+ bool PrintBetaPreamble(grpc_generator::Printer* out);
+ bool PrintGAServices(grpc_generator::Printer* out);
+ bool PrintBetaServices(grpc_generator::Printer* out);
+
+ bool PrintAddServicerToServer(
const TString& package_qualified_service_name,
- const grpc_generator::Service* service, grpc_generator::Printer* out);
- bool PrintServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
+ const grpc_generator::Service* service, grpc_generator::Printer* out);
+ bool PrintServicer(const grpc_generator::Service* service,
+ grpc_generator::Printer* out);
bool PrintStub(const TString& package_qualified_service_name,
- const grpc_generator::Service* service,
- grpc_generator::Printer* out);
-
+ const grpc_generator::Service* service,
+ grpc_generator::Printer* out);
+
bool PrintServiceClass(const TString& package_qualified_service_name,
const grpc_generator::Service* service,
grpc_generator::Printer* out);
- bool PrintBetaServicer(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
+ bool PrintBetaServicer(const grpc_generator::Service* service,
+ grpc_generator::Printer* out);
bool PrintBetaServerFactory(const TString& package_qualified_service_name,
const grpc_generator::Service* service,
grpc_generator::Printer* out);
- bool PrintBetaStub(const grpc_generator::Service* service,
- grpc_generator::Printer* out);
+ bool PrintBetaStub(const grpc_generator::Service* service,
+ grpc_generator::Printer* out);
bool PrintBetaStubFactory(const TString& package_qualified_service_name,
- const grpc_generator::Service* service,
- grpc_generator::Printer* out);
-
- // Get all comments (leading, leading_detached, trailing) and print them as a
- // docstring. Any leading space of a line will be removed, but the line
- // wrapping will not be changed.
+ const grpc_generator::Service* service,
+ grpc_generator::Printer* out);
+
+ // Get all comments (leading, leading_detached, trailing) and print them as a
+ // docstring. Any leading space of a line will be removed, but the line
+ // wrapping will not be changed.
void PrintAllComments(std::vector<TString> comments,
- grpc_generator::Printer* out);
-};
-
-} // namespace
-
-} // namespace grpc_python_generator
-
-#endif // GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
+ grpc_generator::Printer* out);
+};
+
+} // namespace
+
+} // namespace grpc_python_generator
+
+#endif // GRPC_INTERNAL_COMPILER_PYTHON_PRIVATE_GENERATOR_H
diff --git a/contrib/libs/grpc/src/compiler/ruby_generator.cc b/contrib/libs/grpc/src/compiler/ruby_generator.cc
index c82e78fd640..770a7d55dde 100644
--- a/contrib/libs/grpc/src/compiler/ruby_generator.cc
+++ b/contrib/libs/grpc/src/compiler/ruby_generator.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -27,7 +27,7 @@
#include "src/compiler/ruby_generator_string-inl.h"
using grpc::protobuf::FileDescriptor;
-using grpc::protobuf::MethodDescriptor;
+using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
@@ -48,11 +48,11 @@ void PrintMethod(const MethodDescriptor* method, Printer* out) {
output_type = "stream(" + output_type + ")";
}
std::map<TString, TString> method_vars = ListToDict({
- "mth.name",
- method->name(),
- "input.type",
- input_type,
- "output.type",
+ "mth.name",
+ method->name(),
+ "input.type",
+ input_type,
+ "output.type",
output_type,
});
out->Print(GetRubyComments(method, true).c_str());
@@ -68,8 +68,8 @@ void PrintService(const ServiceDescriptor* service, Printer* out) {
// Begin the service module
std::map<TString, TString> module_vars = ListToDict({
- "module.name",
- Modularize(service->name()),
+ "module.name",
+ Modularize(service->name()),
});
out->Print(module_vars, "module $module.name$\n");
out->Indent();
@@ -160,9 +160,9 @@ TString GetServices(const FileDescriptor* file) {
// Write out a file header.
std::map<TString, TString> header_comment_vars = ListToDict({
- "file.name",
- file->name(),
- "file.package",
+ "file.name",
+ file->name(),
+ "file.package",
package_name,
});
out.Print("# Generated by the protocol buffer compiler. DO NOT EDIT!\n");
@@ -172,7 +172,7 @@ TString GetServices(const FileDescriptor* file) {
TString leading_comments = GetRubyComments(file, true);
if (!leading_comments.empty()) {
out.Print("# Original file comments:\n");
- out.PrintRaw(leading_comments.c_str());
+ out.PrintRaw(leading_comments.c_str());
}
out.Print("\n");
@@ -181,8 +181,8 @@ TString GetServices(const FileDescriptor* file) {
// that defines the messages used by the service. This is generated by the
// main ruby plugin.
std::map<TString, TString> dep_vars = ListToDict({
- "dep.name",
- MessagesRequireName(file),
+ "dep.name",
+ MessagesRequireName(file),
});
out.Print(dep_vars, "require '$dep.name$'\n");
@@ -191,8 +191,8 @@ TString GetServices(const FileDescriptor* file) {
std::vector<TString> modules = Split(package_name, '.');
for (size_t i = 0; i < modules.size(); ++i) {
std::map<TString, TString> module_vars = ListToDict({
- "module.name",
- PackageToModule(modules[i]),
+ "module.name",
+ PackageToModule(modules[i]),
});
out.Print(module_vars, "module $module.name$\n");
out.Indent();
diff --git a/contrib/libs/grpc/src/compiler/ruby_generator.h b/contrib/libs/grpc/src/compiler/ruby_generator.h
index 325dc02294a..b10d265166d 100644
--- a/contrib/libs/grpc/src/compiler/ruby_generator.h
+++ b/contrib/libs/grpc/src/compiler/ruby_generator.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/compiler/ruby_generator_helpers-inl.h b/contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h
index 9a109766194..c9949f74dfa 100644
--- a/contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h
+++ b/contrib/libs/grpc/src/compiler/ruby_generator_helpers-inl.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -25,7 +25,7 @@
namespace grpc_ruby_generator {
-inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file,
+inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file,
TString* file_name_or_error) {
// Get output file name.
static const unsigned proto_suffix_length = 6; // length of ".proto"
@@ -42,7 +42,7 @@ inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file,
}
inline TString MessagesRequireName(
- const grpc::protobuf::FileDescriptor* file) {
+ const grpc::protobuf::FileDescriptor* file) {
return Replace(file->name(), ".proto", "_pb");
}
diff --git a/contrib/libs/grpc/src/compiler/ruby_generator_map-inl.h b/contrib/libs/grpc/src/compiler/ruby_generator_map-inl.h
index 4c75780b1a3..fb7e334567c 100644
--- a/contrib/libs/grpc/src/compiler/ruby_generator_map-inl.h
+++ b/contrib/libs/grpc/src/compiler/ruby_generator_map-inl.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/compiler/ruby_generator_string-inl.h b/contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h
index 956539f392a..4f7cf54da98 100644
--- a/contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h
+++ b/contrib/libs/grpc/src/compiler/ruby_generator_string-inl.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -81,23 +81,23 @@ inline bool ReplacePrefix(TString* s, const TString& from,
return true;
}
-// Modularize converts a string into a ruby module compatible name
+// Modularize converts a string into a ruby module compatible name
inline TString Modularize(TString s) {
if (s.empty()) {
return s;
}
TString new_string = "";
- bool was_last_underscore = false;
- new_string.append(1, ::toupper(s[0]));
+ bool was_last_underscore = false;
+ new_string.append(1, ::toupper(s[0]));
for (TString::size_type i = 1; i < s.size(); ++i) {
- if (was_last_underscore && s[i] != '_') {
- new_string.append(1, ::toupper(s[i]));
- } else if (s[i] != '_') {
- new_string.append(1, s[i]);
- }
- was_last_underscore = s[i] == '_';
- }
- return new_string;
+ if (was_last_underscore && s[i] != '_') {
+ new_string.append(1, ::toupper(s[i]));
+ } else if (s[i] != '_') {
+ new_string.append(1, s[i]);
+ }
+ was_last_underscore = s[i] == '_';
+ }
+ return new_string;
}
// RubyPackage gets the ruby package in either proto or ruby_package format
@@ -135,7 +135,7 @@ inline TString RubyTypeOf(const grpc::protobuf::Descriptor* descriptor) {
res += "::"; // switch '.' to the ruby module delim
}
if (i < prefixes_and_type.size() - 1) {
- res += Modularize(prefixes_and_type[i]); // capitalize pkgs
+ res += Modularize(prefixes_and_type[i]); // capitalize pkgs
} else {
res += prefixes_and_type[i];
}
diff --git a/contrib/libs/grpc/src/compiler/schema_interface.h b/contrib/libs/grpc/src/compiler/schema_interface.h
index 60b9d337e8d..edadeff5d98 100644
--- a/contrib/libs/grpc/src/compiler/schema_interface.h
+++ b/contrib/libs/grpc/src/compiler/schema_interface.h
@@ -1,118 +1,118 @@
-/*
- *
- * 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_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
-#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
-
-#include "src/compiler/config.h"
-
-#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.
+ *
+ */
+
+#ifndef GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
+#define GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
+
+#include "src/compiler/config.h"
+
+#include <memory>
#include <util/generic/string.h>
-#include <vector>
-
+#include <vector>
+
#ifdef GRPC_CUSTOM_STRING
#warning GRPC_CUSTOM_STRING is no longer supported. Please use TString.
-#endif
-
-namespace grpc {
-
+#endif
+
+namespace grpc {
+
// Using grpc::string and grpc::to_string is discouraged in favor of
// TString and ToString. This is only for legacy code using
// them explictly.
typedef TString string; // deprecated
-
-} // namespace grpc
-
-namespace grpc_generator {
-
-// A common interface for objects having comments in the source.
-// Return formatted comments to be inserted in generated code.
-struct CommentHolder {
- virtual ~CommentHolder() {}
+
+} // namespace grpc
+
+namespace grpc_generator {
+
+// A common interface for objects having comments in the source.
+// Return formatted comments to be inserted in generated code.
+struct CommentHolder {
+ virtual ~CommentHolder() {}
virtual TString GetLeadingComments(const TString prefix) const = 0;
virtual TString GetTrailingComments(const TString prefix) const = 0;
virtual std::vector<TString> GetAllComments() const = 0;
-};
-
-// An abstract interface representing a method.
-struct Method : public CommentHolder {
- virtual ~Method() {}
-
+};
+
+// An abstract interface representing a method.
+struct Method : public CommentHolder {
+ virtual ~Method() {}
+
virtual TString name() const = 0;
-
+
virtual TString input_type_name() const = 0;
virtual TString output_type_name() const = 0;
-
- virtual bool get_module_and_message_path_input(
+
+ virtual 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 = 0;
- virtual bool get_module_and_message_path_output(
+ virtual 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 = 0;
-
+
virtual TString get_input_type_name() const = 0;
virtual TString get_output_type_name() const = 0;
- virtual bool NoStreaming() const = 0;
- virtual bool ClientStreaming() const = 0;
- virtual bool ServerStreaming() const = 0;
- virtual bool BidiStreaming() const = 0;
-};
-
-// An abstract interface representing a service.
-struct Service : public CommentHolder {
- virtual ~Service() {}
-
+ virtual bool NoStreaming() const = 0;
+ virtual bool ClientStreaming() const = 0;
+ virtual bool ServerStreaming() const = 0;
+ virtual bool BidiStreaming() const = 0;
+};
+
+// An abstract interface representing a service.
+struct Service : public CommentHolder {
+ virtual ~Service() {}
+
virtual TString name() const = 0;
-
- virtual int method_count() const = 0;
- virtual std::unique_ptr<const Method> method(int i) const = 0;
-};
-
-struct Printer {
- virtual ~Printer() {}
-
+
+ virtual int method_count() const = 0;
+ virtual std::unique_ptr<const Method> method(int i) const = 0;
+};
+
+struct Printer {
+ virtual ~Printer() {}
+
virtual void Print(const std::map<TString, TString>& vars,
- const char* template_string) = 0;
- virtual void Print(const char* string) = 0;
- virtual void PrintRaw(const char* string) = 0;
- virtual void Indent() = 0;
- virtual void Outdent() = 0;
-};
-
-// An interface that allows the source generated to be output using various
-// libraries/idls/serializers.
-struct File : public CommentHolder {
- virtual ~File() {}
-
+ const char* template_string) = 0;
+ virtual void Print(const char* string) = 0;
+ virtual void PrintRaw(const char* string) = 0;
+ virtual void Indent() = 0;
+ virtual void Outdent() = 0;
+};
+
+// An interface that allows the source generated to be output using various
+// libraries/idls/serializers.
+struct File : public CommentHolder {
+ virtual ~File() {}
+
virtual TString filename() const = 0;
virtual TString filename_without_ext() const = 0;
virtual TString package() const = 0;
virtual std::vector<TString> package_parts() const = 0;
virtual TString additional_headers() const = 0;
virtual std::vector<TString> GetImportNames() const { return {}; }
-
- virtual int service_count() const = 0;
- virtual std::unique_ptr<const Service> service(int i) const = 0;
-
+
+ virtual int service_count() const = 0;
+ virtual std::unique_ptr<const Service> service(int i) const = 0;
+
virtual std::unique_ptr<Printer> CreatePrinter(TString* str) const = 0;
-};
-} // namespace grpc_generator
-
-#endif // GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
+};
+} // namespace grpc_generator
+
+#endif // GRPC_INTERNAL_COMPILER_SCHEMA_INTERFACE_H
diff --git a/contrib/libs/grpc/src/core/README.md b/contrib/libs/grpc/src/core/README.md
index 5dea45a6925..16500a77031 100644
--- a/contrib/libs/grpc/src/core/README.md
+++ b/contrib/libs/grpc/src/core/README.md
@@ -1,4 +1,4 @@
-# Overview
+# 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,
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 ffb09fd34e7..97d291bff5a 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
@@ -1,49 +1,49 @@
-Client Configuration Support for GRPC
-=====================================
-
-This library provides high level configuration machinery to construct client
-channels and load balance between them.
-
+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
-to resolve a name into a set of arguments for the channel. Such arguments
-might include:
-
-- a list of (ip, port) addresses to connect to
-- 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)
-
+to resolve a name into a set of arguments for the channel. Such arguments
+might include:
+
+- a list of (ip, port) addresses to connect to
+- 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 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).
-
-
-Load Balancing
---------------
-
+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).
+
+
+Load Balancing
+--------------
+
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
+
+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.
-
-
-Sub-Channels
-------------
-
-A sub-channel provides a connection to a server for a client channel. It has a
-connectivity state like a regular channel, and so can be connected or
-disconnected. This connectivity state can be used to inform load balancing
-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
+
+
+Sub-Channels
+------------
+
+A sub-channel provides a connection to a server for a client channel. It has a
+connectivity state like a regular channel, and so can be connected or
+disconnected. This connectivity state can be used to inform load balancing
+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.
-
-
-Naming for GRPC
-===============
-
+
+
+Naming for GRPC
+===============
+
See [/doc/naming.md](gRPC name resolution).
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 1b7708953ab..758568bb981 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
@@ -1,63 +1,63 @@
-/*
- *
- * 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/ext/filters/client_channel/backup_poller.h"
-
-#include <grpc/grpc.h>
-#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"
+/*
+ *
+ * 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/ext/filters/client_channel/backup_poller.h"
+
+#include <grpc/grpc.h>
+#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/iomgr/error.h"
+#include "src/core/lib/iomgr/error.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"
-#include "src/core/lib/surface/completion_queue.h"
-
-#define DEFAULT_POLL_INTERVAL_MS 5000
-
-namespace {
-struct backup_poller {
- grpc_timer polling_timer;
- grpc_closure run_poller_closure;
- grpc_closure shutdown_closure;
- gpr_mu* pollset_mu;
- grpc_pollset* pollset; // guarded by pollset_mu
- bool shutting_down; // guarded by pollset_mu
- gpr_refcount refs;
- gpr_refcount shutdown_refs;
-};
-} // namespace
-
-static gpr_once g_once = GPR_ONCE_INIT;
-static gpr_mu g_poller_mu;
-static backup_poller* g_poller = nullptr; // guarded by g_poller_mu
-// g_poll_interval_ms is set only once at the first time
-// grpc_client_channel_start_backup_polling() is called, after that it is
-// treated as const.
-static int g_poll_interval_ms = DEFAULT_POLL_INTERVAL_MS;
-
+#include "src/core/lib/iomgr/pollset.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/surface/completion_queue.h"
+
+#define DEFAULT_POLL_INTERVAL_MS 5000
+
+namespace {
+struct backup_poller {
+ grpc_timer polling_timer;
+ grpc_closure run_poller_closure;
+ grpc_closure shutdown_closure;
+ gpr_mu* pollset_mu;
+ grpc_pollset* pollset; // guarded by pollset_mu
+ bool shutting_down; // guarded by pollset_mu
+ gpr_refcount refs;
+ gpr_refcount shutdown_refs;
+};
+} // namespace
+
+static gpr_once g_once = GPR_ONCE_INIT;
+static gpr_mu g_poller_mu;
+static backup_poller* g_poller = nullptr; // guarded by g_poller_mu
+// g_poll_interval_ms is set only once at the first time
+// grpc_client_channel_start_backup_polling() is called, after that it is
+// 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. "
@@ -78,105 +78,105 @@ void grpc_client_channel_global_init_backup_polling() {
poll_interval_ms, g_poll_interval_ms);
} else {
g_poll_interval_ms = poll_interval_ms;
- }
-}
-
-static void backup_poller_shutdown_unref(backup_poller* p) {
- if (gpr_unref(&p->shutdown_refs)) {
- grpc_pollset_destroy(p->pollset);
- gpr_free(p->pollset);
- gpr_free(p);
- }
-}
-
+ }
+}
+
+static void backup_poller_shutdown_unref(backup_poller* p) {
+ if (gpr_unref(&p->shutdown_refs)) {
+ grpc_pollset_destroy(p->pollset);
+ gpr_free(p->pollset);
+ gpr_free(p);
+ }
+}
+
static void done_poller(void* arg, grpc_error* /*error*/) {
- backup_poller_shutdown_unref(static_cast<backup_poller*>(arg));
-}
-
-static void g_poller_unref() {
- gpr_mu_lock(&g_poller_mu);
- if (gpr_unref(&g_poller->refs)) {
- backup_poller* p = g_poller;
- g_poller = nullptr;
- gpr_mu_unlock(&g_poller_mu);
- gpr_mu_lock(p->pollset_mu);
- p->shutting_down = true;
- grpc_pollset_shutdown(
- p->pollset, GRPC_CLOSURE_INIT(&p->shutdown_closure, done_poller, p,
- grpc_schedule_on_exec_ctx));
- gpr_mu_unlock(p->pollset_mu);
- grpc_timer_cancel(&p->polling_timer);
- backup_poller_shutdown_unref(p);
- } else {
- gpr_mu_unlock(&g_poller_mu);
- }
-}
-
-static void run_poller(void* arg, grpc_error* error) {
- backup_poller* p = static_cast<backup_poller*>(arg);
- if (error != GRPC_ERROR_NONE) {
- if (error != GRPC_ERROR_CANCELLED) {
- GRPC_LOG_IF_ERROR("run_poller", GRPC_ERROR_REF(error));
- }
- backup_poller_shutdown_unref(p);
- return;
- }
- gpr_mu_lock(p->pollset_mu);
- if (p->shutting_down) {
- gpr_mu_unlock(p->pollset_mu);
+ backup_poller_shutdown_unref(static_cast<backup_poller*>(arg));
+}
+
+static void g_poller_unref() {
+ gpr_mu_lock(&g_poller_mu);
+ if (gpr_unref(&g_poller->refs)) {
+ backup_poller* p = g_poller;
+ g_poller = nullptr;
+ gpr_mu_unlock(&g_poller_mu);
+ gpr_mu_lock(p->pollset_mu);
+ p->shutting_down = true;
+ grpc_pollset_shutdown(
+ p->pollset, GRPC_CLOSURE_INIT(&p->shutdown_closure, done_poller, p,
+ grpc_schedule_on_exec_ctx));
+ gpr_mu_unlock(p->pollset_mu);
+ grpc_timer_cancel(&p->polling_timer);
backup_poller_shutdown_unref(p);
- return;
- }
- grpc_error* err =
- grpc_pollset_work(p->pollset, nullptr, grpc_core::ExecCtx::Get()->Now());
- gpr_mu_unlock(p->pollset_mu);
- GRPC_LOG_IF_ERROR("Run client channel backup poller", err);
- grpc_timer_init(&p->polling_timer,
- grpc_core::ExecCtx::Get()->Now() + g_poll_interval_ms,
- &p->run_poller_closure);
-}
-
-static void g_poller_init_locked() {
- if (g_poller == nullptr) {
- g_poller = static_cast<backup_poller*>(gpr_zalloc(sizeof(backup_poller)));
- g_poller->pollset =
- static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
- g_poller->shutting_down = false;
- grpc_pollset_init(g_poller->pollset, &g_poller->pollset_mu);
- gpr_ref_init(&g_poller->refs, 0);
+ } else {
+ gpr_mu_unlock(&g_poller_mu);
+ }
+}
+
+static void run_poller(void* arg, grpc_error* error) {
+ backup_poller* p = static_cast<backup_poller*>(arg);
+ if (error != GRPC_ERROR_NONE) {
+ if (error != GRPC_ERROR_CANCELLED) {
+ GRPC_LOG_IF_ERROR("run_poller", GRPC_ERROR_REF(error));
+ }
+ backup_poller_shutdown_unref(p);
+ return;
+ }
+ gpr_mu_lock(p->pollset_mu);
+ if (p->shutting_down) {
+ gpr_mu_unlock(p->pollset_mu);
+ backup_poller_shutdown_unref(p);
+ return;
+ }
+ grpc_error* err =
+ grpc_pollset_work(p->pollset, nullptr, grpc_core::ExecCtx::Get()->Now());
+ gpr_mu_unlock(p->pollset_mu);
+ GRPC_LOG_IF_ERROR("Run client channel backup poller", err);
+ grpc_timer_init(&p->polling_timer,
+ grpc_core::ExecCtx::Get()->Now() + g_poll_interval_ms,
+ &p->run_poller_closure);
+}
+
+static void g_poller_init_locked() {
+ if (g_poller == nullptr) {
+ g_poller = static_cast<backup_poller*>(gpr_zalloc(sizeof(backup_poller)));
+ g_poller->pollset =
+ static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
+ g_poller->shutting_down = false;
+ grpc_pollset_init(g_poller->pollset, &g_poller->pollset_mu);
+ gpr_ref_init(&g_poller->refs, 0);
// one for timer cancellation, one for pollset shutdown, one for g_poller
gpr_ref_init(&g_poller->shutdown_refs, 3);
- GRPC_CLOSURE_INIT(&g_poller->run_poller_closure, run_poller, g_poller,
- grpc_schedule_on_exec_ctx);
- grpc_timer_init(&g_poller->polling_timer,
- grpc_core::ExecCtx::Get()->Now() + g_poll_interval_ms,
- &g_poller->run_poller_closure);
- }
-}
-
-void grpc_client_channel_start_backup_polling(
- grpc_pollset_set* interested_parties) {
+ GRPC_CLOSURE_INIT(&g_poller->run_poller_closure, run_poller, g_poller,
+ grpc_schedule_on_exec_ctx);
+ grpc_timer_init(&g_poller->polling_timer,
+ grpc_core::ExecCtx::Get()->Now() + g_poll_interval_ms,
+ &g_poller->run_poller_closure);
+ }
+}
+
+void grpc_client_channel_start_backup_polling(
+ grpc_pollset_set* interested_parties) {
if (g_poll_interval_ms == 0 || grpc_iomgr_run_in_background()) {
- return;
- }
- gpr_mu_lock(&g_poller_mu);
- g_poller_init_locked();
- gpr_ref(&g_poller->refs);
- /* Get a reference to g_poller->pollset before releasing g_poller_mu to make
- * TSAN happy. Otherwise, reading from g_poller (i.e g_poller->pollset) after
- * releasing the lock and setting g_poller to NULL in g_poller_unref() is
- * being flagged as a data-race by TSAN */
- grpc_pollset* pollset = g_poller->pollset;
- gpr_mu_unlock(&g_poller_mu);
-
- grpc_pollset_set_add_pollset(interested_parties, pollset);
-}
-
-void grpc_client_channel_stop_backup_polling(
- grpc_pollset_set* interested_parties) {
+ return;
+ }
+ gpr_mu_lock(&g_poller_mu);
+ g_poller_init_locked();
+ gpr_ref(&g_poller->refs);
+ /* Get a reference to g_poller->pollset before releasing g_poller_mu to make
+ * TSAN happy. Otherwise, reading from g_poller (i.e g_poller->pollset) after
+ * releasing the lock and setting g_poller to NULL in g_poller_unref() is
+ * being flagged as a data-race by TSAN */
+ grpc_pollset* pollset = g_poller->pollset;
+ gpr_mu_unlock(&g_poller_mu);
+
+ grpc_pollset_set_add_pollset(interested_parties, pollset);
+}
+
+void grpc_client_channel_stop_backup_polling(
+ grpc_pollset_set* interested_parties) {
if (g_poll_interval_ms == 0 || grpc_iomgr_run_in_background()) {
- return;
- }
- grpc_pollset_set_del_pollset(interested_parties, g_poller->pollset);
- g_poller_unref();
-}
+ return;
+ }
+ grpc_pollset_set_del_pollset(interested_parties, g_poller->pollset);
+ g_poller_unref();
+}
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 b412081b960..1e96ed9a584 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
@@ -1,41 +1,41 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_BACKUP_POLLER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKUP_POLLER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-#include "src/core/lib/channel/channel_stack.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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKUP_POLLER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKUP_POLLER_H
+
+#include <grpc/support/port_platform.h>
+
+#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. */
-void grpc_client_channel_start_backup_polling(
- grpc_pollset_set* interested_parties);
-
+void grpc_client_channel_start_backup_polling(
+ grpc_pollset_set* interested_parties);
+
/* Stops polling \a interested_parties. */
-void grpc_client_channel_stop_backup_polling(
- grpc_pollset_set* interested_parties);
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKUP_POLLER_H */
+void grpc_client_channel_stop_backup_polling(
+ grpc_pollset_set* interested_parties);
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_BACKUP_POLLER_H */
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 4ebb976efe5..d7c60911ca0 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
@@ -1,264 +1,264 @@
-/*
- *
- * 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/surface/channel.h"
-
-#include <inttypes.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/completion_queue.h"
-
-grpc_connectivity_state grpc_channel_check_connectivity_state(
- grpc_channel* channel, int try_to_connect) {
- /* forward through to the underlying client channel */
- grpc_channel_element* client_channel_elem =
- grpc_channel_stack_last_element(grpc_channel_get_channel_stack(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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/surface/channel.h"
+
+#include <inttypes.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/completion_queue.h"
+
+grpc_connectivity_state grpc_channel_check_connectivity_state(
+ grpc_channel* channel, int try_to_connect) {
+ /* forward through to the underlying client channel */
+ grpc_channel_element* client_channel_elem =
+ grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_connectivity_state state;
- GRPC_API_TRACE(
- "grpc_channel_check_connectivity_state(channel=%p, try_to_connect=%d)", 2,
- (channel, try_to_connect));
+ grpc_core::ExecCtx exec_ctx;
+ grpc_connectivity_state state;
+ GRPC_API_TRACE(
+ "grpc_channel_check_connectivity_state(channel=%p, try_to_connect=%d)", 2,
+ (channel, try_to_connect));
if (GPR_LIKELY(client_channel_elem->filter == &grpc_client_channel_filter)) {
- state = grpc_client_channel_check_connectivity_state(client_channel_elem,
- try_to_connect);
-
- return state;
- }
- gpr_log(GPR_ERROR,
- "grpc_channel_check_connectivity_state called on something that is "
- "not a client channel, but '%s'",
- client_channel_elem->filter->name);
-
- return GRPC_CHANNEL_SHUTDOWN;
-}
-
-typedef enum {
- WAITING,
- READY_TO_CALL_BACK,
- CALLING_BACK_AND_FINISHED,
-} callback_phase;
-
-namespace {
-struct state_watcher {
- gpr_mu mu;
- callback_phase phase;
- grpc_closure on_complete;
- grpc_closure on_timeout;
- grpc_closure watcher_timer_init;
- grpc_timer alarm;
- grpc_connectivity_state state;
- grpc_completion_queue* cq;
- grpc_cq_completion completion_storage;
- grpc_channel* channel;
- grpc_error* error;
- void* tag;
-};
-} // namespace
-
-static void delete_state_watcher(state_watcher* w) {
- grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
- grpc_channel_get_channel_stack(w->channel));
- if (client_channel_elem->filter == &grpc_client_channel_filter) {
- GRPC_CHANNEL_INTERNAL_UNREF(w->channel, "watch_channel_connectivity");
- } else {
- abort();
- }
- gpr_mu_destroy(&w->mu);
- gpr_free(w);
-}
-
+ state = grpc_client_channel_check_connectivity_state(client_channel_elem,
+ try_to_connect);
+
+ return state;
+ }
+ gpr_log(GPR_ERROR,
+ "grpc_channel_check_connectivity_state called on something that is "
+ "not a client channel, but '%s'",
+ client_channel_elem->filter->name);
+
+ return GRPC_CHANNEL_SHUTDOWN;
+}
+
+typedef enum {
+ WAITING,
+ READY_TO_CALL_BACK,
+ CALLING_BACK_AND_FINISHED,
+} callback_phase;
+
+namespace {
+struct state_watcher {
+ gpr_mu mu;
+ callback_phase phase;
+ grpc_closure on_complete;
+ grpc_closure on_timeout;
+ grpc_closure watcher_timer_init;
+ grpc_timer alarm;
+ grpc_connectivity_state state;
+ grpc_completion_queue* cq;
+ grpc_cq_completion completion_storage;
+ grpc_channel* channel;
+ grpc_error* error;
+ void* tag;
+};
+} // namespace
+
+static void delete_state_watcher(state_watcher* w) {
+ grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
+ grpc_channel_get_channel_stack(w->channel));
+ if (client_channel_elem->filter == &grpc_client_channel_filter) {
+ GRPC_CHANNEL_INTERNAL_UNREF(w->channel, "watch_channel_connectivity");
+ } else {
+ abort();
+ }
+ gpr_mu_destroy(&w->mu);
+ gpr_free(w);
+}
+
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);
- switch (w->phase) {
- case WAITING:
- case READY_TO_CALL_BACK:
- GPR_UNREACHABLE_CODE(return );
- case CALLING_BACK_AND_FINISHED:
- should_delete = true;
- break;
- }
- gpr_mu_unlock(&w->mu);
-
- if (should_delete) {
- delete_state_watcher(w);
- }
-}
-
-static void partly_done(state_watcher* w, bool due_to_completion,
- grpc_error* error) {
+ bool should_delete = false;
+ state_watcher* w = static_cast<state_watcher*>(pw);
+ gpr_mu_lock(&w->mu);
+ switch (w->phase) {
+ case WAITING:
+ case READY_TO_CALL_BACK:
+ GPR_UNREACHABLE_CODE(return );
+ case CALLING_BACK_AND_FINISHED:
+ should_delete = true;
+ break;
+ }
+ gpr_mu_unlock(&w->mu);
+
+ if (should_delete) {
+ delete_state_watcher(w);
+ }
+}
+
+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;
- if (due_to_completion) {
- grpc_timer_cancel(&w->alarm);
- } else {
- grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
- grpc_channel_get_channel_stack(w->channel));
- grpc_client_channel_watch_connectivity_state(
- client_channel_elem,
- grpc_polling_entity_create_from_pollset(grpc_cq_pollset(w->cq)),
- nullptr, &w->on_complete, nullptr);
- }
-
- gpr_mu_lock(&w->mu);
-
- if (due_to_completion) {
+ if (due_to_completion) {
+ grpc_timer_cancel(&w->alarm);
+ } else {
+ grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
+ grpc_channel_get_channel_stack(w->channel));
+ grpc_client_channel_watch_connectivity_state(
+ client_channel_elem,
+ grpc_polling_entity_create_from_pollset(grpc_cq_pollset(w->cq)),
+ nullptr, &w->on_complete, nullptr);
+ }
+
+ gpr_mu_lock(&w->mu);
+
+ if (due_to_completion) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures)) {
- GRPC_LOG_IF_ERROR("watch_completion_error", GRPC_ERROR_REF(error));
- }
- GRPC_ERROR_UNREF(error);
- error = GRPC_ERROR_NONE;
- } else {
- if (error == GRPC_ERROR_NONE) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Timed out waiting for connection state change");
- } else if (error == GRPC_ERROR_CANCELLED) {
- error = GRPC_ERROR_NONE;
- }
- }
- switch (w->phase) {
- case WAITING:
- GRPC_ERROR_REF(error);
- w->error = error;
- w->phase = READY_TO_CALL_BACK;
- break;
- case READY_TO_CALL_BACK:
- if (error != GRPC_ERROR_NONE) {
- GPR_ASSERT(!due_to_completion);
- GRPC_ERROR_UNREF(w->error);
- GRPC_ERROR_REF(error);
- w->error = error;
- }
- w->phase = CALLING_BACK_AND_FINISHED;
+ GRPC_LOG_IF_ERROR("watch_completion_error", GRPC_ERROR_REF(error));
+ }
+ GRPC_ERROR_UNREF(error);
+ error = GRPC_ERROR_NONE;
+ } else {
+ if (error == GRPC_ERROR_NONE) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Timed out waiting for connection state change");
+ } else if (error == GRPC_ERROR_CANCELLED) {
+ error = GRPC_ERROR_NONE;
+ }
+ }
+ switch (w->phase) {
+ case WAITING:
+ GRPC_ERROR_REF(error);
+ w->error = error;
+ w->phase = READY_TO_CALL_BACK;
+ break;
+ case READY_TO_CALL_BACK:
+ if (error != GRPC_ERROR_NONE) {
+ GPR_ASSERT(!due_to_completion);
+ GRPC_ERROR_UNREF(w->error);
+ GRPC_ERROR_REF(error);
+ 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;
- break;
- case CALLING_BACK_AND_FINISHED:
- GPR_UNREACHABLE_CODE(return );
- break;
- }
- gpr_mu_unlock(&w->mu);
-
+ break;
+ case CALLING_BACK_AND_FINISHED:
+ GPR_UNREACHABLE_CODE(return );
+ break;
+ }
+ 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);
}
- GRPC_ERROR_UNREF(error);
-}
-
-static void watch_complete(void* pw, grpc_error* error) {
- partly_done(static_cast<state_watcher*>(pw), true, GRPC_ERROR_REF(error));
-}
-
-static void timeout_complete(void* pw, grpc_error* error) {
- partly_done(static_cast<state_watcher*>(pw), false, GRPC_ERROR_REF(error));
-}
-
-int grpc_channel_num_external_connectivity_watchers(grpc_channel* channel) {
- grpc_channel_element* client_channel_elem =
- grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
- return grpc_client_channel_num_external_connectivity_watchers(
- client_channel_elem);
-}
-
-typedef struct watcher_timer_init_arg {
- state_watcher* w;
- gpr_timespec deadline;
-} watcher_timer_init_arg;
-
+ GRPC_ERROR_UNREF(error);
+}
+
+static void watch_complete(void* pw, grpc_error* error) {
+ partly_done(static_cast<state_watcher*>(pw), true, GRPC_ERROR_REF(error));
+}
+
+static void timeout_complete(void* pw, grpc_error* error) {
+ partly_done(static_cast<state_watcher*>(pw), false, GRPC_ERROR_REF(error));
+}
+
+int grpc_channel_num_external_connectivity_watchers(grpc_channel* channel) {
+ grpc_channel_element* client_channel_elem =
+ grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
+ return grpc_client_channel_num_external_connectivity_watchers(
+ client_channel_elem);
+}
+
+typedef struct watcher_timer_init_arg {
+ state_watcher* w;
+ gpr_timespec deadline;
+} watcher_timer_init_arg;
+
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),
- &wa->w->on_timeout);
- gpr_free(wa);
-}
-
-int grpc_channel_support_connectivity_watcher(grpc_channel* channel) {
- grpc_channel_element* client_channel_elem =
- grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
- return client_channel_elem->filter != &grpc_client_channel_filter ? 0 : 1;
-}
-
-void grpc_channel_watch_connectivity_state(
- grpc_channel* channel, grpc_connectivity_state last_observed_state,
- gpr_timespec deadline, grpc_completion_queue* cq, void* tag) {
- grpc_channel_element* client_channel_elem =
- grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
+ 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),
+ &wa->w->on_timeout);
+ gpr_free(wa);
+}
+
+int grpc_channel_support_connectivity_watcher(grpc_channel* channel) {
+ grpc_channel_element* client_channel_elem =
+ grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
+ return client_channel_elem->filter != &grpc_client_channel_filter ? 0 : 1;
+}
+
+void grpc_channel_watch_connectivity_state(
+ grpc_channel* channel, grpc_connectivity_state last_observed_state,
+ gpr_timespec deadline, grpc_completion_queue* cq, void* tag) {
+ grpc_channel_element* client_channel_elem =
+ grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel));
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- state_watcher* w = static_cast<state_watcher*>(gpr_malloc(sizeof(*w)));
-
- GRPC_API_TRACE(
- "grpc_channel_watch_connectivity_state("
- "channel=%p, last_observed_state=%d, "
- "deadline=gpr_timespec { tv_sec: %" PRId64
- ", tv_nsec: %d, clock_type: %d }, "
- "cq=%p, tag=%p)",
- 7,
- (channel, (int)last_observed_state, deadline.tv_sec, deadline.tv_nsec,
- (int)deadline.clock_type, cq, tag));
-
- GPR_ASSERT(grpc_cq_begin_op(cq, tag));
-
- gpr_mu_init(&w->mu);
- GRPC_CLOSURE_INIT(&w->on_complete, watch_complete, w,
- grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&w->on_timeout, timeout_complete, w,
- grpc_schedule_on_exec_ctx);
- w->phase = WAITING;
- w->state = last_observed_state;
- w->cq = cq;
- w->tag = tag;
- w->channel = channel;
- w->error = nullptr;
-
- watcher_timer_init_arg* wa = static_cast<watcher_timer_init_arg*>(
- gpr_malloc(sizeof(watcher_timer_init_arg)));
- wa->w = w;
- wa->deadline = deadline;
- GRPC_CLOSURE_INIT(&w->watcher_timer_init, watcher_timer_init, wa,
- grpc_schedule_on_exec_ctx);
-
- if (client_channel_elem->filter == &grpc_client_channel_filter) {
- GRPC_CHANNEL_INTERNAL_REF(channel, "watch_channel_connectivity");
- grpc_client_channel_watch_connectivity_state(
- client_channel_elem,
- grpc_polling_entity_create_from_pollset(grpc_cq_pollset(cq)), &w->state,
- &w->on_complete, &w->watcher_timer_init);
- } else {
- abort();
- }
-}
+ grpc_core::ExecCtx exec_ctx;
+ state_watcher* w = static_cast<state_watcher*>(gpr_malloc(sizeof(*w)));
+
+ GRPC_API_TRACE(
+ "grpc_channel_watch_connectivity_state("
+ "channel=%p, last_observed_state=%d, "
+ "deadline=gpr_timespec { tv_sec: %" PRId64
+ ", tv_nsec: %d, clock_type: %d }, "
+ "cq=%p, tag=%p)",
+ 7,
+ (channel, (int)last_observed_state, deadline.tv_sec, deadline.tv_nsec,
+ (int)deadline.clock_type, cq, tag));
+
+ GPR_ASSERT(grpc_cq_begin_op(cq, tag));
+
+ gpr_mu_init(&w->mu);
+ GRPC_CLOSURE_INIT(&w->on_complete, watch_complete, w,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&w->on_timeout, timeout_complete, w,
+ grpc_schedule_on_exec_ctx);
+ w->phase = WAITING;
+ w->state = last_observed_state;
+ w->cq = cq;
+ w->tag = tag;
+ w->channel = channel;
+ w->error = nullptr;
+
+ watcher_timer_init_arg* wa = static_cast<watcher_timer_init_arg*>(
+ gpr_malloc(sizeof(watcher_timer_init_arg)));
+ wa->w = w;
+ wa->deadline = deadline;
+ GRPC_CLOSURE_INIT(&w->watcher_timer_init, watcher_timer_init, wa,
+ grpc_schedule_on_exec_ctx);
+
+ if (client_channel_elem->filter == &grpc_client_channel_filter) {
+ GRPC_CHANNEL_INTERNAL_REF(channel, "watch_channel_connectivity");
+ grpc_client_channel_watch_connectivity_state(
+ client_channel_elem,
+ grpc_polling_entity_create_from_pollset(grpc_cq_pollset(cq)), &w->state,
+ &w->on_complete, &w->watcher_timer_init);
+ } else {
+ abort();
+ }
+}
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 908a05248cb..d0937da4c4c 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
@@ -1,98 +1,98 @@
-/*
- *
- * 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/client_channel.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/client_channel.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
#include <set>
#include "y_absl/strings/numbers.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/string_view.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/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+
#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/backup_poller.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/http_connect_handshaker.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.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/proxy_mapper_registry.h"
-#include "src/core/ext/filters/client_channel/resolver_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/resolving_lb_policy.h"
-#include "src/core/ext/filters/client_channel/retry_throttle.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_call_data.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/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/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/iomgr.h"
+#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/iomgr/work_serializer.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"
-
+#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"
+
using grpc_core::internal::ClientChannelMethodParsedConfig;
-using grpc_core::internal::ServerRetryThrottleData;
-
+using grpc_core::internal::ServerRetryThrottleData;
+
//
// 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?
-#define DEFAULT_PER_RPC_RETRY_BUFFER_SIZE (256 << 10)
-
-// This value was picked arbitrarily. It can be changed if there is
-// any even moderately compelling reason to do so.
-#define RETRY_BACKOFF_JITTER 0.2
-
+
+// By default, we buffer 256 KiB per RPC for retries.
+// TODO(roth): Do we have any data to suggest a better value?
+#define DEFAULT_PER_RPC_RETRY_BUFFER_SIZE (256 << 10)
+
+// This value was picked arbitrarily. It can be changed if there is
+// 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
@@ -102,25 +102,25 @@ using grpc_core::internal::ServerRetryThrottleData;
// 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);
@@ -128,18 +128,18 @@ class ChannelData {
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_; }
@@ -1977,22 +1977,22 @@ void ChannelData::StartTransportOpLocked(grpc_transport_op* op) {
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) {
state_tracker_.RemoveWatcher(op->stop_connectivity_watch);
}
// Ping.
- if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
+ 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);
- }
+ }
op->bind_pollset = nullptr;
- op->send_ping.on_initiate = nullptr;
- op->send_ping.on_ack = nullptr;
- }
+ op->send_ping.on_initiate = nullptr;
+ op->send_ping.on_ack = nullptr;
+ }
// Reset backoff.
if (op->reset_connect_backoff) {
if (resolving_lb_policy_ != nullptr) {
@@ -2000,7 +2000,7 @@ void ChannelData::StartTransportOpLocked(grpc_transport_op* op) {
}
}
// Disconnect or enter IDLE.
- if (op->disconnect_with_error != GRPC_ERROR_NONE) {
+ if (op->disconnect_with_error != GRPC_ERROR_NONE) {
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));
@@ -2026,38 +2026,38 @@ void ChannelData::StartTransportOpLocked(grpc_transport_op* op) {
y_absl::make_unique<LoadBalancingPolicy::TransientFailurePicker>(
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);
-}
-
+}
+
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);
+ GPR_ASSERT(op->set_accept_stream == false);
// Handle bind_pollset.
- if (op->bind_pollset != nullptr) {
+ if (op->bind_pollset != nullptr) {
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");
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_);
- if (info->lb_policy_name != nullptr) {
+ if (info->lb_policy_name != nullptr) {
*info->lb_policy_name = gpr_strdup(chand->info_lb_policy_name_.get());
- }
- if (info->service_config_json != nullptr) {
- *info->service_config_json =
+ }
+ 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.
@@ -2067,7 +2067,7 @@ void ChannelData::AddQueuedPick(QueuedPick* pick,
// 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.
@@ -2081,7 +2081,7 @@ void ChannelData::RemoveQueuedPick(QueuedPick* to_remove,
}
}
}
-
+
RefCountedPtr<ConnectedSubchannel>
ChannelData::GetConnectedSubchannelInDataPlane(
SubchannelInterface* subchannel) const {
@@ -2098,7 +2098,7 @@ void ChannelData::TryToConnectLocked() {
resolving_lb_policy_->ExitIdleLocked();
} else {
CreateResolvingLoadBalancingPolicyLocked();
- }
+ }
GRPC_CHANNEL_STACK_UNREF(owning_stack_, "TryToConnect");
}
@@ -2108,60 +2108,60 @@ grpc_connectivity_state ChannelData::CheckConnectivityState(
if (out == GRPC_CHANNEL_IDLE && try_to_connect) {
GRPC_CHANNEL_STACK_REF(owning_stack_, "TryToConnect");
work_serializer_->Run([this]() { TryToConnectLocked(); }, DEBUG_LOCATION);
- }
+ }
return out;
-}
-
+}
+
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);
}
-
+
//
// CallData implementation
//
-
-// Retry support:
-//
-// In order to support retries, we act as a proxy for stream op batches.
-// When we get a batch from the surface, we add it to our list of pending
-// batches, and we then use those batches to construct separate "child"
-// batches to be started on the subchannel call. When the child batches
-// return, we then decide which pending batches have been completed and
-// schedule their callbacks accordingly. If a subchannel call fails and
-// we want to retry it, we do a new pick and start again, constructing
-// new "child" batches for the new subchannel call.
-//
-// Note that retries are committed when receiving data from the server
-// (except for Trailers-Only responses). However, there may be many
-// send ops started before receiving any data, so we may have already
-// completed some number of send ops (and returned the completions up to
-// the surface) by the time we realize that we need to retry. To deal
-// with this, we cache data for send ops, so that we can replay them on a
-// different subchannel call even after we have completed the original
-// batches.
-//
-// There are two sets of data to maintain:
-// - In call_data (in the parent channel), we maintain a list of pending
-// ops and cached data for send ops.
-// - In the subchannel call, we maintain state to indicate what ops have
-// already been sent down to that call.
-//
-// When constructing the "child" batches, we compare those two sets of
-// data to see which batches need to be sent to the subchannel call.
-
-// TODO(roth): In subsequent PRs:
-// - add support for transparent retries (including initial metadata)
-// - figure out how to record stats in census for retries
-// (census filter is on top of this one)
-// - add census stats for retries
-
+
+// Retry support:
+//
+// In order to support retries, we act as a proxy for stream op batches.
+// When we get a batch from the surface, we add it to our list of pending
+// batches, and we then use those batches to construct separate "child"
+// batches to be started on the subchannel call. When the child batches
+// return, we then decide which pending batches have been completed and
+// schedule their callbacks accordingly. If a subchannel call fails and
+// we want to retry it, we do a new pick and start again, constructing
+// new "child" batches for the new subchannel call.
+//
+// Note that retries are committed when receiving data from the server
+// (except for Trailers-Only responses). However, there may be many
+// send ops started before receiving any data, so we may have already
+// completed some number of send ops (and returned the completions up to
+// the surface) by the time we realize that we need to retry. To deal
+// with this, we cache data for send ops, so that we can replay them on a
+// different subchannel call even after we have completed the original
+// batches.
+//
+// There are two sets of data to maintain:
+// - In call_data (in the parent channel), we maintain a list of pending
+// ops and cached data for send ops.
+// - In the subchannel call, we maintain state to indicate what ops have
+// already been sent down to that call.
+//
+// When constructing the "child" batches, we compare those two sets of
+// data to see which batches need to be sent to the subchannel call.
+
+// TODO(roth): In subsequent PRs:
+// - add support for transparent retries (including initial metadata)
+// - figure out how to record stats in census for retries
+// (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,
@@ -2309,105 +2309,105 @@ void CallData::SetPollent(grpc_call_element* elem,
CallData* calld = static_cast<CallData*>(elem->call_data);
calld->pollent_ = pollent;
}
-
-//
-// send op data caching
-//
-
+
+//
+// send op data caching
+//
+
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) {
+ 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);
- grpc_metadata_batch* send_initial_metadata =
- batch->payload->send_initial_metadata.send_initial_metadata;
+ grpc_metadata_batch* send_initial_metadata =
+ batch->payload->send_initial_metadata.send_initial_metadata;
send_initial_metadata_storage_ = (grpc_linked_mdelem*)arena_->Alloc(
- sizeof(grpc_linked_mdelem) * send_initial_metadata->list.count);
+ 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_ =
- batch->payload->send_initial_metadata.send_initial_metadata_flags;
+ batch->payload->send_initial_metadata.send_initial_metadata_flags;
peer_string_ = batch->payload->send_initial_metadata.peer_string;
- }
- // Set up cache for send_message ops.
- if (batch->send_message) {
+ }
+ // Set up cache for send_message ops.
+ if (batch->send_message) {
ByteStreamCache* cache = arena_->New<ByteStreamCache>(
- std::move(batch->payload->send_message.send_message));
+ std::move(batch->payload->send_message.send_message));
send_messages_.push_back(cache);
- }
- // Save metadata batch for send_trailing_metadata ops.
- if (batch->send_trailing_metadata) {
+ }
+ // 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);
- grpc_metadata_batch* send_trailing_metadata =
- batch->payload->send_trailing_metadata.send_trailing_metadata;
+ 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_);
- }
-}
-
+ }
+}
+
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,
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: destroying calld->send_initial_metadata", chand,
this);
- }
+ }
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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: destroying calld->send_messages[%" PRIuPTR "]",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: destroying calld->send_messages[%" PRIuPTR "]",
chand, this, idx);
- }
+ }
send_messages_[idx]->Destroy();
-}
-
+}
+
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",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: destroying calld->send_trailing_metadata",
chand, this);
- }
+ }
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);
- if (retry_state->completed_send_initial_metadata) {
+ if (retry_state->completed_send_initial_metadata) {
FreeCachedSendInitialMetadata(chand);
- }
- for (size_t i = 0; i < retry_state->completed_send_message_count; ++i) {
+ }
+ for (size_t i = 0; i < retry_state->completed_send_message_count; ++i) {
FreeCachedSendMessage(chand, i);
- }
- if (retry_state->completed_send_trailing_metadata) {
+ }
+ if (retry_state->completed_send_trailing_metadata) {
FreeCachedSendTrailingMetadata(chand);
- }
-}
-
+ }
+}
+
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) {
+ if (batch_data->batch.send_initial_metadata) {
FreeCachedSendInitialMetadata(chand);
- }
- if (batch_data->batch.send_message) {
+ }
+ if (batch_data->batch.send_message) {
FreeCachedSendMessage(chand, retry_state->completed_send_message_count - 1);
- }
- if (batch_data->batch.send_trailing_metadata) {
+ }
+ if (batch_data->batch.send_trailing_metadata) {
FreeCachedSendTrailingMetadata(chand);
- }
-}
-
-//
+ }
+}
+
+//
// LB recv_trailing_metadata_ready handling
//
@@ -2461,94 +2461,94 @@ void CallData::MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(
}
//
-// pending_batches management
-//
-
+// pending_batches management
+//
+
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;
- if (batch->send_message) return 1;
- if (batch->send_trailing_metadata) return 2;
- if (batch->recv_initial_metadata) return 3;
- if (batch->recv_message) return 4;
- if (batch->recv_trailing_metadata) return 5;
- GPR_UNREACHABLE_CODE(return (size_t)-1);
-}
-
-// This is called via the call combiner, so access to calld is synchronized.
+ // 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;
+ if (batch->send_message) return 1;
+ if (batch->send_trailing_metadata) return 2;
+ if (batch->recv_initial_metadata) return 3;
+ if (batch->recv_message) return 4;
+ if (batch->recv_trailing_metadata) return 5;
+ GPR_UNREACHABLE_CODE(return (size_t)-1);
+}
+
+// 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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: adding pending batch at index %" PRIuPTR, chand,
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: adding pending batch at index %" PRIuPTR, chand,
this, idx);
- }
+ }
PendingBatch* pending = &pending_batches_[idx];
- GPR_ASSERT(pending->batch == nullptr);
- pending->batch = batch;
- pending->send_ops_cached = false;
+ GPR_ASSERT(pending->batch == nullptr);
+ pending->batch = batch;
+ pending->send_ops_cached = false;
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) {
+ // 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(
- batch->payload->send_initial_metadata.send_initial_metadata);
- }
- if (batch->send_message) {
+ batch->payload->send_initial_metadata.send_initial_metadata);
+ }
+ if (batch->send_message) {
pending_send_message_ = true;
bytes_buffered_for_retry_ +=
- batch->payload->send_message.send_message->length();
- }
- if (batch->send_trailing_metadata) {
+ batch->payload->send_message.send_message->length();
+ }
+ if (batch->send_trailing_metadata) {
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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: exceeded retry buffer size, committing",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: exceeded retry buffer size, committing",
chand, this);
- }
+ }
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 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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: disabling retries before first attempt",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: disabling retries before first attempt",
chand, this);
- }
+ }
enable_retries_ = false;
- }
- }
- }
-}
-
+ }
+ }
+ }
+}
+
void CallData::PendingBatchClear(PendingBatch* pending) {
if (enable_retries_) {
- if (pending->batch->send_initial_metadata) {
+ if (pending->batch->send_initial_metadata) {
pending_send_initial_metadata_ = false;
- }
- if (pending->batch->send_message) {
+ }
+ if (pending->batch->send_message) {
pending_send_message_ = false;
- }
- if (pending->batch->send_trailing_metadata) {
+ }
+ if (pending->batch->send_trailing_metadata) {
pending_send_trailing_metadata_ = false;
- }
- }
- pending->batch = nullptr;
-}
-
+ }
+ }
+ pending->batch = nullptr;
+}
+
void CallData::MaybeClearPendingBatch(grpc_call_element* elem,
PendingBatch* pending) {
ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
@@ -2572,35 +2572,35 @@ void CallData::MaybeClearPendingBatch(grpc_call_element* elem,
}
}
-// This is called via the call combiner, so access to calld is synchronized.
+// This is called via the call combiner, so access to calld is synchronized.
void CallData::FailPendingBatchInCallCombiner(void* arg, grpc_error* error) {
- grpc_transport_stream_op_batch* batch =
- static_cast<grpc_transport_stream_op_batch*>(arg);
+ grpc_transport_stream_op_batch* batch =
+ static_cast<grpc_transport_stream_op_batch*>(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(
+ // Note: This will release the call combiner.
+ grpc_transport_stream_op_batch_finish_with_failure(
batch, GRPC_ERROR_REF(error), calld->call_combiner_);
-}
-
-// This is called via the call combiner, so access to calld is synchronized.
+}
+
+// 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) {
- GPR_ASSERT(error != GRPC_ERROR_NONE);
+ GPR_ASSERT(error != GRPC_ERROR_NONE);
if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- size_t num_batches = 0;
+ 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;
- }
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: failing %" PRIuPTR " pending batches: %s",
+ }
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: failing %" PRIuPTR " pending batches: %s",
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];
- grpc_transport_stream_op_batch* batch = pending->batch;
- if (batch != nullptr) {
+ grpc_transport_stream_op_batch* batch = pending->batch;
+ if (batch != nullptr) {
if (batch->recv_trailing_metadata) {
MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch);
}
@@ -2611,50 +2611,50 @@ void CallData::PendingBatchesFail(
closures.Add(&batch->handler_private.closure, GRPC_ERROR_REF(error),
"PendingBatchesFail");
PendingBatchClear(pending);
- }
- }
+ }
+ }
if (yield_call_combiner_predicate(closures)) {
closures.RunClosures(call_combiner_);
} else {
closures.RunClosuresWithoutYielding(call_combiner_);
- }
- GRPC_ERROR_UNREF(error);
-}
-
-// This is called via the call combiner, so access to calld is synchronized.
+ }
+ 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*/) {
- grpc_transport_stream_op_batch* batch =
- static_cast<grpc_transport_stream_op_batch*>(arg);
+ 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);
- // Note: This will release the call combiner.
+ // Note: This will release the call combiner.
subchannel_call->StartTransportStreamOpBatch(batch);
-}
-
-// This is called via the call combiner, so access to calld is synchronized.
+}
+
+// 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);
- return;
- }
- // Retries not enabled; send down batches as-is.
+ return;
+ }
+ // Retries not enabled; send down batches as-is.
if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- size_t num_batches = 0;
+ 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;
- }
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: starting %" PRIuPTR
- " pending batches on subchannel_call=%p",
+ }
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: starting %" PRIuPTR
+ " pending batches on subchannel_call=%p",
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];
- grpc_transport_stream_op_batch* batch = pending->batch;
- if (batch != nullptr) {
+ grpc_transport_stream_op_batch* batch = pending->batch;
+ if (batch != nullptr) {
if (batch->recv_trailing_metadata) {
MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch);
}
@@ -2665,12 +2665,12 @@ void CallData::PendingBatchesResume(grpc_call_element* elem) {
closures.Add(&batch->handler_private.closure, GRPC_ERROR_NONE,
"PendingBatchesResume");
PendingBatchClear(pending);
- }
- }
- // Note: This will release the call combiner.
+ }
+ }
+ // Note: This will release the call combiner.
closures.RunClosures(call_combiner_);
-}
-
+}
+
template <typename Predicate>
CallData::PendingBatch* CallData::PendingBatchFind(grpc_call_element* elem,
const char* log_message,
@@ -2687,14 +2687,14 @@ CallData::PendingBatch* CallData::PendingBatchFind(grpc_call_element* elem,
}
return pending;
}
- }
+ }
return nullptr;
-}
-
-//
-// retry code
-//
-
+}
+
+//
+// retry code
+//
+
void CallData::RetryCommit(grpc_call_element* elem,
SubchannelCallRetryState* retry_state) {
ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
@@ -2702,162 +2702,162 @@ void CallData::RetryCommit(grpc_call_element* elem,
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) {
+ }
+ if (retry_state != nullptr) {
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();
- GPR_ASSERT(retry_policy != nullptr);
+ GPR_ASSERT(retry_policy != nullptr);
// Reset subchannel call.
subchannel_call_.reset();
- // Compute backoff delay.
- grpc_millis next_attempt_time;
- if (server_pushback_ms >= 0) {
+ // 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;
- } else {
+ } else {
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));
+ .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;
- }
+ }
next_attempt_time = retry_backoff_->NextAttemptTime();
- }
+ }
if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"chand=%p calld=%p: retrying failed call in %" PRId64 " ms", chand,
this, next_attempt_time - ExecCtx::Get()->Now());
- }
- // Schedule retry after computed delay.
+ }
+ // 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_);
- // Update bookkeeping.
- if (retry_state != nullptr) retry_state->retry_dispatched = true;
-}
-
+ // 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);
- // Get retry policy.
+ // Get 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).
+ 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;
- if (batch_data != nullptr) {
+ if (batch_data != nullptr) {
retry_state = static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
- if (retry_state->retry_dispatched) {
+ if (retry_state->retry_dispatched) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: retry already dispatched", chand,
+ gpr_log(GPR_INFO, "chand=%p calld=%p: retry already dispatched", chand,
this);
- }
- return true;
- }
- }
- // Check status.
+ }
+ return true;
+ }
+ }
+ // Check status.
if (GPR_LIKELY(status == GRPC_STATUS_OK)) {
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);
- }
- return false;
- }
- // Status is not OK. Check whether the status is retryable.
- if (!retry_policy->retryable_status_codes.Contains(status)) {
+ }
+ 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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: status %s not configured as retryable", chand,
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: status %s not configured as retryable", chand,
this, grpc_status_code_to_string(status));
- }
- return false;
- }
- // Record the failure and check whether retries are throttled.
- // Note that it's important for this check to come after the status
- // code check above, since we should only record failures whose statuses
- // match the configured retryable status codes, so that we don't count
- // 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.
+ }
+ return false;
+ }
+ // Record the failure and check whether retries are throttled.
+ // Note that it's important for this check to come after the status
+ // code check above, since we should only record failures whose statuses
+ // match the configured retryable status codes, so that we don't count
+ // 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);
- }
- return false;
- }
- // Check whether the call is committed.
+ }
+ return false;
+ }
+ // Check whether the call is committed.
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,
+ gpr_log(GPR_INFO, "chand=%p calld=%p: retries already committed", chand,
this);
- }
- return false;
- }
- // Check whether we have retries remaining.
+ }
+ 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)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: exceeded %d retry attempts", chand,
+ gpr_log(GPR_INFO, "chand=%p calld=%p: exceeded %d retry attempts", chand,
this, retry_policy->max_attempts);
- }
- return false;
- }
- // If the call was cancelled from the surface, don't retry.
+ }
+ 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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: call cancelled from surface, not retrying",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: call cancelled from surface, not retrying",
chand, this);
- }
- return false;
- }
- // Check server push-back.
- grpc_millis server_pushback_ms = -1;
- if (server_pushback_md != nullptr) {
- // 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)) {
+ }
+ return false;
+ }
+ // Check server push-back.
+ grpc_millis server_pushback_ms = -1;
+ if (server_pushback_md != nullptr) {
+ // 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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: not retrying due to server push-back",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: not retrying due to server push-back",
chand, this);
- }
- return false;
- } else {
+ }
+ return false;
+ } else {
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",
+ gpr_log(GPR_INFO, "chand=%p calld=%p: server push-back: retry in %u ms",
chand, this, ms);
- }
- server_pushback_ms = (grpc_millis)ms;
- }
- }
+ }
+ server_pushback_ms = (grpc_millis)ms;
+ }
+ }
DoRetry(elem, retry_state, server_pushback_ms);
- return true;
-}
-
-//
+ return true;
+}
+
+//
// 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);
@@ -2902,15 +2902,15 @@ void CallData::SubchannelCallBatchData::Destroy() {
GRPC_CALL_STACK_UNREF(calld->owning_call_, "batch_data");
}
-//
-// recv_initial_metadata callback handling
-//
-
+//
+// 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);
- // Find pending batch.
+ // Find pending batch.
PendingBatch* pending = calld->PendingBatchFind(
batch_data->elem, "invoking recv_initial_metadata_ready for",
[](grpc_transport_stream_op_batch* batch) {
@@ -2918,40 +2918,40 @@ void CallData::InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error) {
batch->payload->recv_initial_metadata
.recv_initial_metadata_ready != nullptr;
});
- GPR_ASSERT(pending != nullptr);
- // Return metadata.
+ GPR_ASSERT(pending != nullptr);
+ // Return metadata.
SubchannelCallRetryState* retry_state =
static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
- grpc_metadata_batch_move(
+ grpc_metadata_batch_move(
&retry_state->recv_initial_metadata,
- pending->batch->payload->recv_initial_metadata.recv_initial_metadata);
- // Update bookkeeping.
- // Note: Need to do this before invoking the callback, since invoking
- // the callback will result in yielding the call combiner.
- grpc_closure* recv_initial_metadata_ready =
- pending->batch->payload->recv_initial_metadata
- .recv_initial_metadata_ready;
- pending->batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
- nullptr;
+ pending->batch->payload->recv_initial_metadata.recv_initial_metadata);
+ // Update bookkeeping.
+ // Note: Need to do this before invoking the callback, since invoking
+ // the callback will result in yielding the call combiner.
+ grpc_closure* recv_initial_metadata_ready =
+ pending->batch->payload->recv_initial_metadata
+ .recv_initial_metadata_ready;
+ pending->batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
+ nullptr;
calld->MaybeClearPendingBatch(batch_data->elem, pending);
batch_data->Unref();
- // Invoke callback.
+ // Invoke callback.
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);
- grpc_call_element* elem = batch_data->elem;
+ 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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: got recv_initial_metadata_ready, error=%s",
- chand, calld, grpc_error_string(error));
- }
+ 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*>(
batch_data->subchannel_call->GetParentData());
@@ -2964,7 +2964,7 @@ void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) {
"recv_initial_metadata_ready after retry dispatched");
return;
}
- // If we got an error or a Trailers-Only response and have not yet gotten
+ // If we got an error or a Trailers-Only response and have not yet gotten
// the recv_trailing_metadata_ready callback, then defer propagating this
// callback back to the surface. We can evaluate whether to retry when
// recv_trailing_metadata comes back.
@@ -2972,76 +2972,76 @@ void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) {
error != GRPC_ERROR_NONE) &&
!retry_state->completed_recv_trailing_metadata)) {
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)",
- chand, calld);
- }
- retry_state->recv_initial_metadata_ready_deferred_batch = batch_data;
- retry_state->recv_initial_metadata_error = GRPC_ERROR_REF(error);
- if (!retry_state->started_recv_trailing_metadata) {
- // recv_trailing_metadata not yet started by application; start it
- // ourselves to get status.
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: deferring recv_initial_metadata_ready "
+ "(Trailers-Only)",
+ chand, calld);
+ }
+ retry_state->recv_initial_metadata_ready_deferred_batch = batch_data;
+ retry_state->recv_initial_metadata_error = GRPC_ERROR_REF(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);
- } else {
- GRPC_CALL_COMBINER_STOP(
+ } else {
+ GRPC_CALL_COMBINER_STOP(
calld->call_combiner_,
- "recv_initial_metadata_ready trailers-only or error");
- }
- return;
- }
- // Received valid initial metadata, so commit the call.
+ "recv_initial_metadata_ready trailers-only or error");
+ }
+ return;
+ }
+ // Received valid initial metadata, so commit the call.
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.
+ // Manually invoking a callback function; it does not take ownership of error.
calld->InvokeRecvInitialMetadataCallback(batch_data, error);
-}
-
-//
-// recv_message callback handling
-//
-
+}
+
+//
+// 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);
- // Find pending op.
+ // Find pending op.
PendingBatch* pending = calld->PendingBatchFind(
batch_data->elem, "invoking recv_message_ready for",
[](grpc_transport_stream_op_batch* batch) {
return batch->recv_message &&
batch->payload->recv_message.recv_message_ready != nullptr;
});
- GPR_ASSERT(pending != nullptr);
- // Return payload.
+ GPR_ASSERT(pending != nullptr);
+ // Return payload.
SubchannelCallRetryState* retry_state =
static_cast<SubchannelCallRetryState*>(
batch_data->subchannel_call->GetParentData());
- *pending->batch->payload->recv_message.recv_message =
+ *pending->batch->payload->recv_message.recv_message =
std::move(retry_state->recv_message);
- // Update bookkeeping.
- // Note: Need to do this before invoking the callback, since invoking
- // the callback will result in yielding the call combiner.
- grpc_closure* recv_message_ready =
- pending->batch->payload->recv_message.recv_message_ready;
- pending->batch->payload->recv_message.recv_message_ready = nullptr;
+ // Update bookkeeping.
+ // Note: Need to do this before invoking the callback, since invoking
+ // the callback will result in yielding the call combiner.
+ 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();
- // Invoke callback.
+ // Invoke callback.
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);
- grpc_call_element* elem = batch_data->elem;
+ 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)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: got recv_message_ready, error=%s",
- chand, calld, grpc_error_string(error));
- }
+ 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*>(
batch_data->subchannel_call->GetParentData());
@@ -3053,7 +3053,7 @@ void CallData::RecvMessageReady(void* arg, grpc_error* error) {
"recv_message_ready after retry dispatched");
return;
}
- // If we got an error or the payload was nullptr and we have not yet gotten
+ // If we got an error or the payload was nullptr and we have not yet gotten
// the recv_trailing_metadata_ready callback, then defer propagating this
// callback back to the surface. We can evaluate whether to retry when
// recv_trailing_metadata comes back.
@@ -3061,51 +3061,51 @@ void CallData::RecvMessageReady(void* arg, grpc_error* error) {
(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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: deferring recv_message_ready (nullptr "
- "message and recv_trailing_metadata pending)",
- chand, calld);
- }
- retry_state->recv_message_ready_deferred_batch = batch_data;
- retry_state->recv_message_error = GRPC_ERROR_REF(error);
- if (!retry_state->started_recv_trailing_metadata) {
- // recv_trailing_metadata not yet started by application; start it
- // ourselves to get status.
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: deferring recv_message_ready (nullptr "
+ "message and recv_trailing_metadata pending)",
+ chand, calld);
+ }
+ retry_state->recv_message_ready_deferred_batch = batch_data;
+ retry_state->recv_message_error = GRPC_ERROR_REF(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);
- } else {
+ } else {
GRPC_CALL_COMBINER_STOP(calld->call_combiner_, "recv_message_ready null");
- }
- return;
- }
- // Received a valid message, so commit the call.
+ }
+ return;
+ }
+ // Received a valid message, so commit the call.
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.
+ // Manually invoking a callback function; it does not take ownership of 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) {
if (error != GRPC_ERROR_NONE) {
grpc_error_get_status(error, deadline_, status, nullptr, nullptr, nullptr);
- } else {
+ } else {
GPR_ASSERT(md_batch->idx.named.grpc_status != nullptr);
*status =
grpc_get_status_code_from_metadata(md_batch->idx.named.grpc_status->md);
if (server_pushback_md != nullptr &&
md_batch->idx.named.grpc_retry_pushback_ms != nullptr) {
*server_pushback_md = &md_batch->idx.named.grpc_retry_pushback_ms->md;
- }
- }
+ }
+ }
GRPC_ERROR_UNREF(error);
-}
-
+}
+
void CallData::AddClosureForRecvTrailingMetadataReady(
grpc_call_element* elem, SubchannelCallBatchData* batch_data,
grpc_error* error, CallCombinerClosureList* closures) {
@@ -3122,7 +3122,7 @@ void CallData::AddClosureForRecvTrailingMetadataReady(
if (pending == nullptr) {
GRPC_ERROR_UNREF(error);
return;
- }
+ }
// Return metadata.
SubchannelCallRetryState* retry_state =
static_cast<SubchannelCallRetryState*>(
@@ -3138,13 +3138,13 @@ void CallData::AddClosureForRecvTrailingMetadataReady(
pending->batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
nullptr;
MaybeClearPendingBatch(elem, pending);
-}
-
+}
+
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 (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,
@@ -3154,9 +3154,9 @@ void CallData::AddClosuresForDeferredRecvCallbacks(
closures->Add(&retry_state->recv_initial_metadata_ready,
retry_state->recv_initial_metadata_error,
"resuming recv_initial_metadata_ready");
- retry_state->recv_initial_metadata_ready_deferred_batch = nullptr;
- }
- // Add closure for deferred recv_message_ready.
+ retry_state->recv_initial_metadata_ready_deferred_batch = nullptr;
+ }
+ // Add closure for deferred recv_message_ready.
if (GPR_UNLIKELY(retry_state->recv_message_ready_deferred_batch !=
nullptr)) {
GRPC_CLOSURE_INIT(&retry_state->recv_message_ready,
@@ -3166,11 +3166,11 @@ void CallData::AddClosuresForDeferredRecvCallbacks(
closures->Add(&retry_state->recv_message_ready,
retry_state->recv_message_error,
"resuming recv_message_ready");
- retry_state->recv_message_ready_deferred_batch = nullptr;
- }
- }
-}
-
+ retry_state->recv_message_ready_deferred_batch = nullptr;
+ }
+ }
+}
+
bool CallData::PendingBatchIsUnstarted(PendingBatch* pending,
SubchannelCallRetryState* retry_state) {
if (pending->batch == nullptr || pending->batch->on_complete == nullptr) {
@@ -3321,55 +3321,55 @@ 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 =
+ bool have_pending_send_message_ops =
retry_state->started_send_message_count < send_messages_.size();
- bool have_pending_send_trailing_metadata_op =
+ bool have_pending_send_trailing_metadata_op =
seen_send_trailing_metadata_ &&
- !retry_state->started_send_trailing_metadata;
- if (!have_pending_send_message_ops &&
- !have_pending_send_trailing_metadata_op) {
+ !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];
- 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;
- if (batch->send_trailing_metadata) {
- have_pending_send_trailing_metadata_op = true;
- }
- }
- }
- if (have_pending_send_message_ops || have_pending_send_trailing_metadata_op) {
+ 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;
+ if (batch->send_trailing_metadata) {
+ have_pending_send_trailing_metadata_op = true;
+ }
+ }
+ }
+ if (have_pending_send_message_ops || have_pending_send_trailing_metadata_op) {
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)",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: starting next batch for pending send op(s)",
chand, this);
- }
+ }
GRPC_CLOSURE_INIT(&batch_data->batch.handler_private.closure,
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);
- grpc_call_element* elem = batch_data->elem;
+ 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)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: got on_complete, error=%s, batch=%s",
+ 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*>(
batch_data->subchannel_call->GetParentData());
- // Update bookkeeping in retry_state.
+ // Update bookkeeping in retry_state.
if (batch_data->batch.send_initial_metadata) {
retry_state->completed_send_initial_metadata = true;
- }
+ }
if (batch_data->batch.send_message) {
++retry_state->completed_send_message_count;
}
@@ -3380,8 +3380,8 @@ void CallData::OnComplete(void* arg, grpc_error* error) {
// completed.
if (calld->retry_committed_) {
calld->FreeCachedSendOpDataForCompletedBatch(elem, batch_data, retry_state);
- }
- // Construct list of closures to execute.
+ }
+ // Construct list of closures to execute.
CallCombinerClosureList closures;
// If a retry was already dispatched, that means we saw
// recv_trailing_metadata before this, so we do nothing here.
@@ -3396,36 +3396,36 @@ void CallData::OnComplete(void* arg, grpc_error* error) {
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_;
const bool last_send_batch_complete =
calld->num_pending_retriable_subchannel_send_batches_ == 0;
- // Don't need batch_data anymore.
+ // Don't need batch_data anymore.
batch_data->Unref();
- // Schedule all of the closures identified above.
+ // Schedule all of the closures identified above.
// Note: This yeilds the 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");
}
-}
-
-//
-// subchannel batch construction
-//
-
+}
+
+//
+// subchannel batch construction
+//
+
void CallData::StartBatchInCallCombiner(void* arg, grpc_error* /*ignored*/) {
- grpc_transport_stream_op_batch* batch =
- static_cast<grpc_transport_stream_op_batch*>(arg);
+ 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);
- // Note: This will release the call combiner.
+ // Note: This will release the call combiner.
subchannel_call->StartTransportStreamOpBatch(batch);
-}
-
+}
+
void CallData::AddClosureForSubchannelBatch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch,
CallCombinerClosureList* closures) {
@@ -3436,23 +3436,23 @@ void CallData::AddClosureForSubchannelBatch(
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());
- }
+ }
closures->Add(&batch->handler_private.closure, GRPC_ERROR_NONE,
"start_subchannel_batch");
-}
-
+}
+
void CallData::AddRetriableSendInitialMetadataOp(
SubchannelCallRetryState* retry_state,
SubchannelCallBatchData* batch_data) {
- // Maps the number of retries to the corresponding metadata value slice.
+ // 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};
- // 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.
- //
- // If we've already completed one or more attempts, add the
- // grpc-retry-attempts header.
+ // 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.
+ //
+ // 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) *
@@ -3464,103 +3464,103 @@ void CallData::AddRetriableSendInitialMetadataOp(
.grpc_previous_rpc_attempts != nullptr)) {
grpc_metadata_batch_remove(&retry_state->send_initial_metadata,
GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS);
- }
+ }
if (GPR_UNLIKELY(num_attempts_completed_ > 0)) {
grpc_mdelem retry_md = grpc_mdelem_create(
- GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS,
+ GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS,
*retry_count_strings[num_attempts_completed_ - 1], nullptr);
- grpc_error* error = grpc_metadata_batch_add_tail(
+ 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);
if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
- gpr_log(GPR_ERROR, "error adding retry metadata: %s",
- grpc_error_string(error));
- GPR_ASSERT(false);
- }
- }
- retry_state->started_send_initial_metadata = true;
- batch_data->batch.send_initial_metadata = true;
- batch_data->batch.payload->send_initial_metadata.send_initial_metadata =
+ gpr_log(GPR_ERROR, "error adding retry metadata: %s",
+ grpc_error_string(error));
+ GPR_ASSERT(false);
+ }
+ }
+ retry_state->started_send_initial_metadata = true;
+ batch_data->batch.send_initial_metadata = true;
+ 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 =
+ 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_;
-}
-
+}
+
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 "]",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: starting calld->send_messages[%" PRIuPTR "]",
chand, this, retry_state->started_send_message_count);
- }
+ }
ByteStreamCache* cache =
send_messages_[retry_state->started_send_message_count];
- ++retry_state->started_send_message_count;
+ ++retry_state->started_send_message_count;
retry_state->send_message.Init(cache);
- batch_data->batch.send_message = true;
- batch_data->batch.payload->send_message.send_message.reset(
+ batch_data->batch.send_message = true;
+ batch_data->batch.payload->send_message.send_message.reset(
retry_state->send_message.get());
-}
-
+}
+
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.
+ // 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_,
&retry_state->send_trailing_metadata,
retry_state->send_trailing_metadata_storage);
- retry_state->started_send_trailing_metadata = true;
- batch_data->batch.send_trailing_metadata = true;
- batch_data->batch.payload->send_trailing_metadata.send_trailing_metadata =
+ retry_state->started_send_trailing_metadata = true;
+ batch_data->batch.send_trailing_metadata = true;
+ batch_data->batch.payload->send_trailing_metadata.send_trailing_metadata =
&retry_state->send_trailing_metadata;
-}
-
+}
+
void CallData::AddRetriableRecvInitialMetadataOp(
SubchannelCallRetryState* retry_state,
SubchannelCallBatchData* batch_data) {
- retry_state->started_recv_initial_metadata = true;
- batch_data->batch.recv_initial_metadata = true;
+ retry_state->started_recv_initial_metadata = true;
+ batch_data->batch.recv_initial_metadata = true;
grpc_metadata_batch_init(&retry_state->recv_initial_metadata);
- batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata =
+ batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata =
&retry_state->recv_initial_metadata;
- batch_data->batch.payload->recv_initial_metadata.trailing_metadata_available =
+ 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,
- grpc_schedule_on_exec_ctx);
- batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata_ready =
+ 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) {
- ++retry_state->started_recv_message_count;
- batch_data->batch.recv_message = true;
- batch_data->batch.payload->recv_message.recv_message =
+ ++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,
- batch_data, grpc_schedule_on_exec_ctx);
- batch_data->batch.payload->recv_message.recv_message_ready =
+ 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) {
- retry_state->started_recv_trailing_metadata = true;
- batch_data->batch.recv_trailing_metadata = true;
+ retry_state->started_recv_trailing_metadata = true;
+ batch_data->batch.recv_trailing_metadata = true;
grpc_metadata_batch_init(&retry_state->recv_trailing_metadata);
- batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata =
+ batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata =
&retry_state->recv_trailing_metadata;
batch_data->batch.payload->recv_trailing_metadata.collect_stats =
&retry_state->collect_stats;
@@ -3572,170 +3572,170 @@ void CallData::AddRetriableRecvTrailingMetadataOp(
&retry_state->recv_trailing_metadata_ready;
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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: call failed but recv_trailing_metadata not "
- "started; starting it internally",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: call failed but recv_trailing_metadata not "
+ "started; starting it internally",
chand, this);
- }
+ }
SubchannelCallRetryState* retry_state =
static_cast<SubchannelCallRetryState*>(subchannel_call_->GetParentData());
- // Create batch_data with 2 refs, since this batch will be unreffed twice:
+ // 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);
- retry_state->recv_trailing_metadata_internal_batch = batch_data;
- // Note: This will release the call combiner.
+ retry_state->recv_trailing_metadata_internal_batch = batch_data;
+ // Note: This will release the call combiner.
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.
+}
+
+// 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;
- // send_initial_metadata.
+ // send_initial_metadata.
if (seen_send_initial_metadata_ &&
- !retry_state->started_send_initial_metadata &&
+ !retry_state->started_send_initial_metadata &&
!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",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: replaying previously completed "
+ "send_initial_metadata op",
chand, this);
- }
+ }
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.
+ }
+ // 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() &&
- retry_state->started_send_message_count ==
- retry_state->completed_send_message_count &&
+ 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)) {
- gpr_log(GPR_INFO,
- "chand=%p calld=%p: replaying previously completed "
- "send_message op",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: replaying previously completed "
+ "send_message op",
chand, this);
- }
- if (replay_batch_data == nullptr) {
+ }
+ if (replay_batch_data == nullptr) {
replay_batch_data =
SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
- }
+ }
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.
+ }
+ // 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() &&
- !retry_state->started_send_trailing_metadata &&
+ !retry_state->started_send_trailing_metadata &&
!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",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: replaying previously completed "
+ "send_trailing_metadata op",
chand, this);
- }
- if (replay_batch_data == nullptr) {
+ }
+ if (replay_batch_data == nullptr) {
replay_batch_data =
SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */);
- }
+ }
AddRetriableSendTrailingMetadataOp(retry_state, replay_batch_data);
- }
- return 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];
- grpc_transport_stream_op_batch* batch = pending->batch;
- if (batch == nullptr) continue;
- // Skip any batch that either (a) has already been started on this
- // subchannel call or (b) we can't start yet because we're still
- // replaying send ops that need to be completed first.
- // TODO(roth): Note that if any one op in the batch can't be sent
- // yet due to ops that we're replaying, we don't start any of the ops
- // in the batch. This is probably okay, but it could conceivably
- // lead to increased latency in some cases -- e.g., we could delay
- // starting a recv op due to it being in the same batch with a send
- // op. If/when we revamp the callback protocol in
- // transport_stream_op_batch, we may be able to fix this.
- if (batch->send_initial_metadata &&
- retry_state->started_send_initial_metadata) {
- continue;
- }
- if (batch->send_message && retry_state->completed_send_message_count <
- retry_state->started_send_message_count) {
- continue;
- }
- // Note that we only start send_trailing_metadata 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 (batch->send_trailing_metadata &&
- (retry_state->started_send_message_count + batch->send_message <
+ grpc_transport_stream_op_batch* batch = pending->batch;
+ if (batch == nullptr) continue;
+ // Skip any batch that either (a) has already been started on this
+ // subchannel call or (b) we can't start yet because we're still
+ // replaying send ops that need to be completed first.
+ // TODO(roth): Note that if any one op in the batch can't be sent
+ // yet due to ops that we're replaying, we don't start any of the ops
+ // in the batch. This is probably okay, but it could conceivably
+ // lead to increased latency in some cases -- e.g., we could delay
+ // starting a recv op due to it being in the same batch with a send
+ // op. If/when we revamp the callback protocol in
+ // transport_stream_op_batch, we may be able to fix this.
+ if (batch->send_initial_metadata &&
+ retry_state->started_send_initial_metadata) {
+ continue;
+ }
+ if (batch->send_message && retry_state->completed_send_message_count <
+ retry_state->started_send_message_count) {
+ continue;
+ }
+ // Note that we only start send_trailing_metadata 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 (batch->send_trailing_metadata &&
+ (retry_state->started_send_message_count + batch->send_message <
send_messages_.size() ||
- retry_state->started_send_trailing_metadata)) {
- continue;
- }
- if (batch->recv_initial_metadata &&
- retry_state->started_recv_initial_metadata) {
- continue;
- }
- if (batch->recv_message && retry_state->completed_recv_message_count <
- retry_state->started_recv_message_count) {
- continue;
- }
- if (batch->recv_trailing_metadata &&
- retry_state->started_recv_trailing_metadata) {
- // If we previously completed a recv_trailing_metadata op
+ retry_state->started_send_trailing_metadata)) {
+ continue;
+ }
+ if (batch->recv_initial_metadata &&
+ retry_state->started_recv_initial_metadata) {
+ continue;
+ }
+ if (batch->recv_message && retry_state->completed_recv_message_count <
+ retry_state->started_recv_message_count) {
+ continue;
+ }
+ 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
- // result of that instead of trying to re-start this op.
+ // result of that instead of trying to re-start this op.
if (GPR_UNLIKELY((retry_state->recv_trailing_metadata_internal_batch !=
nullptr))) {
- // If the batch completed, then trigger the completion callback
- // directly, so that we return the previously returned results to
- // the application. Otherwise, just unref the internally
- // started subchannel batch, since we'll propagate the
- // completion when it completes.
- if (retry_state->completed_recv_trailing_metadata) {
- // Batches containing recv_trailing_metadata always succeed.
+ // If the batch completed, then trigger the completion callback
+ // directly, so that we return the previously returned results to
+ // the application. Otherwise, just unref the internally
+ // started subchannel batch, since we'll propagate the
+ // completion when it completes.
+ if (retry_state->completed_recv_trailing_metadata) {
+ // Batches containing recv_trailing_metadata always succeed.
closures->Add(
&retry_state->recv_trailing_metadata_ready, GRPC_ERROR_NONE,
"re-executing recv_trailing_metadata_ready to propagate "
"internally triggered result");
- } else {
+ } else {
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.
+ }
+ 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);
- continue;
- }
- // Create batch with the right number of callbacks.
+ continue;
+ }
+ // Create batch with the right number of callbacks.
const bool has_send_ops = batch->send_initial_metadata ||
batch->send_message ||
batch->send_trailing_metadata;
@@ -3744,34 +3744,34 @@ void CallData::AddSubchannelBatchesForPendingBatches(
batch->recv_trailing_metadata;
SubchannelCallBatchData* batch_data = SubchannelCallBatchData::Create(
elem, num_callbacks, has_send_ops /* set_on_complete */);
- // Cache send ops if needed.
+ // Cache send ops if needed.
MaybeCacheSendOpsForBatch(pending);
- // send_initial_metadata.
- if (batch->send_initial_metadata) {
+ // send_initial_metadata.
+ if (batch->send_initial_metadata) {
AddRetriableSendInitialMetadataOp(retry_state, batch_data);
- }
- // send_message.
- if (batch->send_message) {
+ }
+ // send_message.
+ if (batch->send_message) {
AddRetriableSendMessageOp(elem, retry_state, batch_data);
- }
- // send_trailing_metadata.
- if (batch->send_trailing_metadata) {
+ }
+ // send_trailing_metadata.
+ if (batch->send_trailing_metadata) {
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);
+ }
+ // 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);
- }
- // recv_message.
- if (batch->recv_message) {
+ }
+ // recv_message.
+ if (batch->recv_message) {
AddRetriableRecvMessageOp(retry_state, batch_data);
- }
- // recv_trailing_metadata.
- if (batch->recv_trailing_metadata) {
+ }
+ // recv_trailing_metadata.
+ if (batch->recv_trailing_metadata) {
AddRetriableRecvTrailingMetadataOp(retry_state, batch_data);
- }
+ }
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.
@@ -3782,27 +3782,27 @@ void CallData::AddSubchannelBatchesForPendingBatches(
}
++num_pending_retriable_subchannel_send_batches_;
}
- }
-}
-
+ }
+}
+
void CallData::StartRetriableSubchannelBatches(void* arg,
grpc_error* /*ignored*/) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
+ 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)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: constructing retriable batches",
- chand, calld);
- }
+ gpr_log(GPR_INFO, "chand=%p calld=%p: constructing retriable batches",
+ chand, calld);
+ }
SubchannelCallRetryState* retry_state =
static_cast<SubchannelCallRetryState*>(
calld->subchannel_call_->GetParentData());
- // Construct list of closures to execute, one for each pending batch.
+ // Construct list of closures to execute, one for each pending batch.
CallCombinerClosureList closures;
- // Replay previously-returned send_* ops if needed.
+ // Replay previously-returned send_* ops if needed.
SubchannelCallBatchData* replay_batch_data =
calld->MaybeCreateSubchannelBatchForReplay(elem, retry_state);
- if (replay_batch_data != nullptr) {
+ if (replay_batch_data != nullptr) {
calld->AddClosureForSubchannelBatch(elem, &replay_batch_data->batch,
&closures);
// Track number of pending subchannel send batches.
@@ -3811,27 +3811,27 @@ void CallData::StartRetriableSubchannelBatches(void* arg,
GRPC_CALL_STACK_REF(calld->owning_call_, "subchannel_send_batches");
}
++calld->num_pending_retriable_subchannel_send_batches_;
- }
- // Now add pending batches.
+ }
+ // Now add pending batches.
calld->AddSubchannelBatchesForPendingBatches(elem, retry_state, &closures);
- // Start batches on subchannel call.
+ // Start batches on subchannel call.
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",
+ gpr_log(GPR_INFO,
+ "chand=%p calld=%p: starting %" PRIuPTR
+ " retriable batches on subchannel_call=%p",
chand, calld, closures.size(), calld->subchannel_call_.get());
- }
+ }
// Note: This will yield the call combiner.
closures.RunClosures(calld->call_combiner_);
-}
-
-//
-// LB pick
-//
-
+}
+
+//
+// LB pick
+//
+
void CallData::CreateSubchannelCall(grpc_call_element* elem) {
ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
- const size_t parent_data_size =
+ const size_t parent_data_size =
enable_retries_ ? sizeof(SubchannelCallRetryState) : 0;
SubchannelCall::Args call_args = {
std::move(connected_subchannel_), pollent_, path_, call_start_time_,
@@ -3842,27 +3842,27 @@ void CallData::CreateSubchannelCall(grpc_call_element* elem) {
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",
+ gpr_log(GPR_INFO, "chand=%p calld=%p: create subchannel_call=%p: error=%s",
chand, this, subchannel_call_.get(), grpc_error_string(error));
- }
+ }
if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) {
PendingBatchesFail(elem, error, YieldCallCombiner);
- } else {
- if (parent_data_size > 0) {
+ } else {
+ if (parent_data_size > 0) {
new (subchannel_call_->GetParentData())
SubchannelCallRetryState(call_context_);
- }
+ }
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) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
+ 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) {
@@ -3870,13 +3870,13 @@ void CallData::PickDone(void* arg, grpc_error* error) {
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->CreateSubchannelCall(elem);
-}
-
+}
+
// A class to handle the call combiner cancellation callback for a
// queued pick.
class CallData::QueuedPickCanceller {
@@ -3887,7 +3887,7 @@ class CallData::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) {
@@ -3929,8 +3929,8 @@ void CallData::MaybeRemoveCallFromQueuedPicksLocked(grpc_call_element* elem) {
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);
@@ -3949,9 +3949,9 @@ 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)) {
- gpr_log(GPR_INFO, "chand=%p calld=%p: applying service config to call",
+ gpr_log(GPR_INFO, "chand=%p calld=%p: applying service config to call",
chand, this);
- }
+ }
ConfigSelector* config_selector = chand->config_selector();
if (config_selector != nullptr) {
// Use the ConfigSelector to determine the config for the call.
@@ -3984,7 +3984,7 @@ grpc_error* CallData::ApplyServiceConfigToCallLocked(
deadline_ = per_method_deadline;
grpc_deadline_state_reset(elem, deadline_);
}
- }
+ }
// If the service config set wait_for_ready and the application
// did not explicitly set it, use the value from the service config.
uint32_t* send_initial_metadata_flags =
@@ -4000,25 +4000,25 @@ grpc_error* CallData::ApplyServiceConfigToCallLocked(
*send_initial_metadata_flags &= ~GRPC_INITIAL_METADATA_WAIT_FOR_READY;
}
}
- }
+ }
// Set retry throttle data for call.
retry_throttle_data_ = chand->retry_throttle_data();
- }
- // If no retry policy, disable retries.
- // TODO(roth): Remove this when adding support for transparent retries.
+ }
+ // 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;
- }
+ }
return GRPC_ERROR_NONE;
-}
-
+}
+
void CallData::MaybeInvokeConfigSelectorCommitCallback() {
if (on_call_committed_ != nullptr) {
on_call_committed_();
on_call_committed_ = nullptr;
- }
-}
-
+ }
+}
+
const char* PickResultTypeName(
LoadBalancingPolicy::PickResult::ResultType type) {
switch (type) {
@@ -4033,14 +4033,14 @@ const char* PickResultTypeName(
}
void CallData::PickSubchannel(void* arg, grpc_error* error) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
+ 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);
@@ -4137,7 +4137,7 @@ bool CallData::PickSubchannelLocked(grpc_call_element* elem,
"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.
@@ -4174,7 +4174,7 @@ bool CallData::PickSubchannelLocked(grpc_call_element* elem,
// 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:
MaybeAddCallToQueuedPicksLocked(elem);
@@ -4201,20 +4201,20 @@ bool CallData::PickSubchannelLocked(grpc_call_element* elem,
lb_recv_trailing_metadata_ready_ = result.recv_trailing_metadata_ready;
*error = result.error;
return true;
- }
-}
-
+ }
+}
+
} // namespace
} // namespace grpc_core
-
-/*************************************************************************
- * EXPORTED SYMBOLS
- */
-
+
+/*************************************************************************
+ * EXPORTED SYMBOLS
+ */
+
using grpc_core::CallData;
using grpc_core::ChannelData;
-const grpc_channel_filter grpc_client_channel_filter = {
+const grpc_channel_filter grpc_client_channel_filter = {
CallData::StartTransportStreamOpBatch,
ChannelData::StartTransportOp,
sizeof(CallData),
@@ -4225,21 +4225,21 @@ const grpc_channel_filter grpc_client_channel_filter = {
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) {
+ "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);
-}
-
+}
+
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,
@@ -4249,30 +4249,30 @@ void grpc_client_channel_watch_connectivity_state(
// Handle cancellation.
GPR_ASSERT(watcher_timer_init == nullptr);
chand->RemoveExternalConnectivityWatcher(closure, /*cancel=*/true);
- return;
- }
+ return;
+ }
// 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_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();
-}
+}
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 35c2a2af6b2..25cd83bc36f 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
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_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_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_H
+
+#include <grpc/support/port_platform.h>
+
#include "src/core/ext/filters/client_channel/client_channel_channelz.h"
-#include "src/core/ext/filters/client_channel/client_channel_factory.h"
-#include "src/core/ext/filters/client_channel/resolver.h"
-#include "src/core/lib/channel/channel_stack.h"
-
-extern grpc_core::TraceFlag grpc_client_channel_trace;
-
-// Channel arg key for server URI string.
-#define GRPC_ARG_SERVER_URI "grpc.server_uri"
-
-/* A client channel is a channel that begins disconnected, and can connect
- to some endpoint on demand. If that endpoint disconnects, it will be
- connected to again later.
-
- Calls on a disconnected client channel are queued until a connection is
- established. */
-
-extern const grpc_channel_filter grpc_client_channel_filter;
-
-grpc_connectivity_state grpc_client_channel_check_connectivity_state(
- grpc_channel_element* elem, int try_to_connect);
-
-int grpc_client_channel_num_external_connectivity_watchers(
- grpc_channel_element* elem);
-
+#include "src/core/ext/filters/client_channel/client_channel_factory.h"
+#include "src/core/ext/filters/client_channel/resolver.h"
+#include "src/core/lib/channel/channel_stack.h"
+
+extern grpc_core::TraceFlag grpc_client_channel_trace;
+
+// Channel arg key for server URI string.
+#define GRPC_ARG_SERVER_URI "grpc.server_uri"
+
+/* A client channel is a channel that begins disconnected, and can connect
+ to some endpoint on demand. If that endpoint disconnects, it will be
+ connected to again later.
+
+ Calls on a disconnected client channel are queued until a connection is
+ established. */
+
+extern const grpc_channel_filter grpc_client_channel_filter;
+
+grpc_connectivity_state grpc_client_channel_check_connectivity_state(
+ grpc_channel_element* elem, int try_to_connect);
+
+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
@@ -55,11 +55,11 @@ int grpc_client_channel_num_external_connectivity_watchers(
// 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);
-
+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
@@ -75,8 +75,8 @@ 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 */
+/* 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);
-
+
#endif // GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_H
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 c0d853ebe5f..54af26996eb 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
@@ -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/client_channel_factory.h"
-#include "src/core/lib/channel/channel_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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#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"
-
+
namespace grpc_core {
-
+
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);
-}
+}
const grpc_arg_pointer_vtable factory_arg_vtable = {
factory_arg_copy, factory_arg_destroy, factory_arg_cmp};
-
+
} // 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);
-}
-
+}
+
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
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 79797bbc454..32e4fda1a86 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
@@ -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_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_FACTORY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_FACTORY_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/grpc_types.h>
-
-#include "src/core/ext/filters/client_channel/subchannel.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_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_FACTORY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_FACTORY_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/impl/codegen/grpc_types.h>
+
+#include "src/core/ext/filters/client_channel/subchannel.h"
+
namespace grpc_core {
-
+
class ClientChannelFactory {
public:
virtual ~ClientChannelFactory() = default;
-
+
// 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 the factory from args, or null if not found.
static ClientChannelFactory* GetFromChannelArgs(
const grpc_channel_args* args);
-};
-
+};
+
} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_FACTORY_H */
+
+#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 2358415fc2e..0e25e43b001 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
@@ -1,70 +1,70 @@
-/*
- *
- * 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 <stdbool.h>
-#include <string.h>
-
-#include <grpc/support/alloc.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 <limits.h>
+#include <stdbool.h>
+#include <string.h>
+
+#include <grpc/support/alloc.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.h"
#include "src/core/ext/filters/client_channel/client_channel_channelz.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/http_proxy.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/http_connect_handshaker.h"
+#include "src/core/ext/filters/client_channel/http_proxy.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/resolver_result_parsing.h"
-#include "src/core/ext/filters/client_channel/retry_throttle.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"
-
-static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
- return grpc_channel_stack_builder_append_filter(
- builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
-}
-
-void grpc_client_channel_init(void) {
+#include "src/core/lib/surface/channel_init.h"
+
+static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
+ return grpc_channel_stack_builder_append_filter(
+ builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
+}
+
+void grpc_client_channel_init(void) {
grpc_core::ServiceConfigParser::Init();
grpc_core::internal::ClientChannelServiceConfigParser::Register();
- grpc_core::LoadBalancingPolicyRegistry::Builder::InitRegistry();
- grpc_core::ResolverRegistry::Builder::InitRegistry();
- grpc_core::internal::ServerRetryThrottleMap::Init();
+ grpc_core::LoadBalancingPolicyRegistry::Builder::InitRegistry();
+ grpc_core::ResolverRegistry::Builder::InitRegistry();
+ grpc_core::internal::ServerRetryThrottleMap::Init();
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_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();
-}
-
-void grpc_client_channel_shutdown(void) {
+}
+
+void grpc_client_channel_shutdown(void) {
grpc_core::GlobalSubchannelPool::Shutdown();
- grpc_channel_init_shutdown();
+ grpc_channel_init_shutdown();
grpc_core::ProxyMapperRegistry::Shutdown();
- grpc_core::internal::ServerRetryThrottleMap::Shutdown();
- grpc_core::ResolverRegistry::Builder::ShutdownRegistry();
- grpc_core::LoadBalancingPolicyRegistry::Builder::ShutdownRegistry();
+ grpc_core::internal::ServerRetryThrottleMap::Shutdown();
+ grpc_core::ResolverRegistry::Builder::ShutdownRegistry();
+ grpc_core::LoadBalancingPolicyRegistry::Builder::ShutdownRegistry();
grpc_core::ServiceConfigParser::Shutdown();
-}
+}
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 256471456e3..1300058b110 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
@@ -1,34 +1,34 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.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_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H
+
+#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/iomgr/resolve_address.h"
-#include "src/core/lib/transport/transport.h"
-
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/transport/transport.h"
+
namespace grpc_core {
-
+
// Interface for connection-establishment functionality.
// Each transport that supports client channels (e.g., not inproc) must
// supply an implementation of this.
@@ -42,7 +42,7 @@ class SubchannelConnector : public InternallyRefCounted<SubchannelConnector> {
// Channel args to be passed to handshakers and transport.
const grpc_channel_args* channel_args;
};
-
+
struct Result {
// The connected transport.
grpc_transport* transport = nullptr;
@@ -50,14 +50,14 @@ class SubchannelConnector : public InternallyRefCounted<SubchannelConnector> {
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();
}
};
-
+
// Attempts to connect.
// When complete, populates *result and invokes notify.
// Only one connection attempt may be in progress at any one time.
@@ -67,13 +67,13 @@ class SubchannelConnector : public InternallyRefCounted<SubchannelConnector> {
// 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();
}
-};
-
+};
+
} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H */
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H */
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 190baabd0a3..6278efa81c0 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
@@ -1,49 +1,49 @@
-/*
- *
- * 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/ext/filters/client_channel/http_connect_handshaker.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
-#include "src/core/ext/filters/client_channel/resolver_registry.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/handshaker_registry.h"
-#include "src/core/lib/gpr/string.h"
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
+#include "src/core/ext/filters/client_channel/resolver_registry.h"
+#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/http/format_request.h"
-#include "src/core/lib/http/parser.h"
-#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/http/format_request.h"
+#include "src/core/lib/http/parser.h"
+#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/uri/uri_parser.h"
-
+
namespace grpc_core {
-
+
namespace {
-
+
class HttpConnectHandshaker : public Handshaker {
public:
HttpConnectHandshaker();
@@ -65,26 +65,26 @@ class HttpConnectHandshaker : public Handshaker {
Mutex mu_;
bool is_shutdown_ = false;
- // Endpoint and read buffer to destroy after a shutdown.
+ // Endpoint and read buffer to destroy after a shutdown.
grpc_endpoint* endpoint_to_destroy_ = nullptr;
grpc_slice_buffer* read_buffer_to_destroy_ = nullptr;
-
- // State saved while performing the handshake.
+
+ // State saved while performing the handshake.
HandshakerArgs* args_ = nullptr;
grpc_closure* on_handshake_done_ = nullptr;
-
- // Objects for processing the HTTP CONNECT request and response.
+
+ // Objects for processing the HTTP CONNECT request and response.
grpc_slice_buffer write_buffer_;
grpc_closure request_done_closure_;
grpc_closure response_read_closure_;
grpc_http_parser http_parser_;
grpc_http_response http_response_;
};
-
+
HttpConnectHandshaker::~HttpConnectHandshaker() {
if (endpoint_to_destroy_ != nullptr) {
grpc_endpoint_destroy(endpoint_to_destroy_);
- }
+ }
if (read_buffer_to_destroy_ != nullptr) {
grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_);
gpr_free(read_buffer_to_destroy_);
@@ -92,10 +92,10 @@ HttpConnectHandshaker::~HttpConnectHandshaker() {
grpc_slice_buffer_destroy_internal(&write_buffer_);
grpc_http_parser_destroy(&http_parser_);
grpc_http_response_destroy(&http_response_);
-}
-
-// Set args fields to nullptr, saving the endpoint and read buffer for
-// later destruction.
+}
+
+// Set args fields to nullptr, saving the endpoint and read buffer for
+// later destruction.
void HttpConnectHandshaker::CleanupArgsForFailureLocked() {
endpoint_to_destroy_ = args_->endpoint;
args_->endpoint = nullptr;
@@ -103,34 +103,34 @@ void HttpConnectHandshaker::CleanupArgsForFailureLocked() {
args_->read_buffer = nullptr;
grpc_channel_args_destroy(args_->args);
args_->args = nullptr;
-}
-
-// If the handshake failed or we're shutting down, clean up and invoke the
-// callback with the error.
+}
+
+// If the handshake failed or we're shutting down, clean up and invoke the
+// callback with the error.
void HttpConnectHandshaker::HandshakeFailedLocked(grpc_error* error) {
- if (error == GRPC_ERROR_NONE) {
- // If we were shut down after an endpoint operation succeeded but
- // before the endpoint callback was invoked, we need to generate our
- // own error.
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
- }
+ if (error == GRPC_ERROR_NONE) {
+ // If we were shut down after an endpoint operation succeeded but
+ // before the endpoint callback was invoked, we need to generate our
+ // own error.
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
+ }
if (!is_shutdown_) {
- // 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.
+ // 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));
- // Not shutting down, so the handshake failed. Clean up before
- // invoking the callback.
+ // Not shutting down, so the handshake failed. Clean up before
+ // invoking the callback.
CleanupArgsForFailureLocked();
- // Set shutdown to true so that subsequent calls to
- // http_connect_handshaker_shutdown() do nothing.
+ // Set shutdown to true so that subsequent calls to
+ // http_connect_handshaker_shutdown() do nothing.
is_shutdown_ = true;
- }
- // Invoke callback.
+ }
+ // 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) {
@@ -143,28 +143,28 @@ void HttpConnectHandshaker::OnWriteDoneScheduler(void* arg, grpc_error* error) {
GRPC_ERROR_REF(error));
}
-// Callback invoked when finished writing HTTP CONNECT request.
+// 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_);
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.
+ // 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();
handshaker->Unref();
- } else {
- // Otherwise, read the response.
- // The read callback inherits our ref to the handshaker.
+ } 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);
- }
-}
-
+ }
+}
+
// 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) {
@@ -177,59 +177,59 @@ void HttpConnectHandshaker::OnReadDoneScheduler(void* arg, grpc_error* error) {
GRPC_ERROR_REF(error));
}
-// Callback invoked for reading HTTP CONNECT response.
+// 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_);
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.
+ // If the read failed or we're shutting down, clean up and invoke the
+ // callback with the error.
handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error));
- goto done;
- }
- // Add buffer to parser.
+ goto done;
+ }
+ // Add buffer to parser.
for (size_t i = 0; i < handshaker->args_->read_buffer->count; ++i) {
if (GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i]) > 0) {
- size_t body_start_offset = 0;
+ size_t body_start_offset = 0;
error = grpc_http_parser_parse(&handshaker->http_parser_,
handshaker->args_->read_buffer->slices[i],
- &body_start_offset);
- if (error != GRPC_ERROR_NONE) {
+ &body_start_offset);
+ if (error != GRPC_ERROR_NONE) {
handshaker->HandshakeFailedLocked(error);
- goto done;
- }
+ goto done;
+ }
if (handshaker->http_parser_.state == GRPC_HTTP_BODY) {
- // Remove the data we've already read from the read buffer,
- // leaving only the leftover bytes (if any).
- grpc_slice_buffer tmp_buffer;
- grpc_slice_buffer_init(&tmp_buffer);
- if (body_start_offset <
+ // Remove the data we've already read from the read buffer,
+ // leaving only the leftover bytes (if any).
+ grpc_slice_buffer tmp_buffer;
+ grpc_slice_buffer_init(&tmp_buffer);
+ if (body_start_offset <
GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i])) {
- grpc_slice_buffer_add(
- &tmp_buffer,
+ grpc_slice_buffer_add(
+ &tmp_buffer,
grpc_slice_split_tail(&handshaker->args_->read_buffer->slices[i],
- body_start_offset));
- }
- grpc_slice_buffer_addn(&tmp_buffer,
+ body_start_offset));
+ }
+ grpc_slice_buffer_addn(&tmp_buffer,
&handshaker->args_->read_buffer->slices[i + 1],
handshaker->args_->read_buffer->count - i - 1);
grpc_slice_buffer_swap(handshaker->args_->read_buffer, &tmp_buffer);
- grpc_slice_buffer_destroy_internal(&tmp_buffer);
- break;
- }
- }
- }
- // If we're not done reading the response, read more data.
- // TODO(roth): In practice, I suspect that the response to a CONNECT
- // request will never include a body, in which case this check is
- // sufficient. However, the language of RFC-2817 doesn't explicitly
- // forbid the response from including a body. If there is a body,
- // it's possible that we might have parsed part but not all of the
- // body, in which case this check will cause us to fail to parse the
- // remainder of the body. If that ever becomes an issue, we may
- // need to fix the HTTP parser to understand when the body is
- // complete (e.g., handling chunked transfer encoding or looking
- // at the Content-Length: header).
+ grpc_slice_buffer_destroy_internal(&tmp_buffer);
+ break;
+ }
+ }
+ }
+ // If we're not done reading the response, read more data.
+ // TODO(roth): In practice, I suspect that the response to a CONNECT
+ // request will never include a body, in which case this check is
+ // sufficient. However, the language of RFC-2817 doesn't explicitly
+ // forbid the response from including a body. If there is a body,
+ // it's possible that we might have parsed part but not all of the
+ // body, in which case this check will cause us to fail to parse the
+ // remainder of the body. If that ever becomes an issue, we may
+ // need to fix the HTTP parser to understand when the body is
+ // complete (e.g., handling chunked transfer encoding or looking
+ // 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(
@@ -238,9 +238,9 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
&HttpConnectHandshaker::OnReadDoneScheduler,
handshaker, grpc_schedule_on_exec_ctx),
/*urgent=*/true);
- return;
- }
- // Make sure we got a 2xx response.
+ return;
+ }
+ // Make sure we got a 2xx response.
if (handshaker->http_response_.status < 200 ||
handshaker->http_response_.status >= 300) {
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
@@ -248,22 +248,22 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
handshaker->http_response_.status)
.c_str());
handshaker->HandshakeFailedLocked(error);
- goto done;
- }
- // Success. Invoke handshake-done callback.
+ goto done;
+ }
+ // Success. Invoke handshake-done callback.
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.
+done:
+ // Set shutdown to true so that subsequent calls to
+ // http_connect_handshaker_shutdown() do nothing.
handshaker->is_shutdown_ = true;
lock.Unlock();
handshaker->Unref();
-}
-
-//
-// Public handshaker methods
-//
-
+}
+
+//
+// Public handshaker methods
+//
+
void HttpConnectHandshaker::Shutdown(grpc_error* why) {
{
MutexLock lock(&mu_);
@@ -272,83 +272,83 @@ void HttpConnectHandshaker::Shutdown(grpc_error* why) {
grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why));
CleanupArgsForFailureLocked();
}
- }
- GRPC_ERROR_UNREF(why);
-}
-
+ }
+ GRPC_ERROR_UNREF(why);
+}
+
void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
grpc_closure* on_handshake_done,
HandshakerArgs* args) {
- // Check for HTTP CONNECT channel arg.
- // If not found, invoke on_handshake_done without doing anything.
- const grpc_arg* arg =
- grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_SERVER);
- char* server_name = grpc_channel_arg_get_string(arg);
- if (server_name == nullptr) {
- // Set shutdown to true so that subsequent calls to
- // http_connect_handshaker_shutdown() do nothing.
+ // Check for HTTP CONNECT channel arg.
+ // If not found, invoke on_handshake_done without doing anything.
+ const grpc_arg* arg =
+ grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_SERVER);
+ char* server_name = grpc_channel_arg_get_string(arg);
+ 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);
- return;
- }
- // Get headers from channel args.
- arg = grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_HEADERS);
- char* arg_header_string = grpc_channel_arg_get_string(arg);
- grpc_http_header* headers = nullptr;
- size_t num_headers = 0;
- char** header_strings = nullptr;
- size_t num_header_strings = 0;
- if (arg_header_string != nullptr) {
- gpr_string_split(arg_header_string, "\n", &header_strings,
- &num_header_strings);
- headers = static_cast<grpc_http_header*>(
- gpr_malloc(sizeof(grpc_http_header) * num_header_strings));
- for (size_t i = 0; i < num_header_strings; ++i) {
- char* sep = strchr(header_strings[i], ':');
+ return;
+ }
+ // Get headers from channel args.
+ arg = grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_HEADERS);
+ char* arg_header_string = grpc_channel_arg_get_string(arg);
+ grpc_http_header* headers = nullptr;
+ size_t num_headers = 0;
+ char** header_strings = nullptr;
+ size_t num_header_strings = 0;
+ if (arg_header_string != nullptr) {
+ gpr_string_split(arg_header_string, "\n", &header_strings,
+ &num_header_strings);
+ headers = static_cast<grpc_http_header*>(
+ gpr_malloc(sizeof(grpc_http_header) * num_header_strings));
+ for (size_t i = 0; i < num_header_strings; ++i) {
+ char* sep = strchr(header_strings[i], ':');
- if (sep == nullptr) {
- gpr_log(GPR_ERROR, "skipping unparseable HTTP CONNECT header: %s",
- header_strings[i]);
- continue;
- }
- *sep = '\0';
- headers[num_headers].key = header_strings[i];
- headers[num_headers].value = sep + 1;
- ++num_headers;
- }
- }
- // Save state in the handshaker object.
+ if (sep == nullptr) {
+ gpr_log(GPR_ERROR, "skipping unparseable HTTP CONNECT header: %s",
+ header_strings[i]);
+ continue;
+ }
+ *sep = '\0';
+ headers[num_headers].key = header_strings[i];
+ headers[num_headers].value = sep + 1;
+ ++num_headers;
+ }
+ }
+ // Save state in the handshaker object.
MutexLock lock(&mu_);
args_ = args;
on_handshake_done_ = on_handshake_done;
- // Log connection via proxy.
+ // Log connection via proxy.
TString proxy_name(grpc_endpoint_get_peer(args->endpoint));
- gpr_log(GPR_INFO, "Connecting to server %s via HTTP proxy %s", server_name,
+ gpr_log(GPR_INFO, "Connecting to server %s via HTTP proxy %s", server_name,
proxy_name.c_str());
- // Construct HTTP CONNECT request.
- grpc_httpcli_request request;
- request.host = server_name;
+ // Construct HTTP CONNECT request.
+ grpc_httpcli_request request;
+ request.host = server_name;
request.ssl_host_override = nullptr;
- request.http.method = (char*)"CONNECT";
- request.http.path = server_name;
+ request.http.method = (char*)"CONNECT";
+ request.http.path = server_name;
request.http.version = GRPC_HTTP_HTTP10; // Set by OnReadDone
- request.http.hdrs = headers;
- request.http.hdr_count = num_headers;
+ request.http.hdrs = headers;
+ request.http.hdr_count = num_headers;
request.http.body_length = 0;
request.http.body = nullptr;
- request.handshaker = &grpc_httpcli_plaintext;
- grpc_slice request_slice = grpc_httpcli_format_connect_request(&request);
+ request.handshaker = &grpc_httpcli_plaintext;
+ grpc_slice request_slice = grpc_httpcli_format_connect_request(&request);
grpc_slice_buffer_add(&write_buffer_, request_slice);
- // Clean up.
- gpr_free(headers);
- for (size_t i = 0; i < num_header_strings; ++i) {
- gpr_free(header_strings[i]);
- }
- gpr_free(header_strings);
- // Take a new ref to be held by the write callback.
+ // Clean up.
+ gpr_free(headers);
+ for (size_t i = 0; i < num_header_strings; ++i) {
+ gpr_free(header_strings[i]);
+ }
+ gpr_free(header_strings);
+ // Take a new ref to be held by the write callback.
Ref().release();
grpc_endpoint_write(
args->endpoint, &write_buffer_,
@@ -356,17 +356,17 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
&HttpConnectHandshaker::OnWriteDoneScheduler, this,
grpc_schedule_on_exec_ctx),
nullptr);
-}
-
+}
+
HttpConnectHandshaker::HttpConnectHandshaker() {
grpc_slice_buffer_init(&write_buffer_);
grpc_http_parser_init(&http_parser_, GRPC_HTTP_RESPONSE, &http_response_);
-}
-
-//
-// handshaker factory
-//
-
+}
+
+//
+// handshaker factory
+//
+
class HttpConnectHandshakerFactory : public HandshakerFactory {
public:
void AddHandshakers(const grpc_channel_args* /*args*/,
@@ -376,14 +376,14 @@ class HttpConnectHandshakerFactory : public HandshakerFactory {
}
~HttpConnectHandshakerFactory() override = default;
};
-
+
} // namespace
-
+
} // namespace grpc_core
-
-void grpc_http_connect_register_handshaker_factory() {
+
+void grpc_http_connect_register_handshaker_factory() {
using namespace grpc_core;
HandshakerRegistry::RegisterHandshakerFactory(
true /* at_start */, HANDSHAKER_CLIENT,
y_absl::make_unique<HttpConnectHandshakerFactory>());
-}
+}
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 26c31f2a0ab..77b5040cca8 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
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_CONNECT_HANDSHAKER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_CONNECT_HANDSHAKER_H
-
-/// Channel arg indicating the server in HTTP CONNECT request (string).
-/// The presence of this arg triggers the use of HTTP CONNECT.
-#define GRPC_ARG_HTTP_CONNECT_SERVER "grpc.http_connect_server"
-
-/// Channel arg indicating HTTP CONNECT headers (string).
-/// Multiple headers are separated by newlines. Key/value pairs are
+/*
+ *
+ * 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_HTTP_CONNECT_HANDSHAKER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_CONNECT_HANDSHAKER_H
+
+/// Channel arg indicating the server in HTTP CONNECT request (string).
+/// The presence of this arg triggers the use of HTTP CONNECT.
+#define GRPC_ARG_HTTP_CONNECT_SERVER "grpc.http_connect_server"
+
+/// Channel arg indicating HTTP CONNECT headers (string).
+/// Multiple headers are separated by newlines. Key/value pairs are
/// separated by colons.
-#define GRPC_ARG_HTTP_CONNECT_HEADERS "grpc.http_connect_headers"
-
-/// Registers handshaker factory.
-void grpc_http_connect_register_handshaker_factory();
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_CONNECT_HANDSHAKER_H */
+#define GRPC_ARG_HTTP_CONNECT_HEADERS "grpc.http_connect_headers"
+
+/// Registers handshaker factory.
+void grpc_http_connect_register_handshaker_factory();
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_CONNECT_HANDSHAKER_H */
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 2187682526c..894cb545fec 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/http_proxy.h"
-
-#include <stdbool.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/http_proxy.h"
+
+#include <stdbool.h>
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
-#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/gpr/string.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
+#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
+#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/slice/b64.h"
+#include "src/core/lib/slice/b64.h"
#include "src/core/lib/uri/uri_parser.h"
-
+
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
* credentials if present in the 'http_proxy' env var, otherwise leaves it
* unchanged. It is caller's responsibility to gpr_free user_cred.
- */
+ */
char* GetHttpProxyServer(const grpc_channel_args* args, char** user_cred) {
- GPR_ASSERT(user_cred != nullptr);
+ GPR_ASSERT(user_cred != nullptr);
grpc_uri* uri = nullptr;
- char* proxy_name = nullptr;
- char** authority_strs = nullptr;
- size_t authority_nstrs;
+ char* proxy_name = nullptr;
+ char** authority_strs = nullptr;
+ size_t authority_nstrs;
/* We check the following places to determine the HTTP proxy to use, stopping
* at the first one that is set:
* 1. GRPC_ARG_HTTP_PROXY channel arg
@@ -66,43 +66,43 @@ char* GetHttpProxyServer(const grpc_channel_args* args, char** user_cred) {
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("http_proxy");
- if (uri_str == nullptr) return nullptr;
+ if (uri_str == nullptr) return nullptr;
// an emtpy value means "don't use proxy"
if (uri_str[0] == '\0') goto done;
uri = grpc_uri_parse(uri_str, false /* suppress_errors */);
- if (uri == nullptr || uri->authority == nullptr) {
- gpr_log(GPR_ERROR, "cannot parse value of 'http_proxy' env var");
- goto done;
- }
- if (strcmp(uri->scheme, "http") != 0) {
- gpr_log(GPR_ERROR, "'%s' scheme not supported in proxy URI", uri->scheme);
- goto done;
- }
- /* Split on '@' to separate user credentials from host */
- gpr_string_split(uri->authority, "@", &authority_strs, &authority_nstrs);
- GPR_ASSERT(authority_nstrs != 0); /* should have at least 1 string */
- if (authority_nstrs == 1) {
- /* User cred not present in authority */
- proxy_name = authority_strs[0];
- } else if (authority_nstrs == 2) {
- /* User cred found */
- *user_cred = authority_strs[0];
- proxy_name = authority_strs[1];
- gpr_log(GPR_DEBUG, "userinfo found in proxy URI");
- } else {
- /* Bad authority */
- for (size_t i = 0; i < authority_nstrs; i++) {
- gpr_free(authority_strs[i]);
- }
- proxy_name = nullptr;
- }
- gpr_free(authority_strs);
-done:
- gpr_free(uri_str);
- grpc_uri_destroy(uri);
- return proxy_name;
-}
-
+ if (uri == nullptr || uri->authority == nullptr) {
+ gpr_log(GPR_ERROR, "cannot parse value of 'http_proxy' env var");
+ goto done;
+ }
+ if (strcmp(uri->scheme, "http") != 0) {
+ gpr_log(GPR_ERROR, "'%s' scheme not supported in proxy URI", uri->scheme);
+ goto done;
+ }
+ /* Split on '@' to separate user credentials from host */
+ gpr_string_split(uri->authority, "@", &authority_strs, &authority_nstrs);
+ GPR_ASSERT(authority_nstrs != 0); /* should have at least 1 string */
+ if (authority_nstrs == 1) {
+ /* User cred not present in authority */
+ proxy_name = authority_strs[0];
+ } else if (authority_nstrs == 2) {
+ /* User cred found */
+ *user_cred = authority_strs[0];
+ proxy_name = authority_strs[1];
+ gpr_log(GPR_DEBUG, "userinfo found in proxy URI");
+ } else {
+ /* Bad authority */
+ for (size_t i = 0; i < authority_nstrs; i++) {
+ gpr_free(authority_strs[i]);
+ }
+ proxy_name = nullptr;
+ }
+ gpr_free(authority_strs);
+done:
+ gpr_free(uri_str);
+ grpc_uri_destroy(uri);
+ return proxy_name;
+}
+
class HttpProxyMapper : public ProxyMapperInterface {
public:
bool MapName(const char* server_uri, const grpc_channel_args* args,
@@ -119,7 +119,7 @@ class HttpProxyMapper : public ProxyMapperInterface {
gpr_log(GPR_ERROR,
"'http_proxy' environment variable set, but cannot "
"parse server URI '%s' -- not using proxy",
- server_uri);
+ server_uri);
goto no_use_proxy;
}
if (strcmp(uri->scheme, "unix") == 0) {
@@ -161,15 +161,15 @@ class HttpProxyMapper : public ProxyMapperInterface {
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;
- }
- }
+ }
+ }
grpc_arg args_to_add[2];
args_to_add[0] = grpc_channel_arg_string_create(
(char*)GRPC_ARG_HTTP_CONNECT_SERVER,
@@ -197,22 +197,22 @@ class HttpProxyMapper : public ProxyMapperInterface {
*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;
- }
+ }
};
-
+
} // namespace
void RegisterHttpProxyMapper() {
ProxyMapperRegistry::Register(
true /* at_start */,
std::unique_ptr<ProxyMapperInterface>(new HttpProxyMapper()));
-}
-
+}
+
} // 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 cecdaf8478a..f6e4b4dbe0b 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
@@ -1,28 +1,28 @@
-/*
- *
- * 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_HTTP_PROXY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_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_HTTP_PROXY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H
+
namespace grpc_core {
-
+
void RegisterHttpProxyMapper();
} // namespace grpc_core
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H */
+#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 6c639ef86ce..532dbc25af9 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy.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/lb_policy.h"
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
-#include "src/core/lib/iomgr/combiner.h"
-
-namespace grpc_core {
-
+#include "src/core/lib/iomgr/combiner.h"
+
+namespace grpc_core {
+
DebugOnlyTraceFlag grpc_trace_lb_policy_refcount(false, "lb_policy_refcount");
//
@@ -34,13 +34,13 @@ DebugOnlyTraceFlag grpc_trace_lb_policy_refcount(false, "lb_policy_refcount");
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()),
+ interested_parties_(grpc_pollset_set_create()),
channel_control_helper_(std::move(args.channel_control_helper)) {}
-
-LoadBalancingPolicy::~LoadBalancingPolicy() {
- grpc_pollset_set_destroy(interested_parties_);
-}
-
+
+LoadBalancingPolicy::~LoadBalancingPolicy() {
+ grpc_pollset_set_destroy(interested_parties_);
+}
+
void LoadBalancingPolicy::Orphan() {
ShutdownLocked();
Unref(DEBUG_LOCATION, "Orphan");
@@ -117,12 +117,12 @@ LoadBalancingPolicy::PickResult LoadBalancingPolicy::QueuePicker::Pick(
},
parent, nullptr),
GRPC_ERROR_NONE);
- }
+ }
PickResult result;
result.type = PickResult::PICK_QUEUE;
return result;
-}
-
+}
+
//
// LoadBalancingPolicy::TransientFailurePicker
//
@@ -135,4 +135,4 @@ LoadBalancingPolicy::TransientFailurePicker::Pick(PickArgs /*args*/) {
return result;
}
-} // namespace grpc_core
+} // 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 1cbc074484b..3c53724c6d7 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
@@ -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_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_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_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H
+
+#include <grpc/support/port_platform.h>
+
#include <functional>
#include <iterator>
@@ -31,18 +31,18 @@
#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"
+#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/iomgr/work_serializer.h"
-#include "src/core/lib/transport/connectivity_state.h"
-
-namespace grpc_core {
-
+#include "src/core/lib/transport/connectivity_state.h"
+
+namespace grpc_core {
+
extern DebugOnlyTraceFlag grpc_trace_lb_policy_refcount;
-/// Interface for load balancing policies.
-///
+/// Interface for load balancing policies.
+///
/// The following concepts are used here:
///
/// Channel: An abstraction that manages connections to backend servers
@@ -73,15 +73,15 @@ extern DebugOnlyTraceFlag grpc_trace_lb_policy_refcount;
/// LoadBalacingPolicy API.
///
-/// Note: All methods with a "Locked" suffix must be called from the
+/// 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().
+///
+/// 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.
class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
- public:
+ public:
// Represents backend metrics reported by the backend to the client.
struct BackendMetricData {
/// CPU utilization expressed as a fraction of available CPU resources.
@@ -325,7 +325,7 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
};
/// Args used to instantiate an LB policy.
- struct Args {
+ struct Args {
/// The work_serializer under which all LB policy calls will be run.
std::shared_ptr<WorkSerializer> work_serializer;
/// Channel control helper.
@@ -338,18 +338,18 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
// 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();
-
- // Not copyable nor movable.
- LoadBalancingPolicy(const LoadBalancingPolicy&) = delete;
- LoadBalancingPolicy& operator=(const LoadBalancingPolicy&) = delete;
-
+
+ // 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;
-
+
/// 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.
@@ -359,15 +359,15 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
/// 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;
-
+
grpc_pollset_set* interested_parties() const { return interested_parties_; }
-
+
// Note: This must be invoked while holding the work_serializer.
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.
@@ -375,11 +375,11 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
public:
explicit QueuePicker(RefCountedPtr<LoadBalancingPolicy> parent)
: parent_(std::move(parent)) {}
-
+
~QueuePicker() { parent_.reset(DEBUG_LOCATION, "QueuePicker"); }
-
+
PickResult Pick(PickArgs args) override;
-
+
private:
RefCountedPtr<LoadBalancingPolicy> parent_;
bool exit_idle_called_ = false;
@@ -390,36 +390,36 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
public:
explicit TransientFailurePicker(grpc_error* error) : error_(error) {}
~TransientFailurePicker() override { GRPC_ERROR_UNREF(error_); }
-
+
PickResult Pick(PickArgs args) override;
private:
grpc_error* error_;
};
-
- protected:
+
+ 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();
- }
-
+ }
+
/// Shuts down the policy.
virtual void ShutdownLocked() = 0;
-
- private:
+
+ 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_;
+ /// Owned pointer to interested parties in load balancing decisions.
+ grpc_pollset_set* interested_parties_;
/// Channel control helper.
std::unique_ptr<ChannelControlHelper> channel_control_helper_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H */
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 c8d1b1d7af8..657f6cbeb7e 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
@@ -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/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h"
+
#include <string.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.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_client_stats.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/profiling/timers.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*/) {
- return GRPC_ERROR_NONE;
-}
-
+ return GRPC_ERROR_NONE;
+}
+
static void clr_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
+
+namespace {
-namespace {
-
-struct call_data {
- // Stats object to update.
+struct call_data {
+ // Stats object to update.
grpc_core::RefCountedPtr<grpc_core::GrpcLbClientStats> client_stats;
- // State for intercepting send_initial_metadata.
- grpc_closure on_complete_for_send;
- grpc_closure* original_on_complete_for_send;
+ // State for intercepting send_initial_metadata.
+ grpc_closure on_complete_for_send;
+ grpc_closure* original_on_complete_for_send;
bool send_initial_metadata_succeeded = false;
- // State for intercepting recv_initial_metadata.
- grpc_closure recv_initial_metadata_ready;
- grpc_closure* original_recv_initial_metadata_ready;
+ // State for intercepting recv_initial_metadata.
+ grpc_closure recv_initial_metadata_ready;
+ grpc_closure* original_recv_initial_metadata_ready;
bool recv_initial_metadata_succeeded = false;
-};
-
-} // namespace
-
-static void on_complete_for_send(void* arg, grpc_error* error) {
- call_data* calld = static_cast<call_data*>(arg);
- if (error == GRPC_ERROR_NONE) {
- calld->send_initial_metadata_succeeded = true;
- }
+};
+
+} // namespace
+
+static void on_complete_for_send(void* arg, grpc_error* error) {
+ call_data* calld = static_cast<call_data*>(arg);
+ 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));
-}
-
-static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
- call_data* calld = static_cast<call_data*>(arg);
- if (error == GRPC_ERROR_NONE) {
- calld->recv_initial_metadata_succeeded = true;
- }
+}
+
+static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
+ call_data* calld = static_cast<call_data*>(arg);
+ 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));
-}
-
+}
+
static grpc_error* clr_init_call_elem(grpc_call_element* elem,
const grpc_call_element_args* args) {
- GPR_ASSERT(args->context != nullptr);
+ GPR_ASSERT(args->context != nullptr);
new (elem->call_data) call_data();
- return GRPC_ERROR_NONE;
-}
-
+ return GRPC_ERROR_NONE;
+}
+
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
- // received.
+ 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
+ // received.
calld->client_stats->AddCallFinished(
- !calld->send_initial_metadata_succeeded /* client_failed_to_send */,
+ !calld->send_initial_metadata_succeeded /* client_failed_to_send */,
calld->recv_initial_metadata_succeeded /* known_received */);
- }
+ }
calld->~call_data();
-}
-
+}
+
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);
+ 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.
@@ -109,7 +109,7 @@ static void clr_start_transport_stream_op_batch(
static_cast<const void*>(grpc_core::kGrpcLbClientStatsMetadataKey)) {
break;
}
- }
+ }
if (client_stats_md != nullptr) {
grpc_core::GrpcLbClientStats* client_stats =
const_cast<grpc_core::GrpcLbClientStats*>(
@@ -127,8 +127,8 @@ static void clr_start_transport_stream_op_batch(
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 =
@@ -139,19 +139,19 @@ static void clr_start_transport_stream_op_batch(
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 = {
+ // 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,
- grpc_channel_next_op,
- sizeof(call_data),
+ grpc_channel_next_op,
+ sizeof(call_data),
clr_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
clr_destroy_call_elem,
- 0, // sizeof(channel_data)
+ 0, // sizeof(channel_data)
clr_init_channel_elem,
clr_destroy_channel_elem,
- grpc_channel_next_get_info,
- "client_load_reporting"};
+ grpc_channel_next_get_info,
+ "client_load_reporting"};
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h
index 838e2ef1cae..969b3328650 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h
@@ -1,29 +1,29 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-
-extern const grpc_channel_filter grpc_client_load_reporting_filter;
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+
+extern const grpc_channel_filter grpc_client_load_reporting_filter;
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H \
+ */
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 ccfdb5f215a..32f86707653 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
@@ -1,31 +1,31 @@
-/*
- *
- * 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.
- *
- */
-
-/// Implementation of the gRPC LB policy.
-///
-/// This policy takes as input a list of resolved addresses, which must
-/// include at least one balancer address.
-///
-/// An internal channel (\a lb_channel_) is created for the addresses
-/// from that are balancers. This channel behaves just like a regular
-/// channel that uses pick_first to select from the list of balancer
-/// addresses.
-///
+/*
+ *
+ * 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.
+ *
+ */
+
+/// Implementation of the gRPC LB policy.
+///
+/// This policy takes as input a list of resolved addresses, which must
+/// include at least one balancer address.
+///
+/// An internal channel (\a lb_channel_) is created for the addresses
+/// from that are balancers. This channel behaves just like a regular
+/// 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
@@ -33,37 +33,37 @@
/// 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
+///
+/// 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
-/// resolver.
-///
+/// resolver.
+///
/// 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
+/// 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.
-///
-/// \see https://github.com/grpc/grpc/blob/master/doc/load-balancing.md for the
-/// high level design and details.
-
-// 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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/socket_utils.h"
-
-#include <inttypes.h>
-#include <limits.h>
-#include <string.h>
-
+///
+/// \see https://github.com/grpc/grpc/blob/master/doc/load-balancing.md for the
+/// high level design and details.
+
+// 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 <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/socket_utils.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <string.h>
+
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
@@ -71,63 +71,63 @@
#include "upb/upb.hpp"
-#include <grpc/byte_buffer_reader.h>
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
+#include <grpc/byte_buffer_reader.h>
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/lb_policy/child_policy_handler.h"
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h"
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.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/resolver/fake/fake_resolver.h"
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.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/resolver/fake/fake_resolver.h"
#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/lib/backoff/backoff.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/manual_constructor.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/backoff/backoff.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/channel_stack.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/manual_constructor.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/parse_address.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/surface/channel.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-#define GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS 1
-#define GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER 1.6
-#define GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS 120
-#define GRPC_GRPCLB_RECONNECT_JITTER 0.2
-#define GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS 10000
-
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+#define GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS 1
+#define GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER 1.6
+#define GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS 120
+#define GRPC_GRPCLB_RECONNECT_JITTER 0.2
+#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"
-namespace grpc_core {
-
-TraceFlag grpc_lb_glb_trace(false, "glb");
-
+namespace grpc_core {
+
+TraceFlag grpc_lb_glb_trace(false, "glb");
+
const char kGrpcLbClientStatsMetadataKey[] = "grpclb_client_stats";
const char kGrpcLbLbTokenMetadataKey[] = "lb-token";
const char kGrpcLbAddressAttributeKey[] = "grpclb";
-namespace {
-
+namespace {
+
constexpr char kGrpclb[] = "grpclb";
class GrpcLbConfig : public LoadBalancingPolicy::Config {
@@ -149,42 +149,42 @@ class GrpcLbConfig : public LoadBalancingPolicy::Config {
TString service_name_;
};
-class GrpcLb : public LoadBalancingPolicy {
- public:
+class GrpcLb : public LoadBalancingPolicy {
+ public:
explicit GrpcLb(Args args);
-
+
const char* name() const override { return kGrpclb; }
void UpdateLocked(UpdateArgs args) override;
void ResetBackoffLocked() override;
-
- private:
- /// Contains a call to the LB server and all the data related to the call.
+
+ private:
+ /// Contains a call to the LB server and all the data related to the call.
class BalancerCallState : public InternallyRefCounted<BalancerCallState> {
- public:
- explicit BalancerCallState(
- RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy);
+ public:
+ explicit BalancerCallState(
+ RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy);
~BalancerCallState();
-
- // It's the caller's responsibility to ensure that Orphan() is called from
- // inside the combiner.
- void Orphan() override;
-
- void StartQuery();
-
+
+ // It's the caller's responsibility to ensure that Orphan() is called from
+ // inside the combiner.
+ void Orphan() override;
+
+ void StartQuery();
+
GrpcLbClientStats* client_stats() const { return client_stats_.get(); }
- bool seen_initial_response() const { return seen_initial_response_; }
+ bool seen_initial_response() const { return seen_initial_response_; }
bool seen_serverlist() const { return seen_serverlist_; }
-
- private:
- GrpcLb* grpclb_policy() const {
- return static_cast<GrpcLb*>(grpclb_policy_.get());
- }
-
- void ScheduleNextClientLoadReportLocked();
- void SendClientLoadReportLocked();
-
+
+ private:
+ GrpcLb* grpclb_policy() const {
+ return static_cast<GrpcLb*>(grpclb_policy_.get());
+ }
+
+ 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);
@@ -196,45 +196,45 @@ class GrpcLb : public LoadBalancingPolicy {
void OnInitialRequestSentLocked();
void OnBalancerMessageReceivedLocked();
void OnBalancerStatusReceivedLocked(grpc_error* error);
-
- // The owning LB policy.
- RefCountedPtr<LoadBalancingPolicy> grpclb_policy_;
-
- // The streaming call to the LB server. Always non-NULL.
- grpc_call* lb_call_ = nullptr;
-
- // recv_initial_metadata
- grpc_metadata_array lb_initial_metadata_recv_;
-
- // send_message
- grpc_byte_buffer* send_message_payload_ = nullptr;
- grpc_closure lb_on_initial_request_sent_;
-
- // recv_message
- grpc_byte_buffer* recv_message_payload_ = nullptr;
- grpc_closure lb_on_balancer_message_received_;
- bool seen_initial_response_ = false;
+
+ // The owning LB policy.
+ RefCountedPtr<LoadBalancingPolicy> grpclb_policy_;
+
+ // The streaming call to the LB server. Always non-NULL.
+ grpc_call* lb_call_ = nullptr;
+
+ // recv_initial_metadata
+ grpc_metadata_array lb_initial_metadata_recv_;
+
+ // send_message
+ grpc_byte_buffer* send_message_payload_ = nullptr;
+ grpc_closure lb_on_initial_request_sent_;
+
+ // recv_message
+ grpc_byte_buffer* recv_message_payload_ = nullptr;
+ grpc_closure lb_on_balancer_message_received_;
+ bool seen_initial_response_ = false;
bool seen_serverlist_ = false;
-
- // recv_trailing_metadata
- grpc_closure lb_on_balancer_status_received_;
- grpc_metadata_array lb_trailing_metadata_recv_;
- grpc_status_code lb_call_status_;
- grpc_slice lb_call_status_details_;
-
- // The stats for client-side load reporting associated with this LB call.
- // Created after the first serverlist is received.
+
+ // recv_trailing_metadata
+ grpc_closure lb_on_balancer_status_received_;
+ grpc_metadata_array lb_trailing_metadata_recv_;
+ grpc_status_code lb_call_status_;
+ grpc_slice lb_call_status_details_;
+
+ // The stats for client-side load reporting associated with this LB call.
+ // Created after the first serverlist is received.
RefCountedPtr<GrpcLbClientStats> client_stats_;
- grpc_millis client_stats_report_interval_ = 0;
- grpc_timer client_load_report_timer_;
- bool client_load_report_timer_callback_pending_ = false;
- bool last_client_load_report_counters_were_zero_ = false;
- bool client_load_report_is_due_ = false;
- // The closure used for either the load report timer or the callback for
- // completion of sending the load report.
- grpc_closure client_load_report_closure_;
- };
-
+ grpc_millis client_stats_report_interval_ = 0;
+ grpc_timer client_load_report_timer_;
+ bool client_load_report_timer_callback_pending_ = false;
+ bool last_client_load_report_counters_were_zero_ = false;
+ bool client_load_report_is_due_ = false;
+ // The closure used for either the load report timer or the callback for
+ // completion of sending the load report.
+ grpc_closure client_load_report_closure_;
+ };
+
class TokenAndClientStatsAttribute
: public ServerAddress::AttributeInterface {
public:
@@ -381,10 +381,10 @@ class GrpcLb : public LoadBalancingPolicy {
RefCountedPtr<GrpcLb> parent_;
};
- ~GrpcLb();
-
- void ShutdownLocked() override;
-
+ ~GrpcLb();
+
+ void ShutdownLocked() override;
+
// Helper functions used in UpdateLocked().
void ProcessAddressesAndChannelArgsLocked(const ServerAddressList& addresses,
const grpc_channel_args& args);
@@ -392,87 +392,87 @@ class GrpcLb : public LoadBalancingPolicy {
const ServerAddressList& addresses);
void CancelBalancerChannelConnectivityWatchLocked();
-
+
// 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.
- void StartBalancerCallLocked();
- void StartBalancerCallRetryTimerLocked();
+ void StartBalancerCallLocked();
+ void StartBalancerCallRetryTimerLocked();
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(
const grpc_channel_args* args);
void CreateOrUpdateChildPolicyLocked();
-
- // Who the client is trying to communicate with.
- const char* server_name_ = nullptr;
+
+ // Who the client is trying to communicate with.
+ const char* server_name_ = nullptr;
// Configurations for the policy.
RefCountedPtr<GrpcLbConfig> config_;
-
- // Current channel args from the resolver.
- grpc_channel_args* args_ = nullptr;
-
- // Internal state.
- bool shutting_down_ = false;
-
- // The channel for communicating with the LB server.
- grpc_channel* lb_channel_ = nullptr;
+
+ // Current channel args from the resolver.
+ grpc_channel_args* args_ = nullptr;
+
+ // Internal state.
+ bool shutting_down_ = false;
+
+ // The channel for communicating with the LB server.
+ grpc_channel* lb_channel_ = nullptr;
StateWatcher* watcher_ = nullptr;
- // Response generator to inject address updates into lb_channel_.
- RefCountedPtr<FakeResolverResponseGenerator> response_generator_;
+ // Response generator to inject address updates into lb_channel_.
+ RefCountedPtr<FakeResolverResponseGenerator> response_generator_;
// Parent channelz node.
RefCountedPtr<channelz::ChannelNode> parent_channelz_node_;
-
- // The data associated with the current LB call. It holds a ref to this LB
- // policy. It's initialized every time we query for backends. It's reset to
- // NULL whenever the current LB call is no longer needed (e.g., the LB policy
- // is shutting down, or the LB call has ended). A non-NULL lb_calld_ always
- // contains a non-NULL lb_call_.
- OrphanablePtr<BalancerCallState> lb_calld_;
- // Timeout in milliseconds for the LB call. 0 means no deadline.
- int lb_call_timeout_ms_ = 0;
- // Balancer call retry state.
- BackOff lb_call_backoff_;
- bool retry_timer_callback_pending_ = false;
- grpc_timer lb_call_retry_timer_;
- grpc_closure lb_on_call_retry_;
-
- // The deserialized response from the balancer. May be nullptr until one
- // such response has arrived.
+
+ // The data associated with the current LB call. It holds a ref to this LB
+ // policy. It's initialized every time we query for backends. It's reset to
+ // NULL whenever the current LB call is no longer needed (e.g., the LB policy
+ // is shutting down, or the LB call has ended). A non-NULL lb_calld_ always
+ // contains a non-NULL lb_call_.
+ OrphanablePtr<BalancerCallState> lb_calld_;
+ // Timeout in milliseconds for the LB call. 0 means no deadline.
+ int lb_call_timeout_ms_ = 0;
+ // Balancer call retry state.
+ BackOff lb_call_backoff_;
+ bool retry_timer_callback_pending_ = false;
+ grpc_timer lb_call_retry_timer_;
+ grpc_closure lb_on_call_retry_;
+
+ // The deserialized response from the balancer. May be nullptr until one
+ // such response has arrived.
RefCountedPtr<Serverlist> serverlist_;
-
+
// Whether we're in fallback mode.
bool fallback_mode_ = false;
- // The backend addresses from the resolver.
+ // 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;
- grpc_timer lb_fallback_timer_;
- grpc_closure lb_on_fallback_;
-
+ 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;
-};
-
-//
+};
+
+//
// GrpcLb::Serverlist
-//
-
+//
+
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));
@@ -492,8 +492,8 @@ void ParseServer(const GrpcLbServer& server, grpc_resolved_address* addr) {
addr6->sin6_family = GRPC_AF_INET6;
memcpy(&addr6->sin6_addr, server.ip_addr, server.ip_size);
addr6->sin6_port = netorder_port;
- }
-}
+ }
+}
TString GrpcLb::Serverlist::AsText() const {
std::vector<TString> entries;
@@ -516,25 +516,25 @@ TString GrpcLb::Serverlist::AsText() const {
bool IsServerValid(const GrpcLbServer& server, size_t idx, bool log) {
if (server.drop) return false;
if (GPR_UNLIKELY(server.port >> 16 != 0)) {
- if (log) {
- gpr_log(GPR_ERROR,
- "Invalid port '%d' at index %lu of serverlist. Ignoring.",
+ if (log) {
+ gpr_log(GPR_ERROR,
+ "Invalid port '%d' at index %lu of serverlist. Ignoring.",
server.port, (unsigned long)idx);
- }
- return false;
- }
+ }
+ return false;
+ }
if (GPR_UNLIKELY(server.ip_size != 4 && server.ip_size != 16)) {
- if (log) {
- gpr_log(GPR_ERROR,
- "Expected IP to be 4 or 16 bytes, got %d at index %lu of "
- "serverlist. Ignoring",
+ if (log) {
+ gpr_log(GPR_ERROR,
+ "Expected IP to be 4 or 16 bytes, got %d at index %lu of "
+ "serverlist. Ignoring",
server.ip_size, (unsigned long)idx);
- }
- return false;
- }
- return true;
-}
-
+ }
+ return false;
+ }
+ return true;
+}
+
// Returns addresses extracted from the serverlist.
ServerAddressList GrpcLb::Serverlist::GetServerAddressList(
GrpcLbClientStats* client_stats) const {
@@ -545,18 +545,18 @@ ServerAddressList GrpcLb::Serverlist::GetServerAddressList(
const GrpcLbServer& server = serverlist_[i];
if (!IsServerValid(server, i, false)) continue;
// Address processing.
- grpc_resolved_address addr;
- ParseServer(server, &addr);
+ grpc_resolved_address addr;
+ ParseServer(server, &addr);
// LB token processing.
const size_t lb_token_length = strnlen(
server.load_balance_token, GPR_ARRAY_SIZE(server.load_balance_token));
TString lb_token(server.load_balance_token, lb_token_length);
if (lb_token.empty()) {
- gpr_log(GPR_INFO,
- "Missing LB token for backend address '%s'. The empty token will "
- "be used instead",
+ gpr_log(GPR_INFO,
+ "Missing LB token for backend address '%s'. The empty token will "
+ "be used instead",
grpc_sockaddr_to_uri(&addr).c_str());
- }
+ }
// Attach attribute to address containing LB token and stats object.
std::map<const char*, std::unique_ptr<ServerAddress::AttributeInterface>>
attributes;
@@ -565,10 +565,10 @@ ServerAddressList GrpcLb::Serverlist::GetServerAddressList(
stats);
// Add address.
addresses.emplace_back(addr, /*args=*/nullptr, std::move(attributes));
- }
+ }
return addresses;
-}
-
+}
+
bool GrpcLb::Serverlist::ContainsAllDropEntries() const {
if (serverlist_.empty()) return false;
for (const GrpcLbServer& server : serverlist_) {
@@ -584,7 +584,7 @@ const char* GrpcLb::Serverlist::ShouldDrop() {
return server.drop ? server.load_balance_token : nullptr;
}
-//
+//
// GrpcLb::Picker
//
@@ -733,20 +733,20 @@ void GrpcLb::Helper::AddTraceEvent(TraceSeverity severity,
}
//
-// GrpcLb::BalancerCallState
-//
-
-GrpcLb::BalancerCallState::BalancerCallState(
- RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy)
+// GrpcLb::BalancerCallState
+//
+
+GrpcLb::BalancerCallState::BalancerCallState(
+ RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy)
: InternallyRefCounted<BalancerCallState>(&grpc_lb_glb_trace),
- grpclb_policy_(std::move(parent_grpclb_policy)) {
- GPR_ASSERT(grpclb_policy_ != nullptr);
- GPR_ASSERT(!grpclb_policy()->shutting_down_);
- // Init the LB call. Note that the LB call will progress every time there's
- // activity in grpclb_policy_->interested_parties(), which is comprised of
- // the polling entities from client_channel.
- GPR_ASSERT(grpclb_policy()->server_name_ != nullptr);
- GPR_ASSERT(grpclb_policy()->server_name_[0] != '\0');
+ grpclb_policy_(std::move(parent_grpclb_policy)) {
+ GPR_ASSERT(grpclb_policy_ != nullptr);
+ GPR_ASSERT(!grpclb_policy()->shutting_down_);
+ // Init the LB call. Note that the LB call will progress every time there's
+ // activity in grpclb_policy_->interested_parties(), which is comprised of
+ // the polling entities from client_channel.
+ GPR_ASSERT(grpclb_policy()->server_name_ != nullptr);
+ GPR_ASSERT(grpclb_policy()->server_name_[0] != '\0');
// Closure Initialization
GRPC_CLOSURE_INIT(&lb_on_initial_request_sent_, OnInitialRequestSent, this,
grpc_schedule_on_exec_ctx);
@@ -756,138 +756,138 @@ GrpcLb::BalancerCallState::BalancerCallState(
this, grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&client_load_report_closure_, MaybeSendClientLoadReport,
this, grpc_schedule_on_exec_ctx);
- const grpc_millis deadline =
- grpclb_policy()->lb_call_timeout_ms_ == 0
- ? GRPC_MILLIS_INF_FUTURE
- : ExecCtx::Get()->Now() + grpclb_policy()->lb_call_timeout_ms_;
- lb_call_ = grpc_channel_create_pollset_set_call(
- grpclb_policy()->lb_channel_, nullptr, GRPC_PROPAGATE_DEFAULTS,
- grpclb_policy_->interested_parties(),
- GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD,
- nullptr, deadline, nullptr);
- // Init the LB call request payload.
+ const grpc_millis deadline =
+ grpclb_policy()->lb_call_timeout_ms_ == 0
+ ? GRPC_MILLIS_INF_FUTURE
+ : ExecCtx::Get()->Now() + grpclb_policy()->lb_call_timeout_ms_;
+ lb_call_ = grpc_channel_create_pollset_set_call(
+ grpclb_policy()->lb_channel_, nullptr, GRPC_PROPAGATE_DEFAULTS,
+ grpclb_policy_->interested_parties(),
+ GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD,
+ nullptr, deadline, nullptr);
+ // Init the LB call request payload.
upb::Arena arena;
grpc_slice request_payload_slice = GrpcLbRequestCreate(
grpclb_policy()->config_->service_name().empty()
? grpclb_policy()->server_name_
: grpclb_policy()->config_->service_name().c_str(),
arena.ptr());
- send_message_payload_ =
- grpc_raw_byte_buffer_create(&request_payload_slice, 1);
- grpc_slice_unref_internal(request_payload_slice);
- // Init other data associated with the LB call.
- grpc_metadata_array_init(&lb_initial_metadata_recv_);
- grpc_metadata_array_init(&lb_trailing_metadata_recv_);
-}
-
-GrpcLb::BalancerCallState::~BalancerCallState() {
- GPR_ASSERT(lb_call_ != nullptr);
- grpc_call_unref(lb_call_);
- grpc_metadata_array_destroy(&lb_initial_metadata_recv_);
- grpc_metadata_array_destroy(&lb_trailing_metadata_recv_);
- grpc_byte_buffer_destroy(send_message_payload_);
- grpc_byte_buffer_destroy(recv_message_payload_);
- grpc_slice_unref_internal(lb_call_status_details_);
-}
-
-void GrpcLb::BalancerCallState::Orphan() {
- GPR_ASSERT(lb_call_ != nullptr);
- // If we are here because grpclb_policy wants to cancel the call,
- // lb_on_balancer_status_received_ will complete the cancellation and clean
- // up. Otherwise, we are here because grpclb_policy has to orphan a failed
- // call, then the following cancellation will be a no-op.
+ send_message_payload_ =
+ grpc_raw_byte_buffer_create(&request_payload_slice, 1);
+ grpc_slice_unref_internal(request_payload_slice);
+ // Init other data associated with the LB call.
+ grpc_metadata_array_init(&lb_initial_metadata_recv_);
+ grpc_metadata_array_init(&lb_trailing_metadata_recv_);
+}
+
+GrpcLb::BalancerCallState::~BalancerCallState() {
+ GPR_ASSERT(lb_call_ != nullptr);
+ grpc_call_unref(lb_call_);
+ grpc_metadata_array_destroy(&lb_initial_metadata_recv_);
+ grpc_metadata_array_destroy(&lb_trailing_metadata_recv_);
+ grpc_byte_buffer_destroy(send_message_payload_);
+ grpc_byte_buffer_destroy(recv_message_payload_);
+ grpc_slice_unref_internal(lb_call_status_details_);
+}
+
+void GrpcLb::BalancerCallState::Orphan() {
+ GPR_ASSERT(lb_call_ != nullptr);
+ // If we are here because grpclb_policy wants to cancel the call,
+ // lb_on_balancer_status_received_ will complete the cancellation and clean
+ // up. Otherwise, we are here because grpclb_policy has to orphan a failed
+ // call, then the following cancellation will be a no-op.
grpc_call_cancel_internal(lb_call_);
- if (client_load_report_timer_callback_pending_) {
- grpc_timer_cancel(&client_load_report_timer_);
- }
- // Note that the initial ref is hold by lb_on_balancer_status_received_
- // instead of the caller of this function. So the corresponding unref happens
- // in lb_on_balancer_status_received_ instead of here.
-}
-
-void GrpcLb::BalancerCallState::StartQuery() {
- GPR_ASSERT(lb_call_ != nullptr);
+ if (client_load_report_timer_callback_pending_) {
+ grpc_timer_cancel(&client_load_report_timer_);
+ }
+ // Note that the initial ref is hold by lb_on_balancer_status_received_
+ // instead of the caller of this function. So the corresponding unref happens
+ // in lb_on_balancer_status_received_ instead of here.
+}
+
+void GrpcLb::BalancerCallState::StartQuery() {
+ GPR_ASSERT(lb_call_ != nullptr);
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_);
- }
- // Create the ops.
- grpc_call_error call_error;
- grpc_op ops[3];
- memset(ops, 0, sizeof(ops));
- // Op: send initial metadata.
- grpc_op* op = ops;
- op->op = GRPC_OP_SEND_INITIAL_METADATA;
- op->data.send_initial_metadata.count = 0;
+ grpclb_policy_.get(), this, lb_call_);
+ }
+ // Create the ops.
+ grpc_call_error call_error;
+ grpc_op ops[3];
+ memset(ops, 0, sizeof(ops));
+ // Op: send initial metadata.
+ 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->reserved = nullptr;
- op++;
- // Op: send request message.
- GPR_ASSERT(send_message_payload_ != nullptr);
- op->op = GRPC_OP_SEND_MESSAGE;
- op->data.send_message.send_message = send_message_payload_;
- op->flags = 0;
- op->reserved = nullptr;
- op++;
- // TODO(roth): We currently track this ref manually. Once the
- // ClosureRef API is ready, we should pass the RefCountedPtr<> along
- // with the callback.
- auto self = Ref(DEBUG_LOCATION, "on_initial_request_sent");
- self.release();
- call_error = grpc_call_start_batch_and_execute(
- lb_call_, ops, (size_t)(op - ops), &lb_on_initial_request_sent_);
- GPR_ASSERT(GRPC_CALL_OK == call_error);
- // Op: recv initial metadata.
- op = ops;
- op->op = GRPC_OP_RECV_INITIAL_METADATA;
- op->data.recv_initial_metadata.recv_initial_metadata =
- &lb_initial_metadata_recv_;
- op->flags = 0;
- op->reserved = nullptr;
- op++;
- // Op: recv response.
- op->op = GRPC_OP_RECV_MESSAGE;
- op->data.recv_message.recv_message = &recv_message_payload_;
- op->flags = 0;
- op->reserved = nullptr;
- op++;
- // TODO(roth): We currently track this ref manually. Once the
- // ClosureRef API is ready, we should pass the RefCountedPtr<> along
- // with the callback.
- self = Ref(DEBUG_LOCATION, "on_message_received");
- self.release();
- call_error = grpc_call_start_batch_and_execute(
- lb_call_, ops, (size_t)(op - ops), &lb_on_balancer_message_received_);
- GPR_ASSERT(GRPC_CALL_OK == call_error);
- // Op: recv server status.
- op = ops;
- op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
- op->data.recv_status_on_client.trailing_metadata =
- &lb_trailing_metadata_recv_;
- op->data.recv_status_on_client.status = &lb_call_status_;
- op->data.recv_status_on_client.status_details = &lb_call_status_details_;
- op->flags = 0;
- op->reserved = nullptr;
- op++;
- // This callback signals the end of the LB call, so it relies on the initial
- // ref instead of a new ref. When it's invoked, it's the initial ref that is
- // unreffed.
- 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);
+ op->reserved = nullptr;
+ op++;
+ // Op: send request message.
+ GPR_ASSERT(send_message_payload_ != nullptr);
+ op->op = GRPC_OP_SEND_MESSAGE;
+ op->data.send_message.send_message = send_message_payload_;
+ op->flags = 0;
+ op->reserved = nullptr;
+ op++;
+ // TODO(roth): We currently track this ref manually. Once the
+ // ClosureRef API is ready, we should pass the RefCountedPtr<> along
+ // with the callback.
+ auto self = Ref(DEBUG_LOCATION, "on_initial_request_sent");
+ self.release();
+ call_error = grpc_call_start_batch_and_execute(
+ lb_call_, ops, (size_t)(op - ops), &lb_on_initial_request_sent_);
+ GPR_ASSERT(GRPC_CALL_OK == call_error);
+ // Op: recv initial metadata.
+ op = ops;
+ op->op = GRPC_OP_RECV_INITIAL_METADATA;
+ op->data.recv_initial_metadata.recv_initial_metadata =
+ &lb_initial_metadata_recv_;
+ op->flags = 0;
+ op->reserved = nullptr;
+ op++;
+ // Op: recv response.
+ op->op = GRPC_OP_RECV_MESSAGE;
+ op->data.recv_message.recv_message = &recv_message_payload_;
+ op->flags = 0;
+ op->reserved = nullptr;
+ op++;
+ // TODO(roth): We currently track this ref manually. Once the
+ // ClosureRef API is ready, we should pass the RefCountedPtr<> along
+ // with the callback.
+ self = Ref(DEBUG_LOCATION, "on_message_received");
+ self.release();
+ call_error = grpc_call_start_batch_and_execute(
+ lb_call_, ops, (size_t)(op - ops), &lb_on_balancer_message_received_);
+ GPR_ASSERT(GRPC_CALL_OK == call_error);
+ // Op: recv server status.
+ op = ops;
+ op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
+ op->data.recv_status_on_client.trailing_metadata =
+ &lb_trailing_metadata_recv_;
+ op->data.recv_status_on_client.status = &lb_call_status_;
+ op->data.recv_status_on_client.status_details = &lb_call_status_details_;
+ op->flags = 0;
+ op->reserved = nullptr;
+ op++;
+ // This callback signals the end of the LB call, so it relies on the initial
+ // ref instead of a new ref. When it's invoked, it's the initial ref that is
+ // unreffed.
+ 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_;
+
+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_timer_init(&client_load_report_timer_, next_client_load_report_time,
- &client_load_report_closure_);
- client_load_report_timer_callback_pending_ = true;
-}
-
+ 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);
@@ -897,27 +897,27 @@ void GrpcLb::BalancerCallState::MaybeSendClientLoadReport(void* arg,
DEBUG_LOCATION);
}
-void GrpcLb::BalancerCallState::MaybeSendClientLoadReportLocked(
+void GrpcLb::BalancerCallState::MaybeSendClientLoadReportLocked(
grpc_error* error) {
client_load_report_timer_callback_pending_ = false;
if (error != GRPC_ERROR_NONE || this != grpclb_policy()->lb_calld_.get()) {
Unref(DEBUG_LOCATION, "client_load_report");
GRPC_ERROR_UNREF(error);
- return;
- }
- // If we've already sent the initial request, then we can go ahead and send
- // the load report. Otherwise, we need to wait until the initial request has
- // been sent to send this (see OnInitialRequestSentLocked()).
+ return;
+ }
+ // If we've already sent the initial request, then we can go ahead and send
+ // the load report. Otherwise, we need to wait until the initial request has
+ // been sent to send this (see OnInitialRequestSentLocked()).
if (send_message_payload_ == nullptr) {
SendClientLoadReportLocked();
- } else {
+ } else {
client_load_report_is_due_ = true;
- }
-}
-
-void GrpcLb::BalancerCallState::SendClientLoadReportLocked() {
- // Construct message payload.
- GPR_ASSERT(send_message_payload_ == nullptr);
+ }
+}
+
+void GrpcLb::BalancerCallState::SendClientLoadReportLocked() {
+ // Construct message payload.
+ GPR_ASSERT(send_message_payload_ == nullptr);
// Get snapshot of stats.
int64_t num_calls_started;
int64_t num_calls_finished;
@@ -927,46 +927,46 @@ void GrpcLb::BalancerCallState::SendClientLoadReportLocked() {
client_stats_->Get(&num_calls_started, &num_calls_finished,
&num_calls_finished_with_client_failed_to_send,
&num_calls_finished_known_received, &drop_token_counts);
- // Skip client load report if the counters were all zero in the last
- // report and they are still zero in this one.
+ // Skip client load report if the counters were all zero in the last
+ // report and they are still zero in this one.
if (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 == nullptr || drop_token_counts->size() == 0)) {
- if (last_client_load_report_counters_were_zero_) {
- ScheduleNextClientLoadReportLocked();
- return;
- }
- last_client_load_report_counters_were_zero_ = true;
- } else {
- last_client_load_report_counters_were_zero_ = false;
- }
+ if (last_client_load_report_counters_were_zero_) {
+ ScheduleNextClientLoadReportLocked();
+ return;
+ }
+ last_client_load_report_counters_were_zero_ = true;
+ } else {
+ last_client_load_report_counters_were_zero_ = false;
+ }
// Populate load report.
upb::Arena arena;
grpc_slice request_payload_slice = GrpcLbLoadReportRequestCreate(
num_calls_started, num_calls_finished,
num_calls_finished_with_client_failed_to_send,
num_calls_finished_known_received, drop_token_counts.get(), arena.ptr());
- send_message_payload_ =
- grpc_raw_byte_buffer_create(&request_payload_slice, 1);
- grpc_slice_unref_internal(request_payload_slice);
- // Send the report.
- grpc_op op;
- memset(&op, 0, sizeof(op));
- op.op = GRPC_OP_SEND_MESSAGE;
- op.data.send_message.send_message = send_message_payload_;
+ send_message_payload_ =
+ grpc_raw_byte_buffer_create(&request_payload_slice, 1);
+ grpc_slice_unref_internal(request_payload_slice);
+ // Send the report.
+ grpc_op op;
+ 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_call_error call_error = grpc_call_start_batch_and_execute(
- lb_call_, &op, 1, &client_load_report_closure_);
+ 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)) {
gpr_log(GPR_ERROR,
"[grpclb %p] lb_calld=%p call_error=%d sending client load report",
grpclb_policy_.get(), this, call_error);
- GPR_ASSERT(GRPC_CALL_OK == call_error);
- }
-}
-
+ GPR_ASSERT(GRPC_CALL_OK == call_error);
+ }
+}
+
void GrpcLb::BalancerCallState::ClientLoadReportDone(void* arg,
grpc_error* error) {
BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
@@ -982,14 +982,14 @@ void GrpcLb::BalancerCallState::ClientLoadReportDoneLocked(grpc_error* error) {
if (error != GRPC_ERROR_NONE || this != grpclb_policy()->lb_calld_.get()) {
Unref(DEBUG_LOCATION, "client_load_report");
GRPC_ERROR_UNREF(error);
- return;
- }
+ return;
+ }
ScheduleNextClientLoadReportLocked();
-}
-
+}
+
void GrpcLb::BalancerCallState::OnInitialRequestSent(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->OnInitialRequestSentLocked(); }, DEBUG_LOCATION);
}
@@ -997,15 +997,15 @@ void GrpcLb::BalancerCallState::OnInitialRequestSent(void* arg,
void GrpcLb::BalancerCallState::OnInitialRequestSentLocked() {
grpc_byte_buffer_destroy(send_message_payload_);
send_message_payload_ = nullptr;
- // If we attempted to send a client load report before the initial request was
- // sent (and this lb_calld is still in use), send the load report now.
+ // If we attempted to send a client load report before the initial request was
+ // sent (and this lb_calld is still in use), send the load report now.
if (client_load_report_is_due_ && this == grpclb_policy()->lb_calld_.get()) {
SendClientLoadReportLocked();
client_load_report_is_due_ = false;
- }
+ }
Unref(DEBUG_LOCATION, "on_initial_request_sent");
-}
-
+}
+
void GrpcLb::BalancerCallState::OnBalancerMessageReceived(
void* arg, grpc_error* /*error*/) {
BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
@@ -1019,12 +1019,12 @@ void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() {
if (this != grpclb_policy()->lb_calld_.get() ||
recv_message_payload_ == nullptr) {
Unref(DEBUG_LOCATION, "on_message_received");
- return;
- }
- grpc_byte_buffer_reader bbr;
+ return;
+ }
+ grpc_byte_buffer_reader bbr;
grpc_byte_buffer_reader_init(&bbr, recv_message_payload_);
- grpc_slice response_slice = grpc_byte_buffer_reader_readall(&bbr);
- grpc_byte_buffer_reader_destroy(&bbr);
+ grpc_slice response_slice = grpc_byte_buffer_reader_readall(&bbr);
+ grpc_byte_buffer_reader_destroy(&bbr);
grpc_byte_buffer_destroy(recv_message_payload_);
recv_message_payload_ = nullptr;
GrpcLbResponse response;
@@ -1033,7 +1033,7 @@ void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() {
(response.type == response.INITIAL && seen_initial_response_)) {
char* response_slice_str =
grpc_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX);
- gpr_log(GPR_ERROR,
+ gpr_log(GPR_ERROR,
"[grpclb %p] lb_calld=%p: Invalid LB response received: '%s'. "
"Ignoring.",
grpclb_policy(), this, response_slice_str);
@@ -1150,25 +1150,25 @@ void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() {
break;
}
}
- }
- grpc_slice_unref_internal(response_slice);
+ }
+ grpc_slice_unref_internal(response_slice);
if (!grpclb_policy()->shutting_down_) {
- // Keep listening for serverlist updates.
- grpc_op op;
- memset(&op, 0, sizeof(op));
- op.op = GRPC_OP_RECV_MESSAGE;
+ // Keep listening for serverlist updates.
+ grpc_op op;
+ memset(&op, 0, sizeof(op));
+ op.op = GRPC_OP_RECV_MESSAGE;
op.data.recv_message.recv_message = &recv_message_payload_;
- op.flags = 0;
- op.reserved = nullptr;
- // Reuse the "OnBalancerMessageReceivedLocked" ref taken in StartQuery().
- const grpc_call_error call_error = grpc_call_start_batch_and_execute(
+ op.flags = 0;
+ op.reserved = nullptr;
+ // Reuse the "OnBalancerMessageReceivedLocked" ref taken in StartQuery().
+ const grpc_call_error call_error = grpc_call_start_batch_and_execute(
lb_call_, &op, 1, &lb_on_balancer_message_received_);
- GPR_ASSERT(GRPC_CALL_OK == call_error);
- } else {
+ GPR_ASSERT(GRPC_CALL_OK == call_error);
+ } else {
Unref(DEBUG_LOCATION, "on_message_received+grpclb_shutdown");
- }
-}
-
+ }
+}
+
void GrpcLb::BalancerCallState::OnBalancerStatusReceived(void* arg,
grpc_error* error) {
BalancerCallState* lb_calld = static_cast<BalancerCallState*>(arg);
@@ -1178,22 +1178,22 @@ void GrpcLb::BalancerCallState::OnBalancerStatusReceived(void* arg,
DEBUG_LOCATION);
}
-void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked(
+void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked(
grpc_error* error) {
GPR_ASSERT(lb_call_ != nullptr);
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,
+ gpr_log(GPR_INFO,
"[grpclb %p] lb_calld=%p: Status from LB server received. "
"Status = %d, details = '%s', (lb_call: %p), error '%s'",
grpclb_policy(), this, lb_call_status_, status_details, lb_call_,
grpc_error_string(error));
- gpr_free(status_details);
- }
+ gpr_free(status_details);
+ }
GRPC_ERROR_UNREF(error);
- // If this lb_calld is still in use, this call ended because of a failure so
- // we want to retry connecting. Otherwise, we have deliberately ended this
- // call and no further action is required.
+ // If this lb_calld is still in use, this call ended because of a failure so
+ // 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
@@ -1217,75 +1217,75 @@ void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked(
GPR_ASSERT(!grpclb_policy()->shutting_down_);
grpclb_policy()->channel_control_helper()->RequestReresolution();
if (seen_initial_response_) {
- // If we lose connection to the LB server, reset the backoff and restart
- // the LB call immediately.
+ // If we lose connection to the LB server, reset the backoff and restart
+ // the LB call immediately.
grpclb_policy()->lb_call_backoff_.Reset();
grpclb_policy()->StartBalancerCallLocked();
- } else {
- // If this LB call fails establishing any connection to the LB server,
- // retry later.
+ } else {
+ // If this LB call fails establishing any connection to the LB server,
+ // retry later.
grpclb_policy()->StartBalancerCallRetryTimerLocked();
- }
- }
+ }
+ }
Unref(DEBUG_LOCATION, "lb_call_ended");
-}
-
-//
-// helper code for creating balancer channel
-//
-
+}
+
+//
+// helper code for creating balancer channel
+//
+
ServerAddressList ExtractBalancerAddresses(const grpc_channel_args& args) {
const ServerAddressList* addresses =
FindGrpclbBalancerAddressesInChannelArgs(args);
if (addresses != nullptr) return *addresses;
return ServerAddressList();
-}
-
-/* Returns the channel args for the LB channel, used to create a bidirectional
- * stream for the reception of load balancing updates.
- *
- * Inputs:
- * - \a addresses: corresponding to the balancers.
- * - \a response_generator: in order to propagate updates from the resolver
- * above the grpclb policy.
- * - \a args: other args inherited from the grpclb policy. */
-grpc_channel_args* BuildBalancerChannelArgs(
+}
+
+/* Returns the channel args for the LB channel, used to create a bidirectional
+ * stream for the reception of load balancing updates.
+ *
+ * Inputs:
+ * - \a addresses: corresponding to the balancers.
+ * - \a response_generator: in order to propagate updates from the resolver
+ * above the grpclb policy.
+ * - \a args: other args inherited from the grpclb policy. */
+grpc_channel_args* BuildBalancerChannelArgs(
const ServerAddressList& addresses,
- FakeResolverResponseGenerator* response_generator,
- const grpc_channel_args* args) {
- // Channel args to remove.
- static const char* args_to_remove[] = {
- // LB policy name, since we want to use the default (pick_first) in
- // the LB channel.
- GRPC_ARG_LB_POLICY_NAME,
+ FakeResolverResponseGenerator* response_generator,
+ const grpc_channel_args* args) {
+ // Channel args to remove.
+ static const char* args_to_remove[] = {
+ // LB policy name, since we want to use the default (pick_first) in
+ // the LB channel.
+ GRPC_ARG_LB_POLICY_NAME,
// Strip out the service config, since we don't want the LB policy
// config specified for the parent channel to affect the LB channel.
GRPC_ARG_SERVICE_CONFIG,
- // The channel arg for the server URI, since that will be different for
- // the LB channel than for the parent channel. The client channel
- // factory will re-add this arg with the right value.
- GRPC_ARG_SERVER_URI,
- // The fake resolver response generator, because we are replacing it
- // with the one from the grpclb policy, used to propagate updates to
- // the LB channel.
- GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
- // The LB channel should use the authority indicated by the target
+ // The channel arg for the server URI, since that will be different for
+ // the LB channel than for the parent channel. The client channel
+ // factory will re-add this arg with the right value.
+ GRPC_ARG_SERVER_URI,
+ // The fake resolver response generator, because we are replacing it
+ // with the one from the grpclb policy, used to propagate updates to
+ // 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),
- // 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,
+ // 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,
- };
- // Channel args to add.
+ };
+ // Channel args to add.
y_absl::InlinedVector<grpc_arg, 3> args_to_add = {
// The fake resolver response generator, which we use to inject
// address updates into the LB channel.
- grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
+ grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
response_generator),
// A channel arg indicating the target is a grpclb load balancer.
grpc_channel_arg_integer_create(
@@ -1294,97 +1294,97 @@ grpc_channel_args* BuildBalancerChannelArgs(
grpc_channel_arg_integer_create(
const_cast<char*>(GRPC_ARG_CHANNELZ_IS_INTERNAL_CHANNEL), 1),
};
- // Construct channel args.
- grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(
+ // 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());
- // Make any necessary modifications for security.
+ // Make any necessary modifications for security.
return ModifyGrpclbBalancerChannelArgs(addresses, new_args);
-}
-
-//
-// ctor and dtor
-//
-
+}
+
+//
+// ctor and dtor
+//
+
GrpcLb::GrpcLb(Args args)
: LoadBalancingPolicy(std::move(args)),
- response_generator_(MakeRefCounted<FakeResolverResponseGenerator>()),
- lb_call_backoff_(
- BackOff::Options()
- .set_initial_backoff(GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS *
- 1000)
- .set_multiplier(GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER)
- .set_jitter(GRPC_GRPCLB_RECONNECT_JITTER)
- .set_max_backoff(GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS *
- 1000)) {
+ response_generator_(MakeRefCounted<FakeResolverResponseGenerator>()),
+ lb_call_backoff_(
+ BackOff::Options()
+ .set_initial_backoff(GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS *
+ 1000)
+ .set_multiplier(GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER)
+ .set_jitter(GRPC_GRPCLB_RECONNECT_JITTER)
+ .set_max_backoff(GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS *
+ 1000)) {
// Closure Initialization
GRPC_CLOSURE_INIT(&lb_on_fallback_, &GrpcLb::OnFallbackTimer, this,
grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&lb_on_call_retry_, &GrpcLb::OnBalancerCallRetryTimer, this,
grpc_schedule_on_exec_ctx);
- // Record server name.
- const grpc_arg* arg = grpc_channel_args_find(args.args, GRPC_ARG_SERVER_URI);
- const char* server_uri = grpc_channel_arg_get_string(arg);
- GPR_ASSERT(server_uri != nullptr);
- 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);
+ // Record server name.
+ const grpc_arg* arg = grpc_channel_args_find(args.args, GRPC_ARG_SERVER_URI);
+ const char* server_uri = grpc_channel_arg_get_string(arg);
+ GPR_ASSERT(server_uri != nullptr);
+ 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)) {
- gpr_log(GPR_INFO,
- "[grpclb %p] Will use '%s' as the server name for LB request.",
- this, server_name_);
- }
- grpc_uri_destroy(uri);
- // 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});
+ gpr_log(GPR_INFO,
+ "[grpclb %p] Will use '%s' as the server name for LB request.",
+ this, server_name_);
+ }
+ grpc_uri_destroy(uri);
+ // 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.
- arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS);
+ arg = grpc_channel_args_find(args.args, GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS);
fallback_at_startup_timeout_ = grpc_channel_arg_get_integer(
- arg, {GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS, 0, INT_MAX});
-}
-
-GrpcLb::~GrpcLb() {
- gpr_free((void*)server_name_);
- grpc_channel_args_destroy(args_);
-}
-
-void GrpcLb::ShutdownLocked() {
- shutting_down_ = true;
- lb_calld_.reset();
- if (retry_timer_callback_pending_) {
- grpc_timer_cancel(&lb_call_retry_timer_);
- }
+ arg, {GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS, 0, INT_MAX});
+}
+
+GrpcLb::~GrpcLb() {
+ gpr_free((void*)server_name_);
+ grpc_channel_args_destroy(args_);
+}
+
+void GrpcLb::ShutdownLocked() {
+ shutting_down_ = true;
+ lb_calld_.reset();
+ if (retry_timer_callback_pending_) {
+ grpc_timer_cancel(&lb_call_retry_timer_);
+ }
if (fallback_at_startup_checks_pending_) {
fallback_at_startup_checks_pending_ = false;
- grpc_timer_cancel(&lb_fallback_timer_);
+ grpc_timer_cancel(&lb_fallback_timer_);
CancelBalancerChannelConnectivityWatchLocked();
- }
+ }
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
- // alive when that callback is invoked.
- if (lb_channel_ != nullptr) {
+ // 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
+ // alive when that callback is invoked.
+ if (lb_channel_ != nullptr) {
if (parent_channelz_node_ != nullptr) {
channelz::ChannelNode* child_channelz_node =
grpc_channel_get_channelz_node(lb_channel_);
GPR_ASSERT(child_channelz_node != nullptr);
parent_channelz_node_->RemoveChildChannel(child_channelz_node->uuid());
}
- grpc_channel_destroy(lb_channel_);
- lb_channel_ = nullptr;
- }
-}
-
-//
-// public methods
-//
-
+ grpc_channel_destroy(lb_channel_);
+ lb_channel_ = nullptr;
+ }
+}
+
+//
+// public methods
+//
+
void GrpcLb::ResetBackoffLocked() {
if (lb_channel_ != nullptr) {
grpc_channel_reset_connect_backoff(lb_channel_);
@@ -1392,8 +1392,8 @@ void GrpcLb::ResetBackoffLocked() {
if (child_policy_ != nullptr) {
child_policy_->ResetBackoffLocked();
}
-}
-
+}
+
void GrpcLb::UpdateLocked(UpdateArgs args) {
const bool is_initial_update = lb_channel_ == nullptr;
config_ = args.config;
@@ -1423,12 +1423,12 @@ void GrpcLb::UpdateLocked(UpdateArgs args) {
// Start balancer call.
StartBalancerCallLocked();
}
-}
-
+}
+
//
// helpers for UpdateLocked()
//
-
+
ServerAddressList GrpcLb::AddNullLbTokenToAddresses(
const ServerAddressList& addresses) {
ServerAddressList addresses_out;
@@ -1442,26 +1442,26 @@ ServerAddressList GrpcLb::AddNullLbTokenToAddresses(
void GrpcLb::ProcessAddressesAndChannelArgsLocked(
const ServerAddressList& addresses, const grpc_channel_args& args) {
- // Update fallback address list.
+ // Update fallback address list.
fallback_backend_addresses_ = AddNullLbTokenToAddresses(addresses);
- // Make sure that GRPC_ARG_LB_POLICY_NAME is set in channel args,
- // since we use this to trigger the client_load_reporting filter.
- static const char* args_to_remove[] = {GRPC_ARG_LB_POLICY_NAME};
- grpc_arg new_arg = grpc_channel_arg_string_create(
- (char*)GRPC_ARG_LB_POLICY_NAME, (char*)"grpclb");
- grpc_channel_args_destroy(args_);
- args_ = grpc_channel_args_copy_and_add_and_remove(
- &args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1);
- // Construct args for balancer channel.
+ // Make sure that GRPC_ARG_LB_POLICY_NAME is set in channel args,
+ // since we use this to trigger the client_load_reporting filter.
+ static const char* args_to_remove[] = {GRPC_ARG_LB_POLICY_NAME};
+ grpc_arg new_arg = grpc_channel_arg_string_create(
+ (char*)GRPC_ARG_LB_POLICY_NAME, (char*)"grpclb");
+ grpc_channel_args_destroy(args_);
+ args_ = grpc_channel_args_copy_and_add_and_remove(
+ &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);
- // Create balancer channel if needed.
- if (lb_channel_ == nullptr) {
+ // Create balancer channel if needed.
+ if (lb_channel_ == nullptr) {
TString uri_str = y_absl::StrCat("fake:///", server_name_);
lb_channel_ =
CreateGrpclbBalancerChannel(uri_str.c_str(), *lb_channel_args);
- GPR_ASSERT(lb_channel_ != nullptr);
+ GPR_ASSERT(lb_channel_ != nullptr);
// Set up channelz linkage.
channelz::ChannelNode* child_channelz_node =
grpc_channel_get_channelz_node(lb_channel_);
@@ -1472,15 +1472,15 @@ void GrpcLb::ProcessAddressesAndChannelArgsLocked(
parent_channelz_node->AddChildChannel(child_channelz_node->uuid());
parent_channelz_node_ = parent_channelz_node->Ref();
}
- }
- // Propagate updates to the LB channel (pick_first) through the fake
- // resolver.
+ }
+ // 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));
-}
-
+}
+
void GrpcLb::CancelBalancerChannelConnectivityWatchLocked() {
grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(
grpc_channel_get_channel_stack(lb_channel_));
@@ -1488,46 +1488,46 @@ void GrpcLb::CancelBalancerChannelConnectivityWatchLocked() {
grpc_client_channel_stop_connectivity_watch(client_channel_elem, watcher_);
}
-//
-// code for balancer channel and call
-//
-
-void GrpcLb::StartBalancerCallLocked() {
- GPR_ASSERT(lb_channel_ != nullptr);
- if (shutting_down_) return;
- // Init the LB call data.
- GPR_ASSERT(lb_calld_ == nullptr);
- lb_calld_ = MakeOrphanable<BalancerCallState>(Ref());
+//
+// code for balancer channel and call
+//
+
+void GrpcLb::StartBalancerCallLocked() {
+ GPR_ASSERT(lb_channel_ != nullptr);
+ if (shutting_down_) return;
+ // Init the LB call data.
+ GPR_ASSERT(lb_calld_ == nullptr);
+ lb_calld_ = MakeOrphanable<BalancerCallState>(Ref());
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());
- }
- lb_calld_->StartQuery();
-}
-
-void GrpcLb::StartBalancerCallRetryTimerLocked() {
- grpc_millis next_try = lb_call_backoff_.NextAttemptTime();
+ gpr_log(GPR_INFO,
+ "[grpclb %p] Query for backends (lb_channel: %p, lb_calld: %p)",
+ this, lb_channel_, lb_calld_.get());
+ }
+ lb_calld_->StartQuery();
+}
+
+void GrpcLb::StartBalancerCallRetryTimerLocked() {
+ grpc_millis next_try = lb_call_backoff_.NextAttemptTime();
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) {
+ gpr_log(GPR_INFO, "[grpclb %p] Connection to LB server lost...", this);
+ grpc_millis timeout = next_try - ExecCtx::Get()->Now();
+ if (timeout > 0) {
gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active in %" PRId64 "ms.",
- this, timeout);
- } else {
- gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active immediately.",
- this);
- }
- }
- // TODO(roth): We currently track this ref manually. Once the
- // ClosureRef API is ready, we should pass the RefCountedPtr<> along
- // with the callback.
- auto self = Ref(DEBUG_LOCATION, "on_balancer_call_retry_timer");
- self.release();
- retry_timer_callback_pending_ = true;
- grpc_timer_init(&lb_call_retry_timer_, next_try, &lb_on_call_retry_);
-}
-
+ this, timeout);
+ } else {
+ gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active immediately.",
+ this);
+ }
+ }
+ // TODO(roth): We currently track this ref manually. Once the
+ // ClosureRef API is ready, we should pass the RefCountedPtr<> along
+ // with the callback.
+ auto self = Ref(DEBUG_LOCATION, "on_balancer_call_retry_timer");
+ self.release();
+ retry_timer_callback_pending_ = true;
+ 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);
GRPC_ERROR_REF(error); // ref owned by lambda
@@ -1543,17 +1543,17 @@ void GrpcLb::OnBalancerCallRetryTimerLocked(grpc_error* error) {
if (!shutting_down_ && error == GRPC_ERROR_NONE && lb_calld_ == nullptr) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "[grpclb %p] Restarting call to LB server", this);
- }
+ }
StartBalancerCallLocked();
- }
+ }
Unref(DEBUG_LOCATION, "on_balancer_call_retry_timer");
GRPC_ERROR_UNREF(error);
-}
-
-//
+}
+
+//
// 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.
@@ -1570,16 +1570,16 @@ void GrpcLb::MaybeEnterFallbackModeAfterStartup() {
fallback_mode_ = true;
CreateOrUpdateChildPolicyLocked();
}
-}
-
+}
+
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); },
DEBUG_LOCATION);
-}
-
+}
+
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.
@@ -1593,15 +1593,15 @@ void GrpcLb::OnFallbackTimerLocked(grpc_error* error) {
CancelBalancerChannelConnectivityWatchLocked();
fallback_mode_ = true;
CreateOrUpdateChildPolicyLocked();
- }
+ }
Unref(DEBUG_LOCATION, "on_fallback_timer");
GRPC_ERROR_UNREF(error);
-}
-
-//
+}
+
+//
// code for interacting with the child policy
-//
-
+//
+
grpc_channel_args* GrpcLb::CreateChildPolicyArgsLocked(
bool is_backend_from_grpclb_load_balancer) {
y_absl::InlinedVector<grpc_arg, 2> args_to_add;
@@ -1611,11 +1611,11 @@ grpc_channel_args* GrpcLb::CreateChildPolicyArgsLocked(
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());
-}
-
+}
+
OrphanablePtr<LoadBalancingPolicy> GrpcLb::CreateChildPolicyLocked(
const grpc_channel_args* args) {
LoadBalancingPolicy::Args lb_policy_args;
@@ -1629,14 +1629,14 @@ OrphanablePtr<LoadBalancingPolicy> GrpcLb::CreateChildPolicyLocked(
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
+ // 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(),
- interested_parties());
+ interested_parties());
return lb_policy;
-}
-
+}
+
void GrpcLb::CreateOrUpdateChildPolicyLocked() {
if (shutting_down_) return;
// Construct update args.
@@ -1644,16 +1644,16 @@ void GrpcLb::CreateOrUpdateChildPolicyLocked() {
bool is_backend_from_grpclb_load_balancer = false;
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.
+ // 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.args =
CreateChildPolicyArgsLocked(is_backend_from_grpclb_load_balancer);
GPR_ASSERT(update_args.args != nullptr);
@@ -1661,22 +1661,22 @@ void GrpcLb::CreateOrUpdateChildPolicyLocked() {
// 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)) {
gpr_log(GPR_INFO, "[grpclb %p] Updating child policy handler %p", this,
child_policy_.get());
- }
+ }
child_policy_->UpdateLocked(std::move(update_args));
-}
-
-//
-// factory
-//
-
-class GrpcLbFactory : public LoadBalancingPolicyFactory {
- public:
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
+}
+
+//
+// factory
+//
+
+class GrpcLbFactory : public LoadBalancingPolicyFactory {
+ public:
+ OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return MakeOrphanable<GrpcLb>(std::move(args));
}
@@ -1711,7 +1711,7 @@ class GrpcLbFactory : public LoadBalancingPolicyFactory {
child_policy_config_json = &child_policy_config_json_tmp;
} else {
child_policy_config_json = &it->second;
- }
+ }
grpc_error* parse_error = GRPC_ERROR_NONE;
RefCountedPtr<LoadBalancingPolicy::Config> child_policy_config =
LoadBalancingPolicyRegistry::ParseLoadBalancingConfig(
@@ -1729,49 +1729,49 @@ class GrpcLbFactory : public LoadBalancingPolicyFactory {
*error = GRPC_ERROR_CREATE_FROM_VECTOR("GrpcLb Parser", &error_list);
return nullptr;
}
- }
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-//
-// Plugin registration
-//
-
-namespace {
-
-// Only add client_load_reporting filter if the grpclb LB policy is used.
-bool maybe_add_client_load_reporting_filter(grpc_channel_stack_builder* builder,
- void* arg) {
- const grpc_channel_args* args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- const grpc_arg* channel_arg =
- 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) {
+ }
+};
+
+} // namespace
+
+} // namespace grpc_core
+
+//
+// Plugin registration
+//
+
+namespace {
+
+// Only add client_load_reporting filter if the grpclb LB policy is used.
+bool maybe_add_client_load_reporting_filter(grpc_channel_stack_builder* builder,
+ void* arg) {
+ const grpc_channel_args* args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ const grpc_arg* channel_arg =
+ 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(
- builder, (const grpc_channel_filter*)arg, nullptr, nullptr);
- }
- return true;
-}
-
-} // namespace
-
-void grpc_lb_policy_grpclb_init() {
- grpc_core::LoadBalancingPolicyRegistry::Builder::
- RegisterLoadBalancingPolicyFactory(
+ builder, (const grpc_channel_filter*)arg, nullptr, nullptr);
+ }
+ return true;
+}
+
+} // namespace
+
+void grpc_lb_policy_grpclb_init() {
+ grpc_core::LoadBalancingPolicyRegistry::Builder::
+ RegisterLoadBalancingPolicyFactory(
y_absl::make_unique<grpc_core::GrpcLbFactory>());
- grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
- GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_client_load_reporting_filter,
- (void*)&grpc_client_load_reporting_filter);
-}
-
-void grpc_lb_policy_grpclb_shutdown() {}
+ grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
+ GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ maybe_add_client_load_reporting_filter,
+ (void*)&grpc_client_load_reporting_filter);
+}
+
+void grpc_lb_policy_grpclb_shutdown() {}
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 f8197a89bfb..47f4de73c48 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/grpc.h>
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.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) {
- return args;
-}
+ return args;
+}
grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
const grpc_channel_args& args) {
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 1458233022f..fb37eb7a80c 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
@@ -1,45 +1,45 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CHANNEL_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CHANNEL_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CHANNEL_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CHANNEL_H
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/grpc_types.h>
-
+
#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.
+/// 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
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CHANNEL_H \
- */
+#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 e918ee08360..09ea5f0ab4a 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
-
-#include <string.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
+
+#include <string.h>
+
#include "y_absl/container/inlined_vector.h"
#include <grpc/grpc_security.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/security/credentials/credentials.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-namespace grpc_core {
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/security/credentials/credentials.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+namespace grpc_core {
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
- // credentials: the load balancer is not necessarily trusted to handle
- // bearer token credentials.
- grpc_channel_credentials* channel_credentials =
- grpc_channel_credentials_find_in_args(args);
+ // Substitute the channel credentials with a version without call
+ // credentials: the load balancer is not necessarily trusted to handle
+ // bearer token credentials.
+ grpc_channel_credentials* channel_credentials =
+ grpc_channel_credentials_find_in_args(args);
RefCountedPtr<grpc_channel_credentials> creds_sans_call_creds;
- if (channel_credentials != nullptr) {
- 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);
+ 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()));
- }
- grpc_channel_args* result = grpc_channel_args_copy_and_add_and_remove(
+ }
+ 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());
- // Clean up.
- grpc_channel_args_destroy(args);
- return result;
-}
+ // Clean up.
+ grpc_channel_args_destroy(args);
+ return result;
+}
grpc_channel* CreateGrpclbBalancerChannel(const char* target_uri,
const grpc_channel_args& args) {
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 1566e7b5f17..3925aad3c3d 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
@@ -1,82 +1,82 @@
-/*
- *
- * 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/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
-
-#include <string.h>
-
-#include <grpc/support/atm.h>
-#include <grpc/support/string_util.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
+
+#include <string.h>
+
+#include <grpc/support/atm.h>
+#include <grpc/support/string_util.h>
+
#include "src/core/lib/gprpp/sync.h"
namespace grpc_core {
-
+
void GrpcLbClientStats::AddCallStarted() {
gpr_atm_full_fetch_add(&num_calls_started_, (gpr_atm)1);
-}
-
+}
+
void GrpcLbClientStats::AddCallFinished(
bool finished_with_client_failed_to_send, bool finished_known_received) {
gpr_atm_full_fetch_add(&num_calls_finished_, (gpr_atm)1);
- if (finished_with_client_failed_to_send) {
+ if (finished_with_client_failed_to_send) {
gpr_atm_full_fetch_add(&num_calls_finished_with_client_failed_to_send_,
(gpr_atm)1);
- }
- if (finished_known_received) {
+ }
+ if (finished_known_received) {
gpr_atm_full_fetch_add(&num_calls_finished_known_received_, (gpr_atm)1);
- }
-}
-
+ }
+}
+
void GrpcLbClientStats::AddCallDropped(const char* token) {
- // Increment num_calls_started and num_calls_finished.
+ // 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.
+ // Record the drop.
MutexLock lock(&drop_count_mu_);
if (drop_token_counts_ == nullptr) {
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) {
++(*drop_token_counts_)[i].count;
- return;
- }
- }
+ return;
+ }
+ }
// Not found, so add a new entry.
drop_token_counts_->emplace_back(
grpc_core::UniquePtr<char>(gpr_strdup(token)), 1);
-}
-
+}
+
namespace {
void AtomicGetAndResetCounter(int64_t* value, gpr_atm* counter) {
*value = static_cast<int64_t>(gpr_atm_full_xchg(counter, (gpr_atm)0));
-}
-
+}
+
} // namespace
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,
+ int64_t* num_calls_finished_with_client_failed_to_send,
+ int64_t* num_calls_finished_known_received,
std::unique_ptr<DroppedCallCounts>* drop_token_counts) {
AtomicGetAndResetCounter(num_calls_started, &num_calls_started_);
AtomicGetAndResetCounter(num_calls_finished, &num_calls_finished_);
@@ -86,6 +86,6 @@ void GrpcLbClientStats::Get(
&num_calls_finished_known_received_);
MutexLock lock(&drop_count_mu_);
*drop_token_counts = std::move(drop_token_counts_);
-}
-
+}
+
} // namespace grpc_core
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 e5304fda6be..59068b874ba 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
@@ -1,59 +1,59 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/support/atm.h>
-
+
#include "y_absl/container/inlined_vector.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/sync.h"
-
+
namespace grpc_core {
-
+
class GrpcLbClientStats : public RefCounted<GrpcLbClientStats> {
public:
struct DropTokenCount {
grpc_core::UniquePtr<char> token;
int64_t count;
-
+
DropTokenCount(grpc_core::UniquePtr<char> token, int64_t count)
: token(std::move(token)), count(count) {}
};
-
+
typedef y_absl::InlinedVector<DropTokenCount, 10> DroppedCallCounts;
-
+
void AddCallStarted();
void AddCallFinished(bool finished_with_client_failed_to_send,
bool finished_known_received);
-
+
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) {
@@ -71,5 +71,5 @@ class GrpcLbClientStats : public RefCounted<GrpcLbClientStats> {
} // namespace grpc_core
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H \
- */
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H \
+ */
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 3185b993c41..ab2f6be6ec0 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
@@ -1,31 +1,31 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/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 <grpc/support/alloc.h>
-
+#include <grpc/support/alloc.h>
+
namespace grpc_core {
bool GrpcLbServer::operator==(const GrpcLbServer& other) const {
@@ -60,18 +60,18 @@ grpc_slice GrpcLbRequestCreate(const char* lb_service_name, upb_arena* arena) {
grpc_lb_v1_InitialLoadBalanceRequest_set_name(
initial_request, upb_strview_make(lb_service_name, name_len));
return grpc_grpclb_request_encode(req, arena);
-}
-
+}
+
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);
-}
-
+}
+
} // namespace
-
+
grpc_slice GrpcLbLoadReportRequestCreate(
int64_t num_calls_started, int64_t num_calls_finished,
int64_t num_calls_finished_with_client_failed_to_send,
@@ -101,13 +101,13 @@ grpc_slice GrpcLbLoadReportRequestCreate(
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);
-}
-
+}
+
namespace {
-
+
bool ParseServerList(const grpc_lb_v1_LoadBalanceResponse& response,
std::vector<GrpcLbServer>* server_list) {
// Determine the number of servers.
@@ -141,20 +141,20 @@ bool ParseServerList(const grpc_lb_v1_LoadBalanceResponse& response,
token.size);
}
cur.drop = grpc_lb_v1_Server_drop(servers[i]);
- }
- }
+ }
+ }
return true;
-}
-
+}
+
grpc_millis grpc_grpclb_duration_to_millis(
const google_protobuf_Duration* duration_pb) {
return static_cast<grpc_millis>(
(google_protobuf_Duration_seconds(duration_pb) * GPR_MS_PER_SEC) +
(google_protobuf_Duration_nanos(duration_pb) / GPR_NS_PER_MS));
-}
-
+}
+
} // namespace
-
+
bool GrpcLbResponseParse(const grpc_slice& encoded_grpc_grpclb_response,
upb_arena* arena, GrpcLbResponse* result) {
grpc_lb_v1_LoadBalanceResponse* response =
@@ -166,7 +166,7 @@ bool GrpcLbResponseParse(const grpc_slice& encoded_grpc_grpclb_response,
if (ParseServerList(*response, &result->serverlist)) {
result->type = result->SERVERLIST;
return true;
- }
+ }
// Handle initial responses.
auto* initial_response =
grpc_lb_v1_LoadBalanceResponse_initial_response(response);
@@ -178,9 +178,9 @@ bool GrpcLbResponseParse(const grpc_slice& encoded_grpc_grpclb_response,
if (client_stats_report_interval != nullptr) {
result->client_stats_report_interval =
grpc_grpclb_duration_to_millis(client_stats_report_interval);
- }
+ }
return true;
- }
+ }
// Handle fallback.
if (grpc_lb_v1_LoadBalanceResponse_has_fallback_response(response)) {
result->type = result->FALLBACK;
@@ -188,6 +188,6 @@ bool GrpcLbResponseParse(const grpc_slice& encoded_grpc_grpclb_response,
}
// Unknown response type.
return false;
-}
-
+}
+
} // 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 6caa120f587..d375fed92c0 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
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_LOAD_BALANCER_API_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_LOAD_BALANCER_API_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_LB_POLICY_GRPCLB_LOAD_BALANCER_API_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_LOAD_BALANCER_API_H
+
+#include <grpc/support/port_platform.h>
+
#include <vector>
-#include <grpc/slice_buffer.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
+#include <grpc/slice_buffer.h>
+
+#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"
-
-#define GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH 128
+
+#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
-
+
namespace grpc_core {
// Contains server information. When the drop field is not true, use the other
@@ -46,16 +46,16 @@ struct GrpcLbServer {
bool operator==(const GrpcLbServer& other) const;
};
-
+
struct GrpcLbResponse {
enum { INITIAL, SERVERLIST, FALLBACK } type;
grpc_millis client_stats_report_interval = 0;
std::vector<GrpcLbServer> serverlist;
};
-
+
// Creates a serialized grpclb request.
grpc_slice GrpcLbRequestCreate(const char* lb_service_name, upb_arena* arena);
-
+
// Creates a serialized grpclb load report request.
grpc_slice GrpcLbLoadReportRequestCreate(
int64_t num_calls_started, int64_t num_calls_finished,
@@ -63,12 +63,12 @@ grpc_slice GrpcLbLoadReportRequestCreate(
int64_t num_calls_finished_known_received,
const GrpcLbClientStats::DroppedCallCounts* drop_token_counts,
upb_arena* arena);
-
+
// Deserialize a grpclb response.
bool GrpcLbResponseParse(const grpc_slice& serialized_response,
upb_arena* arena, GrpcLbResponse* response);
-
+
} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_LOAD_BALANCER_API_H \
- */
+
+#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 ab780530085..a59d90e731b 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
@@ -1,103 +1,103 @@
-/*
- *
- * 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 <string.h>
-
-#include <grpc/support/alloc.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy/subchannel_list.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.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 <string.h>
+
+#include <grpc/support/alloc.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy/subchannel_list.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/ext/filters/client_channel/subchannel.h"
-#include "src/core/lib/channel/channel_args.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/iomgr/sockaddr_utils.h"
-#include "src/core/lib/transport/connectivity_state.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"
-
-namespace grpc_core {
-
-TraceFlag grpc_lb_pick_first_trace(false, "pick_first");
-
-namespace {
-
-//
-// pick_first LB policy
-//
-
+
+namespace grpc_core {
+
+TraceFlag grpc_lb_pick_first_trace(false, "pick_first");
+
+namespace {
+
+//
+// pick_first LB policy
+//
+
constexpr char kPickFirst[] = "pick_first";
-class PickFirst : public LoadBalancingPolicy {
- public:
+class PickFirst : public LoadBalancingPolicy {
+ public:
explicit PickFirst(Args args);
-
+
const char* name() const override { return kPickFirst; }
void UpdateLocked(UpdateArgs args) override;
- void ExitIdleLocked() override;
+ void ExitIdleLocked() override;
void ResetBackoffLocked() override;
-
- private:
- ~PickFirst();
-
- class PickFirstSubchannelList;
-
- class PickFirstSubchannelData
- : public SubchannelData<PickFirstSubchannelList,
- PickFirstSubchannelData> {
- public:
+
+ private:
+ ~PickFirst();
+
+ class PickFirstSubchannelList;
+
+ class PickFirstSubchannelData
+ : public SubchannelData<PickFirstSubchannelList,
+ PickFirstSubchannelData> {
+ public:
PickFirstSubchannelData(
SubchannelList<PickFirstSubchannelList, PickFirstSubchannelData>*
subchannel_list,
const ServerAddress& address,
RefCountedPtr<SubchannelInterface> subchannel)
: SubchannelData(subchannel_list, address, std::move(subchannel)) {}
-
- void ProcessConnectivityChangeLocked(
+
+ void ProcessConnectivityChangeLocked(
grpc_connectivity_state connectivity_state) override;
// Processes the connectivity change to READY for an unselected subchannel.
void ProcessUnselectedReadyLocked();
void CheckConnectivityStateAndStartWatchingLocked();
- };
-
- class PickFirstSubchannelList
- : public SubchannelList<PickFirstSubchannelList,
- PickFirstSubchannelData> {
- public:
- PickFirstSubchannelList(PickFirst* policy, TraceFlag* tracer,
+ };
+
+ class PickFirstSubchannelList
+ : public SubchannelList<PickFirstSubchannelList,
+ PickFirstSubchannelData> {
+ public:
+ PickFirstSubchannelList(PickFirst* 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) {
- // 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.
- policy->Ref(DEBUG_LOCATION, "subchannel_list").release();
- }
-
- ~PickFirstSubchannelList() {
- PickFirst* p = static_cast<PickFirst*>(policy());
- p->Unref(DEBUG_LOCATION, "subchannel_list");
- }
+ // 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.
+ policy->Ref(DEBUG_LOCATION, "subchannel_list").release();
+ }
+
+ ~PickFirstSubchannelList() {
+ 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) {
@@ -106,8 +106,8 @@ class PickFirst : public LoadBalancingPolicy {
private:
bool in_transient_failure_ = false;
- };
-
+ };
+
class Picker : public SubchannelPicker {
public:
explicit Picker(RefCountedPtr<SubchannelInterface> subchannel)
@@ -124,58 +124,58 @@ class PickFirst : public LoadBalancingPolicy {
RefCountedPtr<SubchannelInterface> subchannel_;
};
- void ShutdownLocked() override;
-
+ void ShutdownLocked() override;
+
void AttemptToConnectUsingLatestUpdateArgsLocked();
-
+
// 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;
+ // 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 shut down?
- bool shutdown_ = 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)) {
- gpr_log(GPR_INFO, "Pick First %p created.", this);
- }
-}
-
-PickFirst::~PickFirst() {
+ gpr_log(GPR_INFO, "Pick First %p created.", this);
+ }
+}
+
+PickFirst::~PickFirst() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
- gpr_log(GPR_INFO, "Destroying Pick First %p", this);
- }
- GPR_ASSERT(subchannel_list_ == nullptr);
- GPR_ASSERT(latest_pending_subchannel_list_ == nullptr);
-}
-
-void PickFirst::ShutdownLocked() {
+ gpr_log(GPR_INFO, "Destroying Pick First %p", this);
+ }
+ GPR_ASSERT(subchannel_list_ == nullptr);
+ GPR_ASSERT(latest_pending_subchannel_list_ == nullptr);
+}
+
+void PickFirst::ShutdownLocked() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
- gpr_log(GPR_INFO, "Pick First %p Shutting down", this);
- }
- shutdown_ = true;
- subchannel_list_.reset();
- latest_pending_subchannel_list_.reset();
-}
-
+ gpr_log(GPR_INFO, "Pick First %p Shutting down", this);
+ }
+ shutdown_ = true;
+ subchannel_list_.reset();
+ 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);
- }
+ }
idle_ = false;
AttemptToConnectUsingLatestUpdateArgsLocked();
- }
-}
-
+ }
+}
+
void PickFirst::ResetBackoffLocked() {
if (subchannel_list_ != nullptr) subchannel_list_->ResetBackoffLocked();
if (latest_pending_subchannel_list_ != nullptr) {
@@ -185,14 +185,14 @@ void PickFirst::ResetBackoffLocked() {
void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
// Create a subchannel list from the latest_update_args_.
- auto subchannel_list = MakeOrphanable<PickFirstSubchannelList>(
+ 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.
- if (subchannel_list->num_subchannels() == 0) {
+ if (subchannel_list->num_subchannels() == 0) {
// Unsubscribe from all current subchannels.
- subchannel_list_ = std::move(subchannel_list); // Empty list.
- selected_ = nullptr;
+ 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
@@ -203,8 +203,8 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
- return;
- }
+ return;
+ }
// If one of the subchannels in the new list is already in state
// READY, then select it immediately. This can happen when the
// currently selected subchannel is also present in the update. It
@@ -224,32 +224,32 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
return;
}
}
- if (selected_ == nullptr) {
- // We don't yet have a selected subchannel, so replace the current
- // subchannel list immediately.
- subchannel_list_ = std::move(subchannel_list);
+ if (selected_ == nullptr) {
+ // 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
- // subchannel in the new list.
+ // 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();
- } else {
+ } 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.
- if (latest_pending_subchannel_list_ != nullptr) {
+ if (latest_pending_subchannel_list_ != nullptr) {
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",
- this, latest_pending_subchannel_list_.get(),
- subchannel_list.get());
- }
- }
- latest_pending_subchannel_list_ = std::move(subchannel_list);
+ gpr_log(GPR_INFO,
+ "Pick First %p Shutting down latest pending subchannel list "
+ "%p, about to be replaced by newer latest %p",
+ this, latest_pending_subchannel_list_.get(),
+ subchannel_list.get());
+ }
+ }
+ latest_pending_subchannel_list_ = std::move(subchannel_list);
// If we're not in IDLE state, start trying to connect to the first
- // subchannel in the new list.
+ // 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.
@@ -258,9 +258,9 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
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,
@@ -282,36 +282,36 @@ void PickFirst::UpdateLocked(UpdateArgs args) {
}
}
-void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
+void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
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.
- GPR_ASSERT(subchannel_list() == p->subchannel_list_.get() ||
- subchannel_list() == p->latest_pending_subchannel_list_.get());
+ PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy());
+ // The notification must be for a subchannel in either the current or
+ // latest pending subchannel lists.
+ GPR_ASSERT(subchannel_list() == p->subchannel_list_.get() ||
+ subchannel_list() == p->latest_pending_subchannel_list_.get());
GPR_ASSERT(connectivity_state != GRPC_CHANNEL_SHUTDOWN);
- // Handle updates for the currently selected subchannel.
- if (p->selected_ == this) {
+ // Handle updates for the currently selected subchannel.
+ if (p->selected_ == this) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"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 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)) {
- gpr_log(GPR_INFO,
- "Pick First %p promoting pending subchannel list %p to "
- "replace %p",
- p, p->latest_pending_subchannel_list_.get(),
- p->subchannel_list_.get());
- }
- p->selected_ = nullptr;
+ gpr_log(GPR_INFO,
+ "Pick First %p promoting pending subchannel list %p to "
+ "replace %p",
+ p, p->latest_pending_subchannel_list_.get(),
+ p->subchannel_list_.get());
+ }
+ p->selected_ = nullptr;
CancelConnectivityWatchLocked(
"selected subchannel failed; switching to pending update");
- p->subchannel_list_ = std::move(p->latest_pending_subchannel_list_);
+ 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(
@@ -327,8 +327,8 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
y_absl::make_unique<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker")));
}
- } else {
- if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
+ } 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
@@ -337,13 +337,13 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
// ExitIdleLocked().
p->idle_ = true;
p->channel_control_helper()->RequestReresolution();
- p->selected_ = nullptr;
+ p->selected_ = nullptr;
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 {
+ } 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.
@@ -357,28 +357,28 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
y_absl::make_unique<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker")));
}
- }
- }
- return;
- }
- // If we get here, there are two possible cases:
- // 1. We do not currently have a selected subchannel, and the update is
- // for a subchannel in p->subchannel_list_ that we're trying to
- // connect to. The goal here is to find a subchannel that we can
- // select.
- // 2. We do currently have a selected subchannel, and the update is
- // 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.
+ }
+ }
+ return;
+ }
+ // If we get here, there are two possible cases:
+ // 1. We do not currently have a selected subchannel, and the update is
+ // for a subchannel in p->subchannel_list_ that we're trying to
+ // connect to. The goal here is to find a subchannel that we can
+ // select.
+ // 2. We do currently have a selected subchannel, and the update is
+ // 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);
- switch (connectivity_state) {
- case GRPC_CHANNEL_READY: {
+ switch (connectivity_state) {
+ case GRPC_CHANNEL_READY: {
ProcessUnselectedReadyLocked();
- break;
- }
- case GRPC_CHANNEL_TRANSIENT_FAILURE: {
+ break;
+ }
+ case GRPC_CHANNEL_TRANSIENT_FAILURE: {
CancelConnectivityWatchLocked("connection attempt failed");
- PickFirstSubchannelData* sd = this;
+ PickFirstSubchannelData* sd = this;
size_t next_index =
(sd->Index() + 1) % subchannel_list()->num_subchannels();
sd = subchannel_list()->subchannel(next_index);
@@ -401,26 +401,26 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
}
- }
+ }
sd->CheckConnectivityStateAndStartWatchingLocked();
- break;
- }
- case GRPC_CHANNEL_CONNECTING:
- case GRPC_CHANNEL_IDLE: {
- // Only update connectivity state in case 1.
- if (subchannel_list() == p->subchannel_list_.get()) {
+ break;
+ }
+ case GRPC_CHANNEL_CONNECTING:
+ case GRPC_CHANNEL_IDLE: {
+ // Only update connectivity state in case 1.
+ if (subchannel_list() == p->subchannel_list_.get()) {
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING, y_absl::Status(),
y_absl::make_unique<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker")));
- }
- break;
- }
- case GRPC_CHANNEL_SHUTDOWN:
- GPR_UNREACHABLE_CODE(break);
- }
-}
-
+ }
+ break;
+ }
+ case GRPC_CHANNEL_SHUTDOWN:
+ GPR_UNREACHABLE_CODE(break);
+ }
+}
+
void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() {
PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy());
// If we get here, there are two possible cases:
@@ -483,33 +483,33 @@ class PickFirstConfig : public LoadBalancingPolicy::Config {
const char* name() const override { return kPickFirst; }
};
-//
-// factory
-//
-
-class PickFirstFactory : public LoadBalancingPolicyFactory {
- public:
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
+//
+// factory
+//
+
+class PickFirstFactory : public LoadBalancingPolicyFactory {
+ public:
+ OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return MakeOrphanable<PickFirst>(std::move(args));
- }
-
+ }
+
const char* name() const override { return kPickFirst; }
RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** /*error*/) const override {
return MakeRefCounted<PickFirstConfig>();
}
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-void grpc_lb_policy_pick_first_init() {
- grpc_core::LoadBalancingPolicyRegistry::Builder::
- RegisterLoadBalancingPolicyFactory(
+};
+
+} // namespace
+
+} // namespace grpc_core
+
+void grpc_lb_policy_pick_first_init() {
+ grpc_core::LoadBalancingPolicyRegistry::Builder::
+ RegisterLoadBalancingPolicyFactory(
y_absl::make_unique<grpc_core::PickFirstFactory>());
-}
-
-void grpc_lb_policy_pick_first_shutdown() {}
+}
+
+void grpc_lb_policy_pick_first_shutdown() {}
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 b277add32a1..98b2aa49e57 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
@@ -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.
- *
- */
-
-/** Round Robin Policy.
- *
- * Before every pick, the \a get_next_ready_subchannel_index_locked function
- * returns the p->subchannel_list->subchannels index for next subchannel,
- * respecting the relative order of the addresses provided upon creation or
- * updates. Note however that updates will start picking from the beginning of
- * the updated list. */
-
-#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.
+ *
+ */
+
+/** Round Robin Policy.
+ *
+ * Before every pick, the \a get_next_ready_subchannel_index_locked function
+ * returns the p->subchannel_list->subchannels index for next subchannel,
+ * respecting the relative order of the addresses provided upon creation or
+ * updates. Note however that updates will start picking from the beginning of
+ * the updated list. */
+
+#include <grpc/support/port_platform.h>
+
#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy/subchannel_list.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
-#include "src/core/ext/filters/client_channel/subchannel.h"
-#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 <string.h>
+
+#include <grpc/support/alloc.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy/subchannel_list.h"
+#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
+#include "src/core/ext/filters/client_channel/subchannel.h"
+#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/iomgr/sockaddr_utils.h"
-#include "src/core/lib/transport/connectivity_state.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"
-#include "src/core/lib/transport/static_metadata.h"
-
-namespace grpc_core {
-
-TraceFlag grpc_lb_round_robin_trace(false, "round_robin");
-
-namespace {
-
-//
-// round_robin LB policy
-//
-
+#include "src/core/lib/transport/static_metadata.h"
+
+namespace grpc_core {
+
+TraceFlag grpc_lb_round_robin_trace(false, "round_robin");
+
+namespace {
+
+//
+// round_robin LB policy
+//
+
constexpr char kRoundRobin[] = "round_robin";
-class RoundRobin : public LoadBalancingPolicy {
- public:
+class RoundRobin : public LoadBalancingPolicy {
+ public:
explicit RoundRobin(Args args);
-
+
const char* name() const override { return kRoundRobin; }
void UpdateLocked(UpdateArgs args) override;
void ResetBackoffLocked() override;
-
- private:
- ~RoundRobin();
-
- // Forward declaration.
- class RoundRobinSubchannelList;
-
- // Data for a particular subchannel in a subchannel list.
- // This subclass adds the following functionality:
- // - Tracks the previous connectivity state of the subchannel, so that
- // we know how many subchannels are in each state.
- class RoundRobinSubchannelData
- : public SubchannelData<RoundRobinSubchannelList,
- RoundRobinSubchannelData> {
- public:
+
+ private:
+ ~RoundRobin();
+
+ // Forward declaration.
+ class RoundRobinSubchannelList;
+
+ // Data for a particular subchannel in a subchannel list.
+ // This subclass adds the following functionality:
+ // - Tracks the previous connectivity state of the subchannel, so that
+ // we know how many subchannels are in each state.
+ class RoundRobinSubchannelData
+ : public SubchannelData<RoundRobinSubchannelList,
+ RoundRobinSubchannelData> {
+ public:
RoundRobinSubchannelData(
SubchannelList<RoundRobinSubchannelList, RoundRobinSubchannelData>*
subchannel_list,
const ServerAddress& address,
RefCountedPtr<SubchannelInterface> subchannel)
: SubchannelData(subchannel_list, address, std::move(subchannel)) {}
-
- grpc_connectivity_state connectivity_state() const {
- return last_connectivity_state_;
- }
-
+
+ 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.
- void UpdateConnectivityStateLocked(
+ void UpdateConnectivityStateLocked(
grpc_connectivity_state connectivity_state);
-
- private:
+
+ private:
// Performs connectivity state updates that need to be done only
// after we have started watching.
- void ProcessConnectivityChangeLocked(
+ void ProcessConnectivityChangeLocked(
grpc_connectivity_state connectivity_state) override;
-
- grpc_connectivity_state last_connectivity_state_ = GRPC_CHANNEL_IDLE;
+
+ grpc_connectivity_state last_connectivity_state_ = GRPC_CHANNEL_IDLE;
bool seen_failure_since_ready_ = false;
- };
-
- // A list of subchannels.
- class RoundRobinSubchannelList
- : public SubchannelList<RoundRobinSubchannelList,
- RoundRobinSubchannelData> {
- public:
+ };
+
+ // A list of subchannels.
+ class RoundRobinSubchannelList
+ : public SubchannelList<RoundRobinSubchannelList,
+ RoundRobinSubchannelData> {
+ public:
RoundRobinSubchannelList(RoundRobin* policy, TraceFlag* tracer,
ServerAddressList addresses,
const grpc_channel_args& args)
: SubchannelList(policy, tracer, std::move(addresses),
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.
- policy->Ref(DEBUG_LOCATION, "subchannel_list").release();
- }
-
- ~RoundRobinSubchannelList() {
- RoundRobin* p = static_cast<RoundRobin*>(policy());
- p->Unref(DEBUG_LOCATION, "subchannel_list");
- }
-
- // Starts watching the subchannels in this list.
- void StartWatchingLocked();
-
- // 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,
+ // 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.
+ policy->Ref(DEBUG_LOCATION, "subchannel_list").release();
+ }
+
+ ~RoundRobinSubchannelList() {
+ RoundRobin* p = static_cast<RoundRobin*>(policy());
+ p->Unref(DEBUG_LOCATION, "subchannel_list");
+ }
+
+ // Starts watching the subchannels in this list.
+ void StartWatchingLocked();
+
+ // 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);
-
- // If this subchannel list is the RR policy's current subchannel
- // list, updates the RR policy's connectivity state based on the
- // subchannel list's state counters.
- void MaybeUpdateRoundRobinConnectivityStateLocked();
-
- // Updates the RR policy's overall state based on the counters of
- // subchannels in each state.
- void UpdateRoundRobinStateFromSubchannelStateCountsLocked();
-
- private:
- size_t num_ready_ = 0;
- size_t num_connecting_ = 0;
- size_t num_transient_failure_ = 0;
- };
-
+
+ // If this subchannel list is the RR policy's current subchannel
+ // list, updates the RR policy's connectivity state based on the
+ // subchannel list's state counters.
+ void MaybeUpdateRoundRobinConnectivityStateLocked();
+
+ // Updates the RR policy's overall state based on the counters of
+ // subchannels in each state.
+ void UpdateRoundRobinStateFromSubchannelStateCountsLocked();
+
+ private:
+ size_t num_ready_ = 0;
+ size_t num_connecting_ = 0;
+ size_t num_transient_failure_ = 0;
+ };
+
class Picker : public SubchannelPicker {
public:
Picker(RoundRobin* parent, RoundRobinSubchannelList* subchannel_list);
@@ -164,20 +164,20 @@ class RoundRobin : public LoadBalancingPolicy {
y_absl::InlinedVector<RefCountedPtr<SubchannelInterface>, 10> subchannels_;
};
- void ShutdownLocked() override;
-
- /** list of subchannels */
- OrphanablePtr<RoundRobinSubchannelList> subchannel_list_;
- /** Latest version of the subchannel list.
- * Subchannel connectivity callbacks will only promote updated subchannel
- * lists if they equal \a latest_pending_subchannel_list. In other words,
- * racing callbacks that reference outdated subchannel lists won't perform any
- * update. */
- OrphanablePtr<RoundRobinSubchannelList> latest_pending_subchannel_list_;
- /** are we shutting down? */
- bool shutdown_ = false;
-};
-
+ void ShutdownLocked() override;
+
+ /** list of subchannels */
+ OrphanablePtr<RoundRobinSubchannelList> subchannel_list_;
+ /** Latest version of the subchannel list.
+ * Subchannel connectivity callbacks will only promote updated subchannel
+ * lists if they equal \a latest_pending_subchannel_list. In other words,
+ * racing callbacks that reference outdated subchannel lists won't perform any
+ * update. */
+ OrphanablePtr<RoundRobinSubchannelList> latest_pending_subchannel_list_;
+ /** are we shutting down? */
+ bool shutdown_ = false;
+};
+
//
// RoundRobin::Picker
//
@@ -226,26 +226,26 @@ RoundRobin::PickResult RoundRobin::Picker::Pick(PickArgs /*args*/) {
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);
- }
-}
-
-RoundRobin::~RoundRobin() {
+ }
+}
+
+RoundRobin::~RoundRobin() {
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);
- GPR_ASSERT(latest_pending_subchannel_list_ == nullptr);
-}
-
-void RoundRobin::ShutdownLocked() {
+ gpr_log(GPR_INFO, "[RR %p] Destroying Round Robin policy", this);
+ }
+ GPR_ASSERT(subchannel_list_ == nullptr);
+ GPR_ASSERT(latest_pending_subchannel_list_ == nullptr);
+}
+
+void RoundRobin::ShutdownLocked() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) {
- gpr_log(GPR_INFO, "[RR %p] Shutting down", this);
- }
- shutdown_ = true;
- subchannel_list_.reset();
- latest_pending_subchannel_list_.reset();
-}
-
+ gpr_log(GPR_INFO, "[RR %p] Shutting down", this);
+ }
+ shutdown_ = true;
+ subchannel_list_.reset();
+ latest_pending_subchannel_list_.reset();
+}
+
void RoundRobin::ResetBackoffLocked() {
subchannel_list_->ResetBackoffLocked();
if (latest_pending_subchannel_list_ != nullptr) {
@@ -253,84 +253,84 @@ void RoundRobin::ResetBackoffLocked() {
}
}
-void RoundRobin::RoundRobinSubchannelList::StartWatchingLocked() {
- if (num_subchannels() == 0) return;
- // Check current state of each subchannel synchronously, since any
- // subchannel already used by some other channel may have a non-IDLE
- // state.
- for (size_t i = 0; i < num_subchannels(); ++i) {
- grpc_connectivity_state state =
+void RoundRobin::RoundRobinSubchannelList::StartWatchingLocked() {
+ if (num_subchannels() == 0) return;
+ // Check current state of each subchannel synchronously, since any
+ // subchannel already used by some other channel may have a non-IDLE
+ // state.
+ for (size_t i = 0; i < num_subchannels(); ++i) {
+ grpc_connectivity_state state =
subchannel(i)->CheckConnectivityStateLocked();
- if (state != GRPC_CHANNEL_IDLE) {
+ if (state != GRPC_CHANNEL_IDLE) {
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();
+ }
+ }
+ // 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();
- }
- }
+ }
+ }
// Now set the LB policy's state based on the subchannels' states.
UpdateRoundRobinStateFromSubchannelStateCountsLocked();
-}
-
-void RoundRobin::RoundRobinSubchannelList::UpdateStateCountersLocked(
+}
+
+void RoundRobin::RoundRobinSubchannelList::UpdateStateCountersLocked(
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) {
- GPR_ASSERT(num_ready_ > 0);
- --num_ready_;
- } else if (old_state == GRPC_CHANNEL_CONNECTING) {
- GPR_ASSERT(num_connecting_ > 0);
- --num_connecting_;
- } else if (old_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
- GPR_ASSERT(num_transient_failure_ > 0);
- --num_transient_failure_;
- }
- if (new_state == GRPC_CHANNEL_READY) {
- ++num_ready_;
- } else if (new_state == GRPC_CHANNEL_CONNECTING) {
- ++num_connecting_;
- } else if (new_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
- ++num_transient_failure_;
- }
-}
-
+ GPR_ASSERT(old_state != GRPC_CHANNEL_SHUTDOWN);
+ GPR_ASSERT(new_state != GRPC_CHANNEL_SHUTDOWN);
+ if (old_state == GRPC_CHANNEL_READY) {
+ GPR_ASSERT(num_ready_ > 0);
+ --num_ready_;
+ } else if (old_state == GRPC_CHANNEL_CONNECTING) {
+ GPR_ASSERT(num_connecting_ > 0);
+ --num_connecting_;
+ } else if (old_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
+ GPR_ASSERT(num_transient_failure_ > 0);
+ --num_transient_failure_;
+ }
+ if (new_state == GRPC_CHANNEL_READY) {
+ ++num_ready_;
+ } else if (new_state == GRPC_CHANNEL_CONNECTING) {
+ ++num_connecting_;
+ } else if (new_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
+ ++num_transient_failure_;
+ }
+}
+
// 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());
- // Only set connectivity state if this is the current subchannel list.
- if (p->subchannel_list_.get() != this) return;
- /* In priority order. The first rule to match terminates the search (ie, if we
- * are on rule n, all previous rules were unfulfilled).
- *
- * 1) RULE: ANY subchannel is READY => policy is READY.
- * CHECK: subchannel_list->num_ready > 0.
- *
- * 2) RULE: ANY subchannel is CONNECTING => policy is CONNECTING.
- * CHECK: sd->curr_connectivity_state == CONNECTING.
- *
- * 3) RULE: ALL subchannels are TRANSIENT_FAILURE => policy is
- * TRANSIENT_FAILURE.
- * CHECK: subchannel_list->num_transient_failures ==
- * subchannel_list->num_subchannels.
- */
- if (num_ready_ > 0) {
- /* 1) READY */
+void RoundRobin::RoundRobinSubchannelList::
+ MaybeUpdateRoundRobinConnectivityStateLocked() {
+ RoundRobin* p = static_cast<RoundRobin*>(policy());
+ // Only set connectivity state if this is the current subchannel list.
+ if (p->subchannel_list_.get() != this) return;
+ /* In priority order. The first rule to match terminates the search (ie, if we
+ * are on rule n, all previous rules were unfulfilled).
+ *
+ * 1) RULE: ANY subchannel is READY => policy is READY.
+ * CHECK: subchannel_list->num_ready > 0.
+ *
+ * 2) RULE: ANY subchannel is CONNECTING => policy is CONNECTING.
+ * CHECK: sd->curr_connectivity_state == CONNECTING.
+ *
+ * 3) RULE: ALL subchannels are TRANSIENT_FAILURE => policy is
+ * TRANSIENT_FAILURE.
+ * CHECK: subchannel_list->num_transient_failures ==
+ * subchannel_list->num_subchannels.
+ */
+ if (num_ready_ > 0) {
+ /* 1) READY */
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_READY, y_absl::Status(), y_absl::make_unique<Picker>(p, this));
- } else if (num_connecting_ > 0) {
- /* 2) CONNECTING */
+ } else if (num_connecting_ > 0) {
+ /* 2) CONNECTING */
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 */
+ } 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"),
@@ -338,51 +338,51 @@ void RoundRobin::RoundRobinSubchannelList::
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE, grpc_error_to_absl_status(error),
y_absl::make_unique<TransientFailurePicker>(error));
- }
-}
-
-void RoundRobin::RoundRobinSubchannelList::
- UpdateRoundRobinStateFromSubchannelStateCountsLocked() {
- RoundRobin* p = static_cast<RoundRobin*>(policy());
- if (num_ready_ > 0) {
- if (p->subchannel_list_.get() != this) {
- // Promote this list to p->subchannel_list_.
- // This list must be p->latest_pending_subchannel_list_, because
- // any previous update would have been shut down already and
- // therefore we would not be receiving a notification for them.
- GPR_ASSERT(p->latest_pending_subchannel_list_.get() == this);
- GPR_ASSERT(!shutting_down());
+ }
+}
+
+void RoundRobin::RoundRobinSubchannelList::
+ UpdateRoundRobinStateFromSubchannelStateCountsLocked() {
+ RoundRobin* p = static_cast<RoundRobin*>(policy());
+ if (num_ready_ > 0) {
+ if (p->subchannel_list_.get() != this) {
+ // Promote this list to p->subchannel_list_.
+ // This list must be p->latest_pending_subchannel_list_, because
+ // any previous update would have been shut down already and
+ // 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)) {
- const size_t old_num_subchannels =
- p->subchannel_list_ != nullptr
- ? p->subchannel_list_->num_subchannels()
- : 0;
- gpr_log(GPR_INFO,
- "[RR %p] phasing out subchannel list %p (size %" PRIuPTR
- ") in favor of %p (size %" PRIuPTR ")",
- p, p->subchannel_list_.get(), old_num_subchannels, this,
- num_subchannels());
- }
- p->subchannel_list_ = std::move(p->latest_pending_subchannel_list_);
- }
- }
- // Update the RR policy's connectivity state if needed.
- MaybeUpdateRoundRobinConnectivityStateLocked();
-}
-
-void RoundRobin::RoundRobinSubchannelData::UpdateConnectivityStateLocked(
+ const size_t old_num_subchannels =
+ p->subchannel_list_ != nullptr
+ ? p->subchannel_list_->num_subchannels()
+ : 0;
+ gpr_log(GPR_INFO,
+ "[RR %p] phasing out subchannel list %p (size %" PRIuPTR
+ ") in favor of %p (size %" PRIuPTR ")",
+ p, p->subchannel_list_.get(), old_num_subchannels, this,
+ num_subchannels());
+ }
+ p->subchannel_list_ = std::move(p->latest_pending_subchannel_list_);
+ }
+ }
+ // Update the RR policy's connectivity state if needed.
+ MaybeUpdateRoundRobinConnectivityStateLocked();
+}
+
+void RoundRobin::RoundRobinSubchannelData::UpdateConnectivityStateLocked(
grpc_connectivity_state connectivity_state) {
- RoundRobin* p = static_cast<RoundRobin*>(subchannel_list()->policy());
+ RoundRobin* p = static_cast<RoundRobin*>(subchannel_list()->policy());
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(),
+ 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
@@ -402,49 +402,49 @@ void RoundRobin::RoundRobinSubchannelData::UpdateConnectivityStateLocked(
}
}
// Record last seen connectivity state.
- last_connectivity_state_ = connectivity_state;
-}
-
-void RoundRobin::RoundRobinSubchannelData::ProcessConnectivityChangeLocked(
+ last_connectivity_state_ = connectivity_state;
+}
+
+void RoundRobin::RoundRobinSubchannelData::ProcessConnectivityChangeLocked(
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.
- // Only do this if we've started watching, not at startup time.
- // 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.
+ RoundRobin* p = static_cast<RoundRobin*>(subchannel_list()->policy());
+ GPR_ASSERT(subchannel() != nullptr);
+ // If the new state is TRANSIENT_FAILURE, re-resolve.
+ // Only do this if we've started watching, not at startup time.
+ // 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.
- if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
+ if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
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());
- }
+ 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();
- }
- // Update state counters.
+ }
+ // Update state counters.
UpdateConnectivityStateLocked(connectivity_state);
- // Update overall state and renew notification.
- subchannel_list()->UpdateRoundRobinStateFromSubchannelStateCountsLocked();
-}
-
+ // Update overall state and renew notification.
+ subchannel_list()->UpdateRoundRobinStateFromSubchannelStateCountsLocked();
+}
+
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",
+ gpr_log(GPR_INFO, "[RR %p] received update with %" PRIuPTR " addresses",
this, args.addresses.size());
- }
- // Replace latest_pending_subchannel_list_.
- if (latest_pending_subchannel_list_ != nullptr) {
+ }
+ // Replace latest_pending_subchannel_list_.
+ if (latest_pending_subchannel_list_ != nullptr) {
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());
- }
- }
- latest_pending_subchannel_list_ = MakeOrphanable<RoundRobinSubchannelList>(
+ gpr_log(GPR_INFO,
+ "[RR %p] Shutting down previous pending subchannel list %p", this,
+ latest_pending_subchannel_list_.get());
+ }
+ }
+ 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
@@ -455,51 +455,51 @@ void RoundRobin::UpdateLocked(UpdateArgs args) {
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_);
+ 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 {
+ } else {
// Start watching the pending list. It will get swapped into the
// current list when it reports READY.
- latest_pending_subchannel_list_->StartWatchingLocked();
- }
-}
-
+ latest_pending_subchannel_list_->StartWatchingLocked();
+ }
+}
+
class RoundRobinConfig : public LoadBalancingPolicy::Config {
public:
const char* name() const override { return kRoundRobin; }
};
-//
-// factory
-//
-
-class RoundRobinFactory : public LoadBalancingPolicyFactory {
- public:
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
+//
+// factory
+//
+
+class RoundRobinFactory : public LoadBalancingPolicyFactory {
+ public:
+ OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return MakeOrphanable<RoundRobin>(std::move(args));
- }
-
+ }
+
const char* name() const override { return kRoundRobin; }
RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& /*json*/, grpc_error** /*error*/) const override {
return MakeRefCounted<RoundRobinConfig>();
}
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-void grpc_lb_policy_round_robin_init() {
- grpc_core::LoadBalancingPolicyRegistry::Builder::
- RegisterLoadBalancingPolicyFactory(
+};
+
+} // namespace
+
+} // namespace grpc_core
+
+void grpc_lb_policy_round_robin_init() {
+ grpc_core::LoadBalancingPolicyRegistry::Builder::
+ RegisterLoadBalancingPolicyFactory(
y_absl::make_unique<grpc_core::RoundRobinFactory>());
-}
-
-void grpc_lb_policy_round_robin_shutdown() {}
+}
+
+void grpc_lb_policy_round_robin_shutdown() {}
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 db46cd1104e..70a51ce846c 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
@@ -1,137 +1,137 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H
+
+#include <grpc/support/port_platform.h>
+
+#include <string.h>
#include <util/system/compiler.h> // Y_NO_SANITIZE
-
-#include <grpc/support/alloc.h>
-
+
+#include <grpc/support/alloc.h>
+
#include "y_absl/container/inlined_vector.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
+#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.
-#include "src/core/ext/filters/client_channel/subchannel.h"
+#include "src/core/ext/filters/client_channel/subchannel.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"
-#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/sockaddr_utils.h"
-#include "src/core/lib/transport/connectivity_state.h"
-
-// Code for maintaining a list of subchannels within an LB policy.
-//
-// To use this, callers must create their own subclasses, like so:
-/*
-
-class MySubchannelList; // Forward declaration.
-
-class MySubchannelData
- : public SubchannelData<MySubchannelList, MySubchannelData> {
- public:
- void ProcessConnectivityChangeLocked(
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gprpp/orphanable.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/sockaddr_utils.h"
+#include "src/core/lib/transport/connectivity_state.h"
+
+// Code for maintaining a list of subchannels within an LB policy.
+//
+// To use this, callers must create their own subclasses, like so:
+/*
+
+class MySubchannelList; // Forward declaration.
+
+class MySubchannelData
+ : public SubchannelData<MySubchannelList, MySubchannelData> {
+ public:
+ void ProcessConnectivityChangeLocked(
grpc_connectivity_state connectivity_state) override {
- // ...code to handle connectivity changes...
- }
-};
-
-class MySubchannelList
- : public SubchannelList<MySubchannelList, MySubchannelData> {
-};
-
-*/
+ // ...code to handle connectivity changes...
+ }
+};
+
+class MySubchannelList
+ : public SubchannelList<MySubchannelList, MySubchannelData> {
+};
+
+*/
// All methods will be called from within the client_channel work serializer.
-
-namespace grpc_core {
-
+
+namespace grpc_core {
+
// Forward declaration.
template <typename SubchannelListType, typename SubchannelDataType>
class SubchannelList;
-// Stores data for a particular subchannel in a subchannel list.
-// Callers must create a subclass that implements the
-// ProcessConnectivityChangeLocked() method.
-template <typename SubchannelListType, typename SubchannelDataType>
-class SubchannelData {
- public:
- // Returns a pointer to the subchannel list containing this object.
+// Stores data for a particular subchannel in a subchannel list.
+// Callers must create a subclass that implements the
+// ProcessConnectivityChangeLocked() method.
+template <typename SubchannelListType, typename SubchannelDataType>
+class SubchannelData {
+ public:
+ // Returns a pointer to the subchannel list containing this object.
SubchannelListType* subchannel_list() const {
return static_cast<SubchannelListType*>(subchannel_list_);
}
-
- // Returns the index into the subchannel list of this object.
- size_t Index() const {
- return static_cast<size_t>(static_cast<const SubchannelDataType*>(this) -
- subchannel_list_->subchannel(0));
- }
-
- // Returns a pointer to the subchannel.
+
+ // Returns the index into the subchannel list of this object.
+ size_t Index() const {
+ return static_cast<size_t>(static_cast<const SubchannelDataType*>(this) -
+ subchannel_list_->subchannel(0));
+ }
+
+ // Returns a pointer to the subchannel.
SubchannelInterface* subchannel() const { return subchannel_.get(); }
-
- // Synchronously checks the subchannel's connectivity state.
- // Must not be called while there is a connectivity notification
+
+ // 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_;
- }
-
+ }
+
// Resets the connection backoff.
// TODO(roth): This method should go away when we move the backoff
// code out of the subchannel and into the LB policies.
void ResetBackoffLocked();
-
- // Starts watching the connectivity state of the subchannel.
+
+ // Starts watching the connectivity state of the subchannel.
// ProcessConnectivityChangeLocked() will be called whenever the
- // connectivity state changes.
- void StartConnectivityWatchLocked();
-
- // Cancels watching the connectivity state of the subchannel.
- void CancelConnectivityWatchLocked(const char* reason);
-
- // Cancels any pending connectivity watch and unrefs the subchannel.
- void ShutdownLocked();
-
- protected:
+ // connectivity state changes.
+ void StartConnectivityWatchLocked();
+
+ // Cancels watching the connectivity state of the subchannel.
+ void CancelConnectivityWatchLocked(const char* reason);
+
+ // Cancels any pending connectivity watch and unrefs the subchannel.
+ void ShutdownLocked();
+
+ protected:
SubchannelData(
SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list,
const ServerAddress& address,
RefCountedPtr<SubchannelInterface> subchannel);
-
- virtual ~SubchannelData();
-
+
+ virtual ~SubchannelData();
+
// After StartConnectivityWatchLocked() is called, this method will be
// invoked whenever the subchannel's connectivity state changes.
// To stop watching, use CancelConnectivityWatchLocked().
- virtual void ProcessConnectivityChangeLocked(
+ virtual void ProcessConnectivityChangeLocked(
grpc_connectivity_state connectivity_state) = 0;
-
+
private:
// Watcher for subchannel connectivity state.
class Watcher
@@ -159,7 +159,7 @@ class SubchannelData {
// Unrefs the subchannel.
void UnrefSubchannelLocked(const char* reason);
- // Backpointer to owning subchannel list. Not owned.
+ // Backpointer to owning subchannel list. Not owned.
SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list_;
// The subchannel.
RefCountedPtr<SubchannelInterface> subchannel_;
@@ -168,70 +168,70 @@ class SubchannelData {
nullptr;
// Data updated by the watcher.
grpc_connectivity_state connectivity_state_;
-};
-
-// A list of subchannels.
-template <typename SubchannelListType, typename SubchannelDataType>
+};
+
+// A list of subchannels.
+template <typename SubchannelListType, typename SubchannelDataType>
class SubchannelList : public InternallyRefCounted<SubchannelListType> {
- public:
+ public:
typedef y_absl::InlinedVector<SubchannelDataType, 10> SubchannelVector;
-
- // The number of subchannels in the list.
- size_t num_subchannels() const { return subchannels_.size(); }
-
- // The data for the subchannel at a particular index.
- SubchannelDataType* subchannel(size_t index) { return &subchannels_[index]; }
-
- // Returns true if the subchannel list is shutting down.
- bool shutting_down() const { return shutting_down_; }
-
- // Accessors.
- LoadBalancingPolicy* policy() const { return policy_; }
- TraceFlag* tracer() const { return tracer_; }
-
+
+ // The number of subchannels in the list.
+ size_t num_subchannels() const { return subchannels_.size(); }
+
+ // The data for the subchannel at a particular index.
+ SubchannelDataType* subchannel(size_t index) { return &subchannels_[index]; }
+
+ // Returns true if the subchannel list is shutting down.
+ bool shutting_down() const { return shutting_down_; }
+
+ // Accessors.
+ LoadBalancingPolicy* policy() const { return policy_; }
+ TraceFlag* tracer() const { return tracer_; }
+
// Resets connection backoff of all subchannels.
// TODO(roth): We will probably need to rethink this as part of moving
// the backoff code out of subchannels and into LB policies.
void ResetBackoffLocked();
- void Orphan() override {
- ShutdownLocked();
+ void Orphan() override {
+ ShutdownLocked();
InternallyRefCounted<SubchannelListType>::Unref(DEBUG_LOCATION, "shutdown");
- }
-
- protected:
- SubchannelList(LoadBalancingPolicy* policy, TraceFlag* tracer,
+ }
+
+ protected:
+ SubchannelList(LoadBalancingPolicy* policy, TraceFlag* tracer,
ServerAddressList addresses,
LoadBalancingPolicy::ChannelControlHelper* helper,
- const grpc_channel_args& args);
-
- virtual ~SubchannelList();
-
- private:
- // For accessing Ref() and Unref().
- friend class SubchannelData<SubchannelListType, SubchannelDataType>;
-
- void ShutdownLocked();
-
- // Backpointer to owning policy.
- LoadBalancingPolicy* policy_;
-
- TraceFlag* tracer_;
-
- // The list of subchannels.
- SubchannelVector subchannels_;
-
- // Is this list shutting down? This may be true due to the shutdown of the
- // policy itself or because a newer update has arrived while this one hadn't
- // finished processing.
- bool shutting_down_ = false;
-};
-
-//
-// implementation -- no user-servicable parts below
-//
-
-//
+ const grpc_channel_args& args);
+
+ virtual ~SubchannelList();
+
+ private:
+ // For accessing Ref() and Unref().
+ friend class SubchannelData<SubchannelListType, SubchannelDataType>;
+
+ void ShutdownLocked();
+
+ // Backpointer to owning policy.
+ LoadBalancingPolicy* policy_;
+
+ TraceFlag* tracer_;
+
+ // The list of subchannels.
+ SubchannelVector subchannels_;
+
+ // Is this list shutting down? This may be true due to the shutdown of the
+ // policy itself or because a newer update has arrived while this one hadn't
+ // finished processing.
+ bool shutting_down_ = false;
+};
+
+//
+// implementation -- no user-servicable parts below
+//
+
+//
// SubchannelData::Watcher
//
@@ -259,43 +259,43 @@ void SubchannelData<SubchannelListType, SubchannelDataType>::Watcher::
}
//
-// SubchannelData
-//
-
-template <typename SubchannelListType, typename SubchannelDataType>
-SubchannelData<SubchannelListType, SubchannelDataType>::SubchannelData(
+// SubchannelData
+//
+
+template <typename SubchannelListType, typename SubchannelDataType>
+SubchannelData<SubchannelListType, SubchannelDataType>::SubchannelData(
SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list,
const ServerAddress& /*address*/,
RefCountedPtr<SubchannelInterface> subchannel)
- : subchannel_list_(subchannel_list),
+ : subchannel_list_(subchannel_list),
subchannel_(std::move(subchannel)),
- // We assume that the current state is IDLE. If not, we'll get a
- // callback telling us that.
+ // We assume that the current state is IDLE. If not, we'll get a
+ // callback telling us that.
connectivity_state_(GRPC_CHANNEL_IDLE) {}
-
-template <typename SubchannelListType, typename SubchannelDataType>
-SubchannelData<SubchannelListType, SubchannelDataType>::~SubchannelData() {
+
+template <typename SubchannelListType, typename SubchannelDataType>
+SubchannelData<SubchannelListType, SubchannelDataType>::~SubchannelData() {
GPR_ASSERT(subchannel_ == nullptr);
-}
-
-template <typename SubchannelListType, typename SubchannelDataType>
-void SubchannelData<SubchannelListType, SubchannelDataType>::
- UnrefSubchannelLocked(const char* reason) {
- if (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())) {
- gpr_log(GPR_INFO,
- "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
+ gpr_log(GPR_INFO,
+ "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
" (subchannel %p): unreffing subchannel (%s)",
- subchannel_list_->tracer()->name(), subchannel_list_->policy(),
- subchannel_list_, Index(), subchannel_list_->num_subchannels(),
+ subchannel_list_->tracer()->name(), subchannel_list_->policy(),
+ subchannel_list_, Index(), subchannel_list_->num_subchannels(),
subchannel_.get(), reason);
- }
+ }
subchannel_.reset();
- }
-}
-
-template <typename SubchannelListType, typename SubchannelDataType>
-void SubchannelData<SubchannelListType,
+ }
+}
+
+template <typename SubchannelListType, typename SubchannelDataType>
+void SubchannelData<SubchannelListType,
SubchannelDataType>::ResetBackoffLocked() {
if (subchannel_ != nullptr) {
subchannel_->ResetBackoff();
@@ -304,15 +304,15 @@ void SubchannelData<SubchannelListType,
template <typename SubchannelListType, typename SubchannelDataType>
void SubchannelData<SubchannelListType,
- SubchannelDataType>::StartConnectivityWatchLocked() {
+ SubchannelDataType>::StartConnectivityWatchLocked() {
if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) {
- gpr_log(GPR_INFO,
- "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
+ gpr_log(GPR_INFO,
+ "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR
" (subchannel %p): starting watch (from %s)",
- subchannel_list_->tracer()->name(), subchannel_list_->policy(),
- subchannel_list_, Index(), subchannel_list_->num_subchannels(),
+ subchannel_list_->tracer()->name(), subchannel_list_->policy(),
+ subchannel_list_, Index(), subchannel_list_->num_subchannels(),
subchannel_.get(), ConnectivityStateName(connectivity_state_));
- }
+ }
GPR_ASSERT(pending_watcher_ == nullptr);
pending_watcher_ =
new Watcher(this, subchannel_list()->Ref(DEBUG_LOCATION, "Watcher"));
@@ -320,96 +320,96 @@ void SubchannelData<SubchannelListType,
connectivity_state_,
std::unique_ptr<SubchannelInterface::ConnectivityStateWatcherInterface>(
pending_watcher_));
-}
-
-template <typename SubchannelListType, typename SubchannelDataType>
-void SubchannelData<SubchannelListType, SubchannelDataType>::
- CancelConnectivityWatchLocked(const char* reason) {
+}
+
+template <typename SubchannelListType, typename SubchannelDataType>
+void SubchannelData<SubchannelListType, SubchannelDataType>::
+ CancelConnectivityWatchLocked(const char* reason) {
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(),
+ 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);
- }
+ }
if (pending_watcher_ != nullptr) {
subchannel_->CancelConnectivityStateWatch(pending_watcher_);
pending_watcher_ = nullptr;
- }
-}
-
-template <typename SubchannelListType, typename SubchannelDataType>
-void SubchannelData<SubchannelListType, SubchannelDataType>::ShutdownLocked() {
+ }
+}
+
+template <typename SubchannelListType, typename SubchannelDataType>
+void SubchannelData<SubchannelListType, SubchannelDataType>::ShutdownLocked() {
if (pending_watcher_ != nullptr) CancelConnectivityWatchLocked("shutdown");
UnrefSubchannelLocked("shutdown");
-}
-
-//
-// SubchannelList
-//
-
-template <typename SubchannelListType, typename SubchannelDataType>
-SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList(
+}
+
+//
+// SubchannelList
+//
+
+template <typename SubchannelListType, typename SubchannelDataType>
+SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList(
LoadBalancingPolicy* policy, TraceFlag* tracer, ServerAddressList addresses,
LoadBalancingPolicy::ChannelControlHelper* helper,
const grpc_channel_args& args) Y_NO_SANITIZE("undefined")
: InternallyRefCounted<SubchannelListType>(tracer),
- policy_(policy),
+ policy_(policy),
tracer_(tracer) {
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO,
- "[%s %p] Creating subchannel list %p for %" PRIuPTR " subchannels",
+ gpr_log(GPR_INFO,
+ "[%s %p] Creating subchannel list %p for %" PRIuPTR " subchannels",
tracer_->name(), policy, this, addresses.size());
- }
+ }
subchannels_.reserve(addresses.size());
- // Create a subchannel for each address.
+ // Create a subchannel for each address.
for (const ServerAddress& address : addresses) {
RefCountedPtr<SubchannelInterface> subchannel =
helper->CreateSubchannel(std::move(address), args);
- if (subchannel == nullptr) {
- // Subchannel could not be created.
+ if (subchannel == nullptr) {
+ // Subchannel could not be created.
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"[%s %p] could not create subchannel for address %s, "
- "ignoring",
+ "ignoring",
tracer_->name(), policy_, address.ToString().c_str());
- }
- continue;
- }
+ }
+ continue;
+ }
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO,
- "[%s %p] subchannel list %p index %" PRIuPTR
+ gpr_log(GPR_INFO,
+ "[%s %p] subchannel list %p index %" PRIuPTR
": Created subchannel %p for address %s",
tracer_->name(), policy_, this, subchannels_.size(),
subchannel.get(), address.ToString().c_str());
- }
+ }
subchannels_.emplace_back(this, address, std::move(subchannel));
- }
-}
-
-template <typename SubchannelListType, typename SubchannelDataType>
-SubchannelList<SubchannelListType, SubchannelDataType>::~SubchannelList() {
+ }
+}
+
+template <typename SubchannelListType, typename SubchannelDataType>
+SubchannelList<SubchannelListType, SubchannelDataType>::~SubchannelList() {
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO, "[%s %p] Destroying subchannel_list %p", tracer_->name(),
- policy_, this);
- }
-}
-
-template <typename SubchannelListType, typename SubchannelDataType>
-void SubchannelList<SubchannelListType, SubchannelDataType>::ShutdownLocked() {
+ gpr_log(GPR_INFO, "[%s %p] Destroying subchannel_list %p", tracer_->name(),
+ policy_, this);
+ }
+}
+
+template <typename SubchannelListType, typename SubchannelDataType>
+void SubchannelList<SubchannelListType, SubchannelDataType>::ShutdownLocked() {
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
- gpr_log(GPR_INFO, "[%s %p] Shutting down subchannel_list %p",
- tracer_->name(), policy_, this);
- }
- GPR_ASSERT(!shutting_down_);
- shutting_down_ = true;
- for (size_t i = 0; i < subchannels_.size(); i++) {
- SubchannelDataType* sd = &subchannels_[i];
- sd->ShutdownLocked();
- }
-}
-
+ gpr_log(GPR_INFO, "[%s %p] Shutting down subchannel_list %p",
+ tracer_->name(), policy_, this);
+ }
+ GPR_ASSERT(!shutting_down_);
+ shutting_down_ = true;
+ for (size_t i = 0; i < subchannels_.size(); i++) {
+ SubchannelDataType* sd = &subchannels_[i];
+ sd->ShutdownLocked();
+ }
+}
+
template <typename SubchannelListType, typename SubchannelDataType>
void SubchannelList<SubchannelListType,
SubchannelDataType>::ResetBackoffLocked() {
@@ -419,6 +419,6 @@ void SubchannelList<SubchannelListType,
}
}
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H */
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H */
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 9e4425fa447..e8e10eec6db 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
@@ -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_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_FACTORY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_FACTORY_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy.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_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_FACTORY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_FACTORY_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy.h"
#include "src/core/lib/gprpp/orphanable.h"
-
-namespace grpc_core {
-
-class LoadBalancingPolicyFactory {
- public:
+
+namespace grpc_core {
+
+class LoadBalancingPolicyFactory {
+ public:
virtual ~LoadBalancingPolicyFactory() {}
- /// Returns a new LB policy instance.
- virtual OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
+ /// Returns a new LB policy instance.
+ virtual OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args) const = 0;
-
- /// Returns the LB policy name that this factory provides.
- /// Caller does NOT take ownership of result.
+
+ /// Returns the LB policy name that this factory provides.
+ /// Caller does NOT take ownership of result.
virtual const char* name() const = 0;
-
+
virtual RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** error) const = 0;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_FACTORY_H */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_FACTORY_H */
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 463e54a2e6c..81a41cb524b 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy_registry.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/lb_policy_registry.h"
+
+#include <string.h>
+
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include "src/core/lib/gpr/string.h"
-
-namespace grpc_core {
-
-namespace {
-
-class RegistryState {
- public:
- RegistryState() {}
-
- void RegisterLoadBalancingPolicyFactory(
+#include "src/core/lib/gpr/string.h"
+
+namespace grpc_core {
+
+namespace {
+
+class RegistryState {
+ public:
+ RegistryState() {}
+
+ void RegisterLoadBalancingPolicyFactory(
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) {
- GPR_ASSERT(strcmp(factories_[i]->name(), factory->name()) != 0);
- }
- factories_.push_back(std::move(factory));
- }
-
- LoadBalancingPolicyFactory* GetLoadBalancingPolicyFactory(
- const char* name) const {
- for (size_t i = 0; i < factories_.size(); ++i) {
- if (strcmp(name, factories_[i]->name()) == 0) {
- return factories_[i].get();
- }
- }
- return nullptr;
- }
-
- private:
+ for (size_t i = 0; i < factories_.size(); ++i) {
+ GPR_ASSERT(strcmp(factories_[i]->name(), factory->name()) != 0);
+ }
+ factories_.push_back(std::move(factory));
+ }
+
+ LoadBalancingPolicyFactory* GetLoadBalancingPolicyFactory(
+ const char* name) const {
+ for (size_t i = 0; i < factories_.size(); ++i) {
+ if (strcmp(name, factories_[i]->name()) == 0) {
+ return factories_[i].get();
+ }
+ }
+ return nullptr;
+ }
+
+ private:
y_absl::InlinedVector<std::unique_ptr<LoadBalancingPolicyFactory>, 10>
factories_;
-};
-
-RegistryState* g_state = nullptr;
-
-} // namespace
-
-//
-// LoadBalancingPolicyRegistry::Builder
-//
-
-void LoadBalancingPolicyRegistry::Builder::InitRegistry() {
+};
+
+RegistryState* g_state = nullptr;
+
+} // namespace
+
+//
+// LoadBalancingPolicyRegistry::Builder
+//
+
+void LoadBalancingPolicyRegistry::Builder::InitRegistry() {
if (g_state == nullptr) g_state = new RegistryState();
-}
-
-void LoadBalancingPolicyRegistry::Builder::ShutdownRegistry() {
+}
+
+void LoadBalancingPolicyRegistry::Builder::ShutdownRegistry() {
delete g_state;
- g_state = nullptr;
-}
-
-void LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
+ g_state = nullptr;
+}
+
+void LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
std::unique_ptr<LoadBalancingPolicyFactory> factory) {
- InitRegistry();
- g_state->RegisterLoadBalancingPolicyFactory(std::move(factory));
-}
-
-//
-// LoadBalancingPolicyRegistry
-//
-
-OrphanablePtr<LoadBalancingPolicy>
-LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
+ InitRegistry();
+ g_state->RegisterLoadBalancingPolicyFactory(std::move(factory));
+}
+
+//
+// LoadBalancingPolicyRegistry
+//
+
+OrphanablePtr<LoadBalancingPolicy>
+LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
const char* name, LoadBalancingPolicy::Args args) {
- GPR_ASSERT(g_state != nullptr);
- // Find factory.
- LoadBalancingPolicyFactory* factory =
- g_state->GetLoadBalancingPolicyFactory(name);
- if (factory == nullptr) return nullptr; // Specified name not found.
- // Create policy via factory.
+ GPR_ASSERT(g_state != nullptr);
+ // Find factory.
+ LoadBalancingPolicyFactory* factory =
+ g_state->GetLoadBalancingPolicyFactory(name);
+ if (factory == nullptr) return nullptr; // Specified name not found.
+ // Create policy via factory.
return factory->CreateLoadBalancingPolicy(std::move(args));
-}
-
+}
+
bool LoadBalancingPolicyRegistry::LoadBalancingPolicyExists(
const char* name, bool* requires_config) {
GPR_ASSERT(g_state != nullptr);
@@ -185,4 +185,4 @@ LoadBalancingPolicyRegistry::ParseLoadBalancingConfig(const Json& json,
return factory->ParseLoadBalancingConfig(policy->second, error);
}
-} // namespace grpc_core
+} // 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 8d2e3e395d5..f46d9785e33 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
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_REGISTRY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_REGISTRY_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/orphanable.h"
-
-namespace grpc_core {
-
-class LoadBalancingPolicyRegistry {
- public:
- /// Methods used to create and populate the LoadBalancingPolicyRegistry.
- /// NOT THREAD SAFE -- to be used only during global gRPC
- /// initialization and shutdown.
- class Builder {
- public:
- /// Global initialization and shutdown hooks.
- static void InitRegistry();
- static void ShutdownRegistry();
-
- /// 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(
+/*
+ *
+ * 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_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_REGISTRY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_REGISTRY_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/orphanable.h"
+
+namespace grpc_core {
+
+class LoadBalancingPolicyRegistry {
+ public:
+ /// Methods used to create and populate the LoadBalancingPolicyRegistry.
+ /// NOT THREAD SAFE -- to be used only during global gRPC
+ /// initialization and shutdown.
+ class Builder {
+ public:
+ /// Global initialization and shutdown hooks.
+ static void InitRegistry();
+ static void ShutdownRegistry();
+
+ /// 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);
- };
-
- /// Creates an LB policy of the type specified by \a name.
- static OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
+ };
+
+ /// Creates an LB policy of the type specified by \a name.
+ static OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
const char* name, LoadBalancingPolicy::Args args);
/// Returns true if the LB policy factory specified by \a name exists in this
@@ -58,8 +58,8 @@ class LoadBalancingPolicyRegistry {
/// LoadBalancingConfig array \a json.
static RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** error);
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_REGISTRY_H */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_REGISTRY_H */
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 3e297d9a6f0..2d569c55f3c 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
@@ -1,54 +1,54 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/grpc_types.h>
-
-#include "src/core/lib/iomgr/resolve_address.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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/impl/codegen/grpc_types.h>
+
+#include "src/core/lib/iomgr/resolve_address.h"
+
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.
+ /// 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;
- /// 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.
+ /// 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;
-};
-
+};
+
} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_H */
+
+#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 2fc25725258..252ef34e688 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
@@ -1,35 +1,35 @@
-/*
- *
- * 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/ext/filters/client_channel/proxy_mapper_registry.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/proxy_mapper_registry.h"
+
#include <memory>
#include <vector>
-
+
namespace grpc_core {
-
+
namespace {
-
+
using ProxyMapperList = std::vector<std::unique_ptr<ProxyMapperInterface>>;
ProxyMapperList* g_proxy_mapper_list;
-
+
} // namespace
void ProxyMapperRegistry::Init() {
@@ -52,14 +52,14 @@ void ProxyMapperRegistry::Shutdown() {
void ProxyMapperRegistry::Register(
bool at_start, std::unique_ptr<ProxyMapperInterface> mapper) {
Init();
- if (at_start) {
+ if (at_start) {
g_proxy_mapper_list->insert(g_proxy_mapper_list->begin(),
std::move(mapper));
- } else {
+ } else {
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,
@@ -67,12 +67,12 @@ bool ProxyMapperRegistry::MapName(const char* server_uri,
Init();
for (const auto& mapper : *g_proxy_mapper_list) {
if (mapper->MapName(server_uri, args, name_to_resolve, new_args)) {
- return true;
- }
- }
- return false;
-}
-
+ return true;
+ }
+ }
+ return false;
+}
+
bool ProxyMapperRegistry::MapAddress(const grpc_resolved_address& address,
const grpc_channel_args* args,
grpc_resolved_address** new_address,
@@ -80,10 +80,10 @@ bool ProxyMapperRegistry::MapAddress(const grpc_resolved_address& address,
Init();
for (const auto& mapper : *g_proxy_mapper_list) {
if (mapper->MapAddress(address, args, new_address, new_args)) {
- return true;
- }
- }
- return false;
-}
-
+ return true;
+ }
+ }
+ return false;
+}
+
} // 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 b6273e1adf5..3bb9efd45d8 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
@@ -1,44 +1,44 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_REGISTRY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_REGISTRY_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/proxy_mapper.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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_REGISTRY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_REGISTRY_H
+
+#include <grpc/support/port_platform.h>
+
+#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,
@@ -47,4 +47,4 @@ class ProxyMapperRegistry {
} // namespace grpc_core
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_REGISTRY_H */
+#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 4a76a7d7bdc..aaf7cb1e324 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/resolver.h"
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_resolver_refcount(false,
- "resolver_refcount");
-
-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 <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/resolver.h"
+
+grpc_core::DebugOnlyTraceFlag grpc_trace_resolver_refcount(false,
+ "resolver_refcount");
+
+namespace grpc_core {
+
//
// Resolver
//
@@ -34,7 +34,7 @@ Resolver::Resolver(std::shared_ptr<WorkSerializer> work_serializer,
: InternallyRefCounted(&grpc_trace_resolver_refcount),
work_serializer_(std::move(work_serializer)),
result_handler_(std::move(result_handler)) {}
-
+
//
// Resolver::Result
//
@@ -82,4 +82,4 @@ Resolver::Result& Resolver::Result::operator=(Result&& other) noexcept {
return *this;
}
-} // namespace grpc_core
+} // 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 de941a063b4..19664ad0f65 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
@@ -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_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/grpc_types.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_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_H
+
+#include <grpc/support/port_platform.h>
+
+#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/lib/gprpp/orphanable.h"
+#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/work_serializer.h"
-
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_resolver_refcount;
-
-namespace grpc_core {
-
-/// Interface for name resolution.
-///
-/// This interface is designed to support both push-based and pull-based
-/// mechanisms. A push-based mechanism is one where the resolver will
-/// subscribe to updates for a given name, and the name service will
-/// proactively send new data to the resolver whenever the data associated
-/// with the name changes. A pull-based mechanism is one where the resolver
-/// needs to query the name service again to get updated information (e.g.,
-/// DNS).
-///
-/// Note: All methods with a "Locked" suffix must be called from the
+
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_resolver_refcount;
+
+namespace grpc_core {
+
+/// Interface for name resolution.
+///
+/// This interface is designed to support both push-based and pull-based
+/// mechanisms. A push-based mechanism is one where the resolver will
+/// subscribe to updates for a given name, and the name service will
+/// proactively send new data to the resolver whenever the data associated
+/// with the name changes. A pull-based mechanism is one where the resolver
+/// needs to query the name service again to get updated information (e.g.,
+/// DNS).
+///
+/// Note: All methods with a "Locked" suffix must be called from the
/// work_serializer passed to the constructor.
class Resolver : public InternallyRefCounted<Resolver> {
- public:
+ public:
/// Results returned by the resolver.
struct Result {
ServerAddressList addresses;
@@ -84,29 +84,29 @@ class Resolver : public InternallyRefCounted<Resolver> {
// changes, add a method to parse the service config JSON string.
};
- // Not copyable nor movable.
- Resolver(const Resolver&) = delete;
- Resolver& operator=(const Resolver&) = delete;
+ // Not copyable nor movable.
+ Resolver(const Resolver&) = delete;
+ Resolver& operator=(const Resolver&) = delete;
virtual ~Resolver() = default;
-
+
/// Starts resolving.
virtual void StartLocked() = 0;
-
- /// Asks the resolver to obtain an updated resolver result, if
- /// applicable.
- ///
- /// This is useful for pull-based implementations to decide when to
- /// re-resolve. However, the implementation is not required to
- /// re-resolve immediately upon receiving this call; it may instead
- /// elect to delay based on some configured minimum time between
- /// queries, to avoid hammering the name service with queries.
- ///
- /// For push-based implementations, this may be a no-op.
- ///
+
+ /// Asks the resolver to obtain an updated resolver result, if
+ /// applicable.
+ ///
+ /// This is useful for pull-based implementations to decide when to
+ /// re-resolve. However, the implementation is not required to
+ /// re-resolve immediately upon receiving this call; it may instead
+ /// elect to delay based on some configured minimum time between
+ /// queries, to avoid hammering the name service with queries.
+ ///
+ /// For push-based implementations, this may be a no-op.
+ ///
/// Note: Implementations must not invoke any method on the
/// ResultHandler from within this call.
virtual void RequestReresolutionLocked() {}
-
+
/// Resets the re-resolution backoff, if any.
/// This needs to be implemented only by pull-based implementations;
/// for push-based implementations, it will be a no-op.
@@ -116,29 +116,29 @@ class Resolver : public InternallyRefCounted<Resolver> {
virtual void ResetBackoffLocked() {}
// Note: This must be invoked while holding the work_serializer.
- void Orphan() override {
+ void Orphan() override {
ShutdownLocked();
Unref();
- }
-
- protected:
+ }
+
+ protected:
Resolver(std::shared_ptr<WorkSerializer> work_serializer,
std::unique_ptr<ResultHandler> result_handler);
-
+
/// 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(); }
-
- private:
+
+ private:
std::shared_ptr<WorkSerializer> work_serializer_;
std::unique_ptr<ResultHandler> result_handler_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_H */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/README.md b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/README.md
index b0e234e96a5..c7ebce4cf9a 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/README.md
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/README.md
@@ -1,4 +1,4 @@
-# Resolver
-
-Implementations of various name resolution schemes.
-See the [naming spec](/doc/naming.md).
+# Resolver
+
+Implementations of various name resolution schemes.
+See the [naming spec](/doc/naming.md).
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 43d638ab3f1..6875b653db7 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
@@ -1,197 +1,197 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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>
+
#if GRPC_ARES == 1
-
-#include <limits.h>
-#include <stdio.h>
-#include <string.h>
-
+
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include <address_sorting/address_sorting.h>
-
-#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include <address_sorting/address_sorting.h>
+
+#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
#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/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_registry.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/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/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/resolve_address.h"
-#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/iomgr/work_serializer.h"
-#include "src/core/lib/json/json.h"
-
-#define GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS 1
-#define GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER 1.6
-#define GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS 120
-#define GRPC_DNS_RECONNECT_JITTER 0.2
-
-namespace grpc_core {
-
-namespace {
-
-const char kDefaultPort[] = "https";
-
-class AresDnsResolver : public Resolver {
- public:
+#include "src/core/lib/json/json.h"
+
+#define GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS 1
+#define GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER 1.6
+#define GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS 120
+#define GRPC_DNS_RECONNECT_JITTER 0.2
+
+namespace grpc_core {
+
+namespace {
+
+const char kDefaultPort[] = "https";
+
+class AresDnsResolver : public Resolver {
+ public:
explicit AresDnsResolver(ResolverArgs args);
-
+
void StartLocked() override;
-
- void RequestReresolutionLocked() override;
-
+
+ void RequestReresolutionLocked() override;
+
void ResetBackoffLocked() override;
- void ShutdownLocked() override;
-
- private:
- virtual ~AresDnsResolver();
-
- void MaybeStartResolvingLocked();
- void StartResolvingLocked();
-
+ void ShutdownLocked() override;
+
+ private:
+ virtual ~AresDnsResolver();
+
+ void MaybeStartResolvingLocked();
+ void StartResolvingLocked();
+
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);
-
- /// DNS server to use (if not system default)
- char* dns_server_;
- /// name to resolve (usually the same as target_name)
- char* name_to_resolve_;
- /// channel args
- grpc_channel_args* channel_args_;
- /// whether to request the service config
- bool request_service_config_;
- /// pollset_set to drive the name resolution process
- grpc_pollset_set* interested_parties_;
+
+ /// DNS server to use (if not system default)
+ char* dns_server_;
+ /// name to resolve (usually the same as target_name)
+ char* name_to_resolve_;
+ /// channel args
+ grpc_channel_args* channel_args_;
+ /// whether to request the service config
+ bool request_service_config_;
+ /// pollset_set to drive the name resolution process
+ grpc_pollset_set* interested_parties_;
/// closures used by the work_serializer
- grpc_closure on_next_resolution_;
- grpc_closure on_resolved_;
- /// are we currently resolving?
- bool resolving_ = false;
- /// the pending resolving request
- grpc_ares_request* pending_request_ = nullptr;
- /// next resolution timer
- bool have_next_resolution_timer_ = false;
- grpc_timer next_resolution_timer_;
- /// min interval between DNS requests
- grpc_millis min_time_between_resolutions_;
- /// timestamp of last DNS request
- grpc_millis last_resolution_timestamp_ = -1;
- /// retry backoff state
- BackOff backoff_;
+ grpc_closure on_next_resolution_;
+ grpc_closure on_resolved_;
+ /// are we currently resolving?
+ bool resolving_ = false;
+ /// the pending resolving request
+ grpc_ares_request* pending_request_ = nullptr;
+ /// next resolution timer
+ bool have_next_resolution_timer_ = false;
+ grpc_timer next_resolution_timer_;
+ /// min interval between DNS requests
+ grpc_millis min_time_between_resolutions_;
+ /// timestamp of last DNS request
+ grpc_millis last_resolution_timestamp_ = -1;
+ /// retry backoff state
+ BackOff backoff_;
/// currently resolving backend addresses
std::unique_ptr<ServerAddressList> addresses_;
/// currently resolving balancer addresses
std::unique_ptr<ServerAddressList> balancer_addresses_;
- /// currently resolving service config
- char* service_config_json_ = nullptr;
+ /// currently resolving service config
+ char* service_config_json_ = nullptr;
// has shutdown been initiated
bool shutdown_initiated_ = false;
// timeout in milliseconds for active DNS queries
int query_timeout_ms_;
// whether or not to enable SRV DNS queries
bool enable_srv_queries_;
-};
-
+};
+
AresDnsResolver::AresDnsResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer), std::move(args.result_handler)),
- backoff_(
- BackOff::Options()
- .set_initial_backoff(GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS *
- 1000)
- .set_multiplier(GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER)
- .set_jitter(GRPC_DNS_RECONNECT_JITTER)
- .set_max_backoff(GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000)) {
+ backoff_(
+ BackOff::Options()
+ .set_initial_backoff(GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS *
+ 1000)
+ .set_multiplier(GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER)
+ .set_jitter(GRPC_DNS_RECONNECT_JITTER)
+ .set_max_backoff(GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000)) {
// Closure Initialization
GRPC_CLOSURE_INIT(&on_next_resolution_, OnNextResolution, this,
grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&on_resolved_, OnResolved, this, grpc_schedule_on_exec_ctx);
- // Get name to resolve from URI path.
- const char* path = args.uri->path;
- if (path[0] == '/') ++path;
- name_to_resolve_ = gpr_strdup(path);
- // Get DNS server from URI authority.
- dns_server_ = nullptr;
- if (0 != strcmp(args.uri->authority, "")) {
- dns_server_ = gpr_strdup(args.uri->authority);
- }
- channel_args_ = grpc_channel_args_copy(args.args);
+ // Get name to resolve from URI path.
+ const char* path = args.uri->path;
+ if (path[0] == '/') ++path;
+ name_to_resolve_ = gpr_strdup(path);
+ // Get DNS server from URI authority.
+ dns_server_ = nullptr;
+ if (0 != strcmp(args.uri->authority, "")) {
+ dns_server_ = gpr_strdup(args.uri->authority);
+ }
+ channel_args_ = grpc_channel_args_copy(args.args);
// Disable service config option
- const grpc_arg* arg = grpc_channel_args_find(
- channel_args_, GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION);
+ const grpc_arg* arg = grpc_channel_args_find(
+ channel_args_, GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION);
request_service_config_ = !grpc_channel_arg_get_bool(arg, true);
// Min time b/t resolutions option
- arg = grpc_channel_args_find(channel_args_,
- GRPC_ARG_DNS_MIN_TIME_BETWEEN_RESOLUTIONS_MS);
- min_time_between_resolutions_ =
+ 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});
// 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);
- interested_parties_ = grpc_pollset_set_create();
- if (args.pollset_set != nullptr) {
- grpc_pollset_set_add_pollset_set(interested_parties_, args.pollset_set);
- }
+ interested_parties_ = grpc_pollset_set_create();
+ 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(
query_timeout_ms_arg,
{GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS, 0, INT_MAX});
-}
-
-AresDnsResolver::~AresDnsResolver() {
+}
+
+AresDnsResolver::~AresDnsResolver() {
GRPC_CARES_TRACE_LOG("resolver:%p destroying AresDnsResolver", this);
- grpc_pollset_set_destroy(interested_parties_);
- gpr_free(dns_server_);
- gpr_free(name_to_resolve_);
- grpc_channel_args_destroy(channel_args_);
-}
-
+ grpc_pollset_set_destroy(interested_parties_);
+ gpr_free(dns_server_);
+ gpr_free(name_to_resolve_);
+ grpc_channel_args_destroy(channel_args_);
+}
+
void AresDnsResolver::StartLocked() {
GRPC_CARES_TRACE_LOG("resolver:%p AresDnsResolver::StartLocked() is called.",
this);
MaybeStartResolvingLocked();
-}
-
-void AresDnsResolver::RequestReresolutionLocked() {
- if (!resolving_) {
- MaybeStartResolvingLocked();
- }
-}
-
+}
+
+void AresDnsResolver::RequestReresolutionLocked() {
+ if (!resolving_) {
+ MaybeStartResolvingLocked();
+ }
+}
+
void AresDnsResolver::ResetBackoffLocked() {
if (have_next_resolution_timer_) {
grpc_timer_cancel(&next_resolution_timer_);
@@ -199,16 +199,16 @@ void AresDnsResolver::ResetBackoffLocked() {
backoff_.Reset();
}
-void AresDnsResolver::ShutdownLocked() {
+void AresDnsResolver::ShutdownLocked() {
shutdown_initiated_ = true;
- if (have_next_resolution_timer_) {
- grpc_timer_cancel(&next_resolution_timer_);
- }
- if (pending_request_ != nullptr) {
+ if (have_next_resolution_timer_) {
+ grpc_timer_cancel(&next_resolution_timer_);
+ }
+ if (pending_request_ != nullptr) {
grpc_cancel_ares_request_locked(pending_request_);
- }
-}
-
+ }
+}
+
void AresDnsResolver::OnNextResolution(void* arg, grpc_error* error) {
AresDnsResolver* r = static_cast<AresDnsResolver*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
@@ -227,21 +227,21 @@ void AresDnsResolver::OnNextResolutionLocked(grpc_error* error) {
GRPC_CARES_TRACE_LOG(
"resolver:%p start resolving due to re-resolution timer", this);
StartResolvingLocked();
- }
- }
+ }
+ }
Unref(DEBUG_LOCATION, "next_resolution_timer");
GRPC_ERROR_UNREF(error);
-}
-
+}
+
bool ValueInJsonArray(const Json::Array& array, const char* value) {
for (const Json& entry : array) {
if (entry.type() == Json::Type::STRING && entry.string_value() == value) {
- return true;
- }
- }
- return false;
-}
-
+ return true;
+ }
+ }
+ return false;
+}
+
TString ChooseServiceConfig(char* service_config_choice_json,
grpc_error** error) {
Json json = Json::Parse(service_config_choice_json, error);
@@ -258,7 +258,7 @@ TString ChooseServiceConfig(char* service_config_choice_json,
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");
if (it != choice.object_value().end()) {
@@ -267,7 +267,7 @@ TString ChooseServiceConfig(char* service_config_choice_json,
"field:clientLanguage error:should be of type array"));
} else if (!ValueInJsonArray(it->second.array_value(), "c++")) {
continue;
- }
+ }
}
// Check client hostname, if specified.
it = choice.object_value().find("clientHostname");
@@ -281,7 +281,7 @@ TString ChooseServiceConfig(char* service_config_choice_json,
!ValueInJsonArray(it->second.array_value(), hostname)) {
continue;
}
- }
+ }
}
// Check percentage, if specified.
it = choice.object_value().find("percentage");
@@ -290,16 +290,16 @@ TString ChooseServiceConfig(char* service_config_choice_json,
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:percentage error:should be of type number"));
} else {
- int random_pct = rand() % 100;
- int percentage;
+ 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"));
} else if (random_pct > percentage || percentage == 0) {
continue;
- }
- }
- }
+ }
+ }
+ }
// Found service config.
it = choice.object_value().find("serviceConfig");
if (it == choice.object_value().end()) {
@@ -310,8 +310,8 @@ TString ChooseServiceConfig(char* service_config_choice_json,
"field:serviceConfig error:should be of type object"));
} else if (service_config == nullptr) {
service_config = &it->second;
- }
- }
+ }
+ }
if (!error_list.empty()) {
service_config = nullptr;
*error = GRPC_ERROR_CREATE_FROM_VECTOR("Service Config Choices Parser",
@@ -319,8 +319,8 @@ TString ChooseServiceConfig(char* service_config_choice_json,
}
if (service_config == nullptr) return "";
return service_config->Dump();
-}
-
+}
+
void AresDnsResolver::OnResolved(void* arg, grpc_error* error) {
AresDnsResolver* r = static_cast<AresDnsResolver*>(arg);
GRPC_ERROR_REF(error); // ref owned by lambda
@@ -353,8 +353,8 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) {
this, service_config_string.c_str());
result.service_config = ServiceConfig::Create(
channel_args_, service_config_string, &result.service_config_error);
- }
- }
+ }
+ }
y_absl::InlinedVector<grpc_arg, 1> new_args;
if (balancer_addresses_ != nullptr) {
new_args.push_back(
@@ -365,8 +365,8 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) {
result_handler()->ReturnResult(std::move(result));
addresses_.reset();
balancer_addresses_.reset();
- // Reset backoff state so that we start from the beginning when the
- // next request gets triggered.
+ // Reset backoff state so that we start from the beginning when the
+ // next request gets triggered.
backoff_.Reset();
} else {
GRPC_CARES_TRACE_LOG("resolver:%p dns resolution failed: %s", this,
@@ -379,108 +379,108 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) {
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_millis timeout = next_try - ExecCtx::Get()->Now();
GRPC_CARES_TRACE_LOG("resolver:%p dns resolution failed (will retry): %s",
this, grpc_error_string(error));
GPR_ASSERT(!have_next_resolution_timer_);
have_next_resolution_timer_ = true;
- // 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.
+ // 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, "retry-timer").release();
- if (timeout > 0) {
+ if (timeout > 0) {
GRPC_CARES_TRACE_LOG("resolver:%p retrying in %" PRId64 " milliseconds",
this, timeout);
- } else {
+ } else {
GRPC_CARES_TRACE_LOG("resolver:%p retrying immediately", this);
- }
+ }
grpc_timer_init(&next_resolution_timer_, next_try, &on_next_resolution_);
- }
+ }
Unref(DEBUG_LOCATION, "dns-resolving");
GRPC_ERROR_UNREF(error);
-}
-
-void AresDnsResolver::MaybeStartResolvingLocked() {
- // If there is an existing timer, the time it fires is the earliest time we
- // can start the next resolution.
+}
+
+void AresDnsResolver::MaybeStartResolvingLocked() {
+ // If there is an existing timer, the time it fires is the earliest time we
+ // can start the next resolution.
if (have_next_resolution_timer_) return;
- if (last_resolution_timestamp_ >= 0) {
- const grpc_millis earliest_next_resolution =
- last_resolution_timestamp_ + min_time_between_resolutions_;
- const grpc_millis ms_until_next_resolution =
- earliest_next_resolution - grpc_core::ExecCtx::Get()->Now();
- if (ms_until_next_resolution > 0) {
- const grpc_millis last_resolution_ago =
- grpc_core::ExecCtx::Get()->Now() - last_resolution_timestamp_;
+ if (last_resolution_timestamp_ >= 0) {
+ const grpc_millis earliest_next_resolution =
+ last_resolution_timestamp_ + min_time_between_resolutions_;
+ const grpc_millis ms_until_next_resolution =
+ earliest_next_resolution - grpc_core::ExecCtx::Get()->Now();
+ if (ms_until_next_resolution > 0) {
+ const grpc_millis last_resolution_ago =
+ grpc_core::ExecCtx::Get()->Now() - last_resolution_timestamp_;
GRPC_CARES_TRACE_LOG(
"resolver:%p In cooldown from last resolution (from %" PRId64
" ms ago). Will resolve again in %" PRId64 " ms",
this, last_resolution_ago, ms_until_next_resolution);
- have_next_resolution_timer_ = true;
- // 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.
+ have_next_resolution_timer_ = true;
+ // 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,
- &on_next_resolution_);
- return;
- }
- }
- StartResolvingLocked();
-}
-
-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.
+ &on_next_resolution_);
+ return;
+ }
+ }
+ StartResolvingLocked();
+}
+
+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();
- GPR_ASSERT(!resolving_);
- resolving_ = true;
- service_config_json_ = nullptr;
+ GPR_ASSERT(!resolving_);
+ resolving_ = true;
+ service_config_json_ = nullptr;
pending_request_ = grpc_dns_lookup_ares_locked(
- dns_server_, name_to_resolve_, kDefaultPort, interested_parties_,
+ dns_server_, name_to_resolve_, kDefaultPort, interested_parties_,
&on_resolved_, &addresses_,
enable_srv_queries_ ? &balancer_addresses_ : nullptr,
request_service_config_ ? &service_config_json_ : nullptr,
query_timeout_ms_, work_serializer());
- last_resolution_timestamp_ = grpc_core::ExecCtx::Get()->Now();
+ last_resolution_timestamp_ = grpc_core::ExecCtx::Get()->Now();
GRPC_CARES_TRACE_LOG("resolver:%p Started resolving. pending_request_:%p",
this, pending_request_);
-}
-
-//
-// Factory
-//
-
-class AresDnsResolverFactory : public ResolverFactory {
- public:
+}
+
+//
+// Factory
+//
+
+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));
- }
-
- const char* scheme() const override { return "dns"; }
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-extern grpc_address_resolver_vtable* grpc_resolve_address_impl;
-static grpc_address_resolver_vtable* default_resolver;
-
-static grpc_error* blocking_resolve_address_ares(
- const char* name, const char* default_port,
- grpc_resolved_addresses** addresses) {
- return default_resolver->blocking_resolve_address(name, default_port,
- addresses);
-}
-
-static grpc_address_resolver_vtable ares_resolver = {
- grpc_resolve_address_ares, blocking_resolve_address_ares};
-
+ }
+
+ const char* scheme() const override { return "dns"; }
+};
+
+} // namespace
+
+} // namespace grpc_core
+
+extern grpc_address_resolver_vtable* grpc_resolve_address_impl;
+static grpc_address_resolver_vtable* default_resolver;
+
+static grpc_error* blocking_resolve_address_ares(
+ const char* name, const char* default_port,
+ grpc_resolved_addresses** addresses) {
+ return default_resolver->blocking_resolve_address(name, default_port,
+ addresses);
+}
+
+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 */
@@ -497,40 +497,40 @@ static bool should_use_ares(const char* resolver_env) {
static bool g_use_ares_dns_resolver;
-void grpc_resolver_dns_ares_init() {
+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;
gpr_log(GPR_DEBUG, "Using ares dns resolver");
- address_sorting_init();
- grpc_error* error = grpc_ares_init();
- if (error != GRPC_ERROR_NONE) {
+ address_sorting_init();
+ grpc_error* error = grpc_ares_init();
+ if (error != GRPC_ERROR_NONE) {
GRPC_LOG_IF_ERROR("grpc_ares_init() failed", error);
- return;
- }
+ return;
+ }
if (default_resolver == nullptr) {
default_resolver = grpc_resolve_address_impl;
}
- grpc_set_resolver_impl(&ares_resolver);
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+ 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;
- }
-}
-
-void grpc_resolver_dns_ares_shutdown() {
+ }
+}
+
+void grpc_resolver_dns_ares_shutdown() {
if (g_use_ares_dns_resolver) {
- address_sorting_shutdown();
- grpc_ares_cleanup();
- }
-}
-
+ address_sorting_shutdown();
+ grpc_ares_cleanup();
+ }
+}
+
#else /* GRPC_ARES == 1 */
-
-void grpc_resolver_dns_ares_init(void) {}
-
-void grpc_resolver_dns_ares_shutdown(void) {}
-
+
+void grpc_resolver_dns_ares_init(void) {}
+
+void grpc_resolver_dns_ares_shutdown(void) {}
+
#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 cedf0c39709..9eb309a2e6e 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
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <ares.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_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <ares.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
-#include "src/core/lib/iomgr/pollset_set.h"
-
-typedef struct grpc_ares_ev_driver grpc_ares_ev_driver;
-
-/* Start \a ev_driver. It will keep working until all IO on its ares_channel is
- done, or grpc_ares_ev_driver_destroy() is called. It may notify the callbacks
- bound to its ares_channel when necessary. */
+#include "src/core/lib/iomgr/pollset_set.h"
+
+typedef struct grpc_ares_ev_driver grpc_ares_ev_driver;
+
+/* Start \a ev_driver. It will keep working until all IO on its ares_channel is
+ done, or grpc_ares_ev_driver_destroy() is called. It may notify the callbacks
+ bound to its ares_channel when necessary. */
void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver);
-
-/* Returns the ares_channel owned by \a ev_driver. To bind a c-ares query to
- \a ev_driver, use the ares_channel owned by \a ev_driver as the arg of the
- query. */
+
+/* Returns the ares_channel owned by \a ev_driver. To bind a c-ares query to
+ \a ev_driver, use the ares_channel owned by \a ev_driver as the arg of the
+ query. */
ares_channel* grpc_ares_ev_driver_get_channel_locked(
grpc_ares_ev_driver* ev_driver);
-
-/* Creates a new grpc_ares_ev_driver. Returns GRPC_ERROR_NONE if \a ev_driver is
- created successfully. */
+
+/* Creates a new grpc_ares_ev_driver. Returns GRPC_ERROR_NONE if \a ev_driver is
+ created successfully. */
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);
-
+
/* Called back when all DNS lookups have completed. */
void grpc_ares_ev_driver_on_queries_complete_locked(
grpc_ares_ev_driver* ev_driver);
-
-/* Shutdown all the grpc_fds used by \a ev_driver */
+
+/* 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);
@@ -100,5 +100,5 @@ std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
} // namespace grpc_core
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H \
- */
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H \
+ */
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 e1fcaa5090c..e3fd0d06284 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
@@ -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.
- *
- */
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.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_POSIX_SOCKET_ARES_EV_DRIVER)
-
-#include <ares.h>
+
+#include <ares.h>
#include <string.h>
-#include <sys/ioctl.h>
-
+#include <sys/ioctl.h>
+
#include "y_absl/strings/str_cat.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/ev_posix.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/sockaddr_utils.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/ev_posix.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+
namespace grpc_core {
-
+
class GrpcPolledFdPosix : public GrpcPolledFd {
public:
GrpcPolledFdPosix(ares_socket_t as, grpc_pollset_set* driver_pollset_set)
@@ -48,7 +48,7 @@ class GrpcPolledFdPosix : public GrpcPolledFd {
driver_pollset_set_ = driver_pollset_set;
grpc_pollset_set_add_fd(driver_pollset_set_, fd_);
}
-
+
~GrpcPolledFdPosix() {
grpc_pollset_set_del_fd(driver_pollset_set_, fd_);
/* c-ares library will close the fd inside grpc_fd. This fd may be picked up
@@ -56,54 +56,54 @@ class GrpcPolledFdPosix : public GrpcPolledFd {
grpc_fd_orphan. */
int dummy_release_fd;
grpc_fd_orphan(fd_, nullptr, &dummy_release_fd, "c-ares query finished");
- }
-
+ }
+
void RegisterForOnReadableLocked(grpc_closure* read_closure) override {
grpc_fd_notify_on_read(fd_, read_closure);
- }
-
+ }
+
void RegisterForOnWriteableLocked(grpc_closure* write_closure) override {
grpc_fd_notify_on_write(fd_, write_closure);
- }
-
+ }
+
bool IsFdStillReadableLocked() override {
size_t bytes_available = 0;
return ioctl(grpc_fd_wrapped_fd(fd_), FIONREAD, &bytes_available) == 0 &&
bytes_available > 0;
- }
-
+ }
+
void ShutdownLocked(grpc_error* error) override {
grpc_fd_shutdown(fd_, error);
- }
-
+ }
+
ares_socket_t GetWrappedAresSocketLocked() override { return as_; }
-
+
const char* GetName() override { return name_.c_str(); }
-
+
private:
TString name_;
ares_socket_t as_;
grpc_fd* fd_;
grpc_pollset_set* driver_pollset_set_;
};
-
+
class GrpcPolledFdFactoryPosix : public GrpcPolledFdFactory {
public:
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);
- }
-
+ }
+
void ConfigureAresChannelLocked(ares_channel /*channel*/) override {}
};
-
+
std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(
std::shared_ptr<WorkSerializer> work_serializer) {
(void)work_serializer;
return y_absl::make_unique<GrpcPolledFdFactoryPosix>();
-}
-
+}
+
} // namespace grpc_core
-
+
#endif /* GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) */
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 c3b236af689..4255d982417 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
@@ -1,99 +1,99 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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>
+
#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"
-
-#include <string.h>
-#include <sys/types.h>
-
+
+#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include <string.h>
+#include <sys/types.h>
+
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <ares.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.h>
-
-#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 <ares.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.h>
+
+#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/iomgr/error.h"
-#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/nameser.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/nameser.h"
#include "src/core/lib/iomgr/parse_address.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/transport/authority_override.h"
-
+
using grpc_core::ServerAddress;
using grpc_core::ServerAddressList;
-grpc_core::TraceFlag grpc_trace_cares_address_sorting(false,
- "cares_address_sorting");
-
+grpc_core::TraceFlag grpc_trace_cares_address_sorting(false,
+ "cares_address_sorting");
+
grpc_core::TraceFlag grpc_trace_cares_resolver(false, "cares_resolver");
-struct grpc_ares_request {
- /** indicates the DNS server to use, if specified */
- struct ares_addr_port_node dns_server_addr;
- /** following members are set in grpc_resolve_address_ares_impl */
- /** closure to call when the request completes */
- grpc_closure* on_done;
- /** the pointer to receive the resolved addresses */
+struct grpc_ares_request {
+ /** indicates the DNS server to use, if specified */
+ struct ares_addr_port_node dns_server_addr;
+ /** following members are set in grpc_resolve_address_ares_impl */
+ /** 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;
/** 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 */
- char** service_config_json_out;
- /** the evernt driver used by this request */
- grpc_ares_ev_driver* ev_driver;
- /** number of ongoing queries */
+ /** the pointer to receive the service config in JSON */
+ char** service_config_json_out;
+ /** the evernt driver used by this request */
+ grpc_ares_ev_driver* ev_driver;
+ /** number of ongoing queries */
size_t pending_queries;
-
+
/** the errors explaining query failures, appended to in query callbacks */
- grpc_error* error;
-};
-
+ grpc_error* error;
+};
+
// TODO(apolcyn): make grpc_ares_hostbyname_request a sub-class
// of GrpcAresQuery.
-typedef struct grpc_ares_hostbyname_request {
+typedef struct grpc_ares_hostbyname_request {
/** following members are set in create_hostbyname_request_locked
*/
- /** the top-level request instance */
- grpc_ares_request* parent_request;
- /** host to resolve, parsed from the name to resolve */
- char* host;
- /** port to fill in sockaddr_in, parsed from the name to resolve */
- uint16_t port;
- /** is it a grpclb address */
- bool is_balancer;
+ /** the top-level request instance */
+ grpc_ares_request* parent_request;
+ /** host to resolve, parsed from the name to resolve */
+ char* host;
+ /** port to fill in sockaddr_in, parsed from the name to resolve */
+ uint16_t port;
+ /** is it a grpclb address */
+ bool is_balancer;
/** for logging and errors: the query type ("A" or "AAAA") */
const char* qtype;
-} grpc_ares_hostbyname_request;
-
+} grpc_ares_hostbyname_request;
+
static void grpc_ares_request_ref_locked(grpc_ares_request* r);
static void grpc_ares_request_unref_locked(grpc_ares_request* r);
@@ -123,7 +123,7 @@ class GrpcAresQuery {
static void log_address_sorting_list(const grpc_ares_request* r,
const ServerAddressList& addresses,
- const char* input_output_str) {
+ const char* input_output_str) {
for (size_t i = 0; i < addresses.size(); i++) {
TString addr_str =
grpc_sockaddr_to_string(&addresses[i].address(), true);
@@ -131,39 +131,39 @@ static void log_address_sorting_list(const grpc_ares_request* r,
"(c-ares resolver) request:%p c-ares address sorting: %s[%" PRIuPTR
"]=%s",
r, input_output_str, i, addr_str.c_str());
- }
-}
-
+ }
+}
+
void grpc_cares_wrapper_address_sorting_sort(const grpc_ares_request* r,
ServerAddressList* addresses) {
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(
+ }
+ address_sorting_sortable* sortables = (address_sorting_sortable*)gpr_zalloc(
sizeof(address_sorting_sortable) * addresses->size());
for (size_t i = 0; i < addresses->size(); ++i) {
sortables[i].user_data = &(*addresses)[i];
memcpy(&sortables[i].dest_addr.addr, &(*addresses)[i].address().addr,
(*addresses)[i].address().len);
sortables[i].dest_addr.len = (*addresses)[i].address().len;
- }
+ }
address_sorting_rfc_6724_sort(sortables, addresses->size());
ServerAddressList sorted;
sorted.reserve(addresses->size());
for (size_t i = 0; i < addresses->size(); ++i) {
sorted.emplace_back(*static_cast<ServerAddress*>(sortables[i].user_data));
- }
- gpr_free(sortables);
+ }
+ gpr_free(sortables);
*addresses = std::move(sorted);
if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_address_sorting)) {
log_address_sorting_list(r, *addresses, "output");
- }
-}
-
+ }
+}
+
static void grpc_ares_request_ref_locked(grpc_ares_request* r) {
r->pending_queries++;
-}
-
+}
+
static void grpc_ares_request_unref_locked(grpc_ares_request* r) {
r->pending_queries--;
if (r->pending_queries == 0u) {
@@ -173,7 +173,7 @@ static void grpc_ares_request_unref_locked(grpc_ares_request* r) {
void grpc_ares_complete_request_locked(grpc_ares_request* r) {
/* Invoke on_done callback and destroy the
- request */
+ request */
r->ev_driver = nullptr;
ServerAddressList* addresses = r->addresses_out->get();
if (addresses != nullptr) {
@@ -182,7 +182,7 @@ void grpc_ares_complete_request_locked(grpc_ares_request* r) {
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();
if (balancer_addresses != nullptr) {
@@ -190,8 +190,8 @@ void grpc_ares_complete_request_locked(grpc_ares_request* r) {
}
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, r->error);
-}
-
+}
+
/* Note that the returned object takes a reference to qtype, so
* qtype must outlive it. */
static grpc_ares_hostbyname_request* create_hostbyname_request_locked(
@@ -202,28 +202,28 @@ static grpc_ares_hostbyname_request* create_hostbyname_request_locked(
"is_balancer:%d qtype:%s",
parent_request, host, port, is_balancer, qtype);
grpc_ares_hostbyname_request* hr = new grpc_ares_hostbyname_request();
- hr->parent_request = parent_request;
- hr->host = gpr_strdup(host);
- hr->port = port;
- hr->is_balancer = is_balancer;
+ hr->parent_request = parent_request;
+ hr->host = gpr_strdup(host);
+ hr->port = port;
+ hr->is_balancer = is_balancer;
hr->qtype = qtype;
grpc_ares_request_ref_locked(parent_request);
- return hr;
-}
-
+ return hr;
+}
+
static void destroy_hostbyname_request_locked(
grpc_ares_hostbyname_request* hr) {
grpc_ares_request_unref_locked(hr->parent_request);
- gpr_free(hr->host);
+ gpr_free(hr->host);
delete hr;
-}
-
+}
+
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_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(
"request:%p on_hostbyname_done_locked qtype=%s host=%s ARES_SUCCESS", r,
hr->qtype, hr->host);
@@ -231,7 +231,7 @@ static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/,
hr->is_balancer ? r->balancer_addresses_out : r->addresses_out;
if (*address_list_ptr == nullptr) {
*address_list_ptr = y_absl::make_unique<ServerAddressList>();
- }
+ }
ServerAddressList& addresses = **address_list_ptr;
for (size_t i = 0; hostent->h_addr_list[i] != nullptr; ++i) {
y_absl::InlinedVector<grpc_arg, 1> args_to_add;
@@ -241,43 +241,43 @@ static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/,
}
grpc_channel_args* args = grpc_channel_args_copy_and_add(
nullptr, args_to_add.data(), args_to_add.size());
- switch (hostent->h_addrtype) {
- case AF_INET6: {
- size_t addr_len = sizeof(struct sockaddr_in6);
- struct sockaddr_in6 addr;
- memset(&addr, 0, addr_len);
+ switch (hostent->h_addrtype) {
+ case AF_INET6: {
+ size_t addr_len = sizeof(struct sockaddr_in6);
+ struct sockaddr_in6 addr;
+ memset(&addr, 0, addr_len);
memcpy(&addr.sin6_addr, hostent->h_addr_list[i],
- sizeof(struct in6_addr));
+ sizeof(struct in6_addr));
addr.sin6_family = static_cast<unsigned char>(hostent->h_addrtype);
- addr.sin6_port = hr->port;
+ addr.sin6_port = hr->port;
addresses.emplace_back(&addr, addr_len, args);
- char output[INET6_ADDRSTRLEN];
- ares_inet_ntop(AF_INET6, &addr.sin6_addr, output, INET6_ADDRSTRLEN);
+ char output[INET6_ADDRSTRLEN];
+ ares_inet_ntop(AF_INET6, &addr.sin6_addr, output, INET6_ADDRSTRLEN);
GRPC_CARES_TRACE_LOG(
"request:%p c-ares resolver gets a AF_INET6 result: \n"
" addr: %s\n port: %d\n sin6_scope_id: %d\n",
r, output, ntohs(hr->port), addr.sin6_scope_id);
- break;
- }
- case AF_INET: {
- size_t addr_len = sizeof(struct sockaddr_in);
- struct sockaddr_in addr;
- memset(&addr, 0, addr_len);
+ break;
+ }
+ case AF_INET: {
+ size_t addr_len = sizeof(struct sockaddr_in);
+ struct sockaddr_in addr;
+ memset(&addr, 0, addr_len);
memcpy(&addr.sin_addr, hostent->h_addr_list[i],
- sizeof(struct in_addr));
+ sizeof(struct in_addr));
addr.sin_family = static_cast<unsigned char>(hostent->h_addrtype);
- addr.sin_port = hr->port;
+ addr.sin_port = hr->port;
addresses.emplace_back(&addr, addr_len, args);
- char output[INET_ADDRSTRLEN];
- ares_inet_ntop(AF_INET, &addr.sin_addr, output, INET_ADDRSTRLEN);
+ char output[INET_ADDRSTRLEN];
+ ares_inet_ntop(AF_INET, &addr.sin_addr, output, INET_ADDRSTRLEN);
GRPC_CARES_TRACE_LOG(
"request:%p c-ares resolver gets a AF_INET result: \n"
" addr: %s\n port: %d\n",
r, output, ntohs(hr->port));
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
} else {
TString error_msg = y_absl::StrFormat(
"C-ares status is not ARES_SUCCESS qtype=%s name=%s is_balancer=%d: %s",
@@ -286,44 +286,44 @@ static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/,
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);
- }
+ }
destroy_hostbyname_request_locked(hr);
-}
-
+}
+
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();
- if (status == ARES_SUCCESS) {
+ if (status == ARES_SUCCESS) {
GRPC_CARES_TRACE_LOG(
"request:%p on_srv_query_done_locked name=%s ARES_SUCCESS", r,
q->name().c_str());
- struct ares_srv_reply* reply;
- const int parse_status = ares_parse_srv_reply(abuf, alen, &reply);
+ 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);
- if (parse_status == ARES_SUCCESS) {
+ if (parse_status == ARES_SUCCESS) {
ares_channel* channel =
grpc_ares_ev_driver_get_channel_locked(r->ev_driver);
- for (struct ares_srv_reply* srv_it = reply; srv_it != nullptr;
- srv_it = srv_it->next) {
+ for (struct ares_srv_reply* srv_it = reply; srv_it != nullptr;
+ srv_it = srv_it->next) {
if (grpc_ares_query_ipv6()) {
grpc_ares_hostbyname_request* hr = create_hostbyname_request_locked(
r, srv_it->host, htons(srv_it->port), true /* is_balancer */,
"AAAA");
- ares_gethostbyname(*channel, hr->host, AF_INET6,
+ ares_gethostbyname(*channel, hr->host, AF_INET6,
on_hostbyname_done_locked, hr);
- }
+ }
grpc_ares_hostbyname_request* hr = create_hostbyname_request_locked(
r, srv_it->host, htons(srv_it->port), true /* is_balancer */, "A");
ares_gethostbyname(*channel, hr->host, AF_INET,
on_hostbyname_done_locked, hr);
grpc_ares_ev_driver_start_locked(r->ev_driver);
- }
- }
- if (reply != nullptr) {
- ares_free_data(reply);
- }
+ }
+ }
+ if (reply != nullptr) {
+ ares_free_data(reply);
+ }
} else {
TString error_msg = y_absl::StrFormat(
"C-ares status is not ARES_SUCCESS qtype=SRV name=%s: %s", q->name(),
@@ -332,58 +332,58 @@ static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/,
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);
- }
+ }
delete q;
-}
-
-static const char g_service_config_attribute_prefix[] = "grpc_config=";
-
+}
+
+static const char g_service_config_attribute_prefix[] = "grpc_config=";
+
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);
grpc_ares_request* r = q->parent_request();
- const size_t prefix_len = sizeof(g_service_config_attribute_prefix) - 1;
- struct ares_txt_ext* result = nullptr;
- struct ares_txt_ext* reply = nullptr;
- grpc_error* error = GRPC_ERROR_NONE;
- if (status != ARES_SUCCESS) goto fail;
+ const size_t prefix_len = sizeof(g_service_config_attribute_prefix) - 1;
+ struct ares_txt_ext* result = nullptr;
+ struct ares_txt_ext* reply = nullptr;
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (status != ARES_SUCCESS) goto fail;
GRPC_CARES_TRACE_LOG("request:%p on_txt_done_locked name=%s ARES_SUCCESS", r,
q->name().c_str());
- status = ares_parse_txt_reply_ext(buf, len, &reply);
- if (status != ARES_SUCCESS) goto fail;
- // Find service config in TXT record.
- for (result = reply; result != nullptr; result = result->next) {
- if (result->record_start &&
- memcmp(result->txt, g_service_config_attribute_prefix, prefix_len) ==
- 0) {
- break;
- }
- }
- // Found a service config record.
- if (result != nullptr) {
- size_t service_config_len = result->length - prefix_len;
- *r->service_config_json_out =
- static_cast<char*>(gpr_malloc(service_config_len + 1));
- memcpy(*r->service_config_json_out, result->txt + prefix_len,
- service_config_len);
- for (result = result->next; result != nullptr && !result->record_start;
- result = result->next) {
- *r->service_config_json_out = static_cast<char*>(
- gpr_realloc(*r->service_config_json_out,
- service_config_len + result->length + 1));
- memcpy(*r->service_config_json_out + service_config_len, result->txt,
- result->length);
- service_config_len += result->length;
- }
- (*r->service_config_json_out)[service_config_len] = '\0';
+ status = ares_parse_txt_reply_ext(buf, len, &reply);
+ if (status != ARES_SUCCESS) goto fail;
+ // Find service config in TXT record.
+ for (result = reply; result != nullptr; result = result->next) {
+ if (result->record_start &&
+ memcmp(result->txt, g_service_config_attribute_prefix, prefix_len) ==
+ 0) {
+ break;
+ }
+ }
+ // Found a service config record.
+ if (result != nullptr) {
+ size_t service_config_len = result->length - prefix_len;
+ *r->service_config_json_out =
+ static_cast<char*>(gpr_malloc(service_config_len + 1));
+ memcpy(*r->service_config_json_out, result->txt + prefix_len,
+ service_config_len);
+ for (result = result->next; result != nullptr && !result->record_start;
+ result = result->next) {
+ *r->service_config_json_out = static_cast<char*>(
+ gpr_realloc(*r->service_config_json_out,
+ service_config_len + result->length + 1));
+ memcpy(*r->service_config_json_out + service_config_len, result->txt,
+ result->length);
+ service_config_len += result->length;
+ }
+ (*r->service_config_json_out)[service_config_len] = '\0';
GRPC_CARES_TRACE_LOG("request:%p found service config: %s", r,
*r->service_config_json_out);
- }
- // Clean up.
- ares_free_data(reply);
+ }
+ // Clean up.
+ ares_free_data(reply);
return;
-fail:
+fail:
TString error_msg =
y_absl::StrFormat("C-ares status is not ARES_SUCCESS qtype=TXT name=%s: %s",
q->name(), ares_strerror(status));
@@ -391,74 +391,74 @@ fail:
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);
-}
-
+}
+
void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
grpc_ares_request* r, const char* dns_server, const char* name,
const char* default_port, grpc_pollset_set* interested_parties,
int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) {
- grpc_error* error = GRPC_ERROR_NONE;
- grpc_ares_hostbyname_request* hr = nullptr;
- ares_channel* channel = nullptr;
- /* parse name, splitting it into host and port parts */
+ grpc_error* error = GRPC_ERROR_NONE;
+ grpc_ares_hostbyname_request* hr = nullptr;
+ ares_channel* channel = nullptr;
+ /* parse name, splitting it into host and port parts */
TString host;
TString port;
grpc_core::SplitHostPort(name, &host, &port);
if (host.empty()) {
- error = grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"),
- GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
- goto error_cleanup;
+ error = grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"),
+ GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
+ goto error_cleanup;
} else if (port.empty()) {
- if (default_port == nullptr) {
- error = grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("no port in name"),
- GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
- goto error_cleanup;
- }
+ if (default_port == nullptr) {
+ error = grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("no port in name"),
+ GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
+ goto error_cleanup;
+ }
port = default_port;
- }
+ }
error = grpc_ares_ev_driver_create_locked(&r->ev_driver, interested_parties,
query_timeout_ms,
std::move(work_serializer), r);
- if (error != GRPC_ERROR_NONE) goto error_cleanup;
+ if (error != GRPC_ERROR_NONE) goto error_cleanup;
channel = grpc_ares_ev_driver_get_channel_locked(r->ev_driver);
- // If dns_server is specified, use it.
- if (dns_server != nullptr) {
+ // If dns_server is specified, use it.
+ if (dns_server != nullptr) {
GRPC_CARES_TRACE_LOG("request:%p Using DNS server %s", r, dns_server);
- grpc_resolved_address addr;
- if (grpc_parse_ipv4_hostport(dns_server, &addr, false /* log_errors */)) {
- r->dns_server_addr.family = AF_INET;
- struct sockaddr_in* in = reinterpret_cast<struct sockaddr_in*>(addr.addr);
- memcpy(&r->dns_server_addr.addr.addr4, &in->sin_addr,
- sizeof(struct in_addr));
- r->dns_server_addr.tcp_port = grpc_sockaddr_get_port(&addr);
- r->dns_server_addr.udp_port = grpc_sockaddr_get_port(&addr);
- } else if (grpc_parse_ipv6_hostport(dns_server, &addr,
- false /* log_errors */)) {
- r->dns_server_addr.family = AF_INET6;
- struct sockaddr_in6* in6 =
- reinterpret_cast<struct sockaddr_in6*>(addr.addr);
- memcpy(&r->dns_server_addr.addr.addr6, &in6->sin6_addr,
- sizeof(struct in6_addr));
- r->dns_server_addr.tcp_port = grpc_sockaddr_get_port(&addr);
- r->dns_server_addr.udp_port = grpc_sockaddr_get_port(&addr);
- } else {
- error = grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("cannot parse authority"),
- GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
- goto error_cleanup;
- }
- int status = ares_set_servers_ports(*channel, &r->dns_server_addr);
- if (status != ARES_SUCCESS) {
+ grpc_resolved_address addr;
+ if (grpc_parse_ipv4_hostport(dns_server, &addr, false /* log_errors */)) {
+ r->dns_server_addr.family = AF_INET;
+ struct sockaddr_in* in = reinterpret_cast<struct sockaddr_in*>(addr.addr);
+ memcpy(&r->dns_server_addr.addr.addr4, &in->sin_addr,
+ sizeof(struct in_addr));
+ r->dns_server_addr.tcp_port = grpc_sockaddr_get_port(&addr);
+ r->dns_server_addr.udp_port = grpc_sockaddr_get_port(&addr);
+ } else if (grpc_parse_ipv6_hostport(dns_server, &addr,
+ false /* log_errors */)) {
+ r->dns_server_addr.family = AF_INET6;
+ struct sockaddr_in6* in6 =
+ reinterpret_cast<struct sockaddr_in6*>(addr.addr);
+ memcpy(&r->dns_server_addr.addr.addr6, &in6->sin6_addr,
+ sizeof(struct in6_addr));
+ r->dns_server_addr.tcp_port = grpc_sockaddr_get_port(&addr);
+ r->dns_server_addr.udp_port = grpc_sockaddr_get_port(&addr);
+ } else {
+ error = grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("cannot parse authority"),
+ GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
+ goto error_cleanup;
+ }
+ int status = ares_set_servers_ports(*channel, &r->dns_server_addr);
+ if (status != ARES_SUCCESS) {
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("C-ares status is not ARES_SUCCESS: ",
ares_strerror(status))
.c_str());
- goto error_cleanup;
- }
- }
+ goto error_cleanup;
+ }
+ }
r->pending_queries = 1;
if (grpc_ares_query_ipv6()) {
hr = create_hostbyname_request_locked(r, host.c_str(),
@@ -466,33 +466,33 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
/*is_balancer=*/false, "AAAA");
ares_gethostbyname(*channel, hr->host, AF_INET6, on_hostbyname_done_locked,
hr);
- }
+ }
hr = create_hostbyname_request_locked(r, host.c_str(),
grpc_strhtons(port.c_str()),
/*is_balancer=*/false, "A");
ares_gethostbyname(*channel, hr->host, AF_INET, on_hostbyname_done_locked,
hr);
if (r->balancer_addresses_out != nullptr) {
- /* Query the SRV record */
+ /* Query the SRV record */
TString service_name = y_absl::StrCat("_grpclb._tcp.", host);
GrpcAresQuery* srv_query = new GrpcAresQuery(r, service_name);
ares_query(*channel, service_name.c_str(), ns_c_in, ns_t_srv,
on_srv_query_done_locked, srv_query);
- }
+ }
if (r->service_config_json_out != nullptr) {
TString config_name = y_absl::StrCat("_grpc_config.", host);
GrpcAresQuery* txt_query = new GrpcAresQuery(r, config_name);
ares_search(*channel, config_name.c_str(), ns_c_in, ns_t_txt,
on_txt_done_locked, txt_query);
- }
+ }
grpc_ares_ev_driver_start_locked(r->ev_driver);
grpc_ares_request_unref_locked(r);
return;
-
-error_cleanup:
+
+error_cleanup:
grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
-}
-
+}
+
static bool inner_resolve_as_ip_literal_locked(
const char* name, const char* default_port,
std::unique_ptr<grpc_core::ServerAddressList>* addrs, TString* host,
@@ -627,8 +627,8 @@ static bool grpc_ares_maybe_resolve_localhost_manually_locked(
#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,
+ 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,
@@ -670,7 +670,7 @@ static grpc_ares_request* grpc_dns_lookup_ares_locked_impl(
std::move(work_serializer));
return r;
}
-
+
grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
const char* dns_server, const char* name, const char* default_port,
grpc_pollset_set* interested_parties, grpc_closure* on_done,
@@ -684,9 +684,9 @@ static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) {
GPR_ASSERT(r != nullptr);
if (r->ev_driver != nullptr) {
grpc_ares_ev_driver_shutdown_locked(r->ev_driver);
- }
-}
-
+ }
+}
+
void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) =
grpc_cancel_ares_request_locked_impl;
@@ -694,35 +694,35 @@ void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) =
// 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) {
+grpc_error* grpc_ares_init(void) {
+ int status = ares_library_init(ARES_LIB_INIT_ALL);
+ if (status != ARES_SUCCESS) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("ares_library_init failed: ", ares_strerror(status))
.c_str());
- }
- return GRPC_ERROR_NONE;
-}
-
+ }
+ 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
-
-/*
- * grpc_resolve_address_ares related structs and functions
- */
-
-typedef struct grpc_resolve_address_ares_request {
+
+/*
+ * grpc_resolve_address_ares related structs and functions
+ */
+
+typedef struct grpc_resolve_address_ares_request {
/* work_serializer that queries and related callbacks run under */
std::shared_ptr<grpc_core::WorkSerializer> work_serializer;
- /** the pointer to receive the resolved addresses */
- grpc_resolved_addresses** addrs_out;
+ /** the pointer to receive the resolved addresses */
+ grpc_resolved_addresses** addrs_out;
/** currently resolving addresses */
std::unique_ptr<ServerAddressList> addresses;
- /** closure to call when the resolve_address_ares request completes */
- grpc_closure* on_resolve_address_done;
+ /** 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
the grpc_dns_lookup_ares_locked operation is done. */
grpc_closure on_dns_lookup_done_locked;
@@ -734,30 +734,30 @@ typedef struct grpc_resolve_address_ares_request {
grpc_pollset_set* interested_parties;
/* underlying ares_request that the query is performed on */
grpc_ares_request* ares_request = nullptr;
-} grpc_resolve_address_ares_request;
-
+} grpc_resolve_address_ares_request;
+
static void on_dns_lookup_done_locked(grpc_resolve_address_ares_request* r,
grpc_error* error) {
gpr_free(r->ares_request);
- grpc_resolved_addresses** resolved_addresses = r->addrs_out;
+ grpc_resolved_addresses** resolved_addresses = r->addrs_out;
if (r->addresses == nullptr || r->addresses->empty()) {
- *resolved_addresses = nullptr;
- } else {
- *resolved_addresses = static_cast<grpc_resolved_addresses*>(
- gpr_zalloc(sizeof(grpc_resolved_addresses)));
+ *resolved_addresses = nullptr;
+ } else {
+ *resolved_addresses = static_cast<grpc_resolved_addresses*>(
+ gpr_zalloc(sizeof(grpc_resolved_addresses)));
(*resolved_addresses)->naddrs = r->addresses->size();
- (*resolved_addresses)->addrs =
- static_cast<grpc_resolved_address*>(gpr_zalloc(
- sizeof(grpc_resolved_address) * (*resolved_addresses)->naddrs));
+ (*resolved_addresses)->addrs =
+ static_cast<grpc_resolved_address*>(gpr_zalloc(
+ sizeof(grpc_resolved_address) * (*resolved_addresses)->naddrs));
for (size_t i = 0; i < (*resolved_addresses)->naddrs; ++i) {
memcpy(&(*resolved_addresses)->addrs[i], &(*r->addresses)[i].address(),
sizeof(grpc_resolved_address));
- }
- }
+ }
+ }
grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_resolve_address_done, error);
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);
@@ -778,27 +778,27 @@ static void grpc_resolve_address_invoke_dns_lookup_ares_locked(void* arg) {
GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS, r->work_serializer);
}
-static void grpc_resolve_address_ares_impl(const char* name,
- const char* default_port,
- grpc_pollset_set* interested_parties,
- grpc_closure* on_done,
- grpc_resolved_addresses** addrs) {
- grpc_resolve_address_ares_request* r =
+static void grpc_resolve_address_ares_impl(const char* name,
+ const char* default_port,
+ grpc_pollset_set* interested_parties,
+ grpc_closure* on_done,
+ grpc_resolved_addresses** addrs) {
+ grpc_resolve_address_ares_request* r =
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;
+ r->addrs_out = addrs;
+ r->on_resolve_address_done = on_done;
r->name = name;
r->default_port = default_port;
r->interested_parties = interested_parties;
r->work_serializer->Run(
[r]() { grpc_resolve_address_invoke_dns_lookup_ares_locked(r); },
DEBUG_LOCATION);
-}
-
-void (*grpc_resolve_address_ares)(
- const char* name, const char* default_port,
- grpc_pollset_set* interested_parties, grpc_closure* on_done,
- grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
-
+}
+
+void (*grpc_resolve_address_ares)(
+ const char* name, const char* default_port,
+ grpc_pollset_set* interested_parties, grpc_closure* on_done,
+ grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
+
#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 ddce754934f..9acc8149528 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
@@ -1,36 +1,36 @@
-/*
- *
- * 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_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_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_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_H
+
+#include <grpc/support/port_platform.h>
+
#include "src/core/ext/filters/client_channel/server_address.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/iomgr/polling_entity.h"
-#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/iomgr/polling_entity.h"
+#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
-extern grpc_core::TraceFlag grpc_trace_cares_address_sorting;
-
+extern grpc_core::TraceFlag grpc_trace_cares_address_sorting;
+
extern grpc_core::TraceFlag grpc_trace_cares_resolver;
#define GRPC_CARES_TRACE_LOG(format, ...) \
@@ -40,51 +40,51 @@ extern grpc_core::TraceFlag grpc_trace_cares_resolver;
} \
} while (0)
-typedef struct grpc_ares_request grpc_ares_request;
-
-/* Asynchronously resolve \a name. Use \a default_port if a port isn't
- designated in \a name, otherwise use the port in \a name. grpc_ares_init()
- must be called at least once before this function. \a on_done may be
- called directly in this function without being scheduled with \a exec_ctx,
- so it must not try to acquire locks that are being held by the caller. */
-extern void (*grpc_resolve_address_ares)(const char* name,
- const char* default_port,
- grpc_pollset_set* interested_parties,
- grpc_closure* on_done,
- grpc_resolved_addresses** addresses);
-
-/* Asynchronously resolve \a name. It will try to resolve grpclb SRV records in
- addition to the normal address records. For normal address records, it uses
- \a default_port if a port isn't designated in \a name, otherwise it uses the
- port in \a name. grpc_ares_init() must be called at least once before this
- function. \a on_done may be called directly in this function without being
- scheduled with \a exec_ctx, so it must not try to acquire locks that are
+typedef struct grpc_ares_request grpc_ares_request;
+
+/* Asynchronously resolve \a name. Use \a default_port if a port isn't
+ designated in \a name, otherwise use the port in \a name. grpc_ares_init()
+ must be called at least once before this function. \a on_done may be
+ called directly in this function without being scheduled with \a exec_ctx,
+ so it must not try to acquire locks that are being held by the caller. */
+extern void (*grpc_resolve_address_ares)(const char* name,
+ const char* default_port,
+ grpc_pollset_set* interested_parties,
+ grpc_closure* on_done,
+ grpc_resolved_addresses** addresses);
+
+/* Asynchronously resolve \a name. It will try to resolve grpclb SRV records in
+ addition to the normal address records. For normal address records, it uses
+ \a default_port if a port isn't designated in \a name, otherwise it uses the
+ port in \a name. grpc_ares_init() must be called at least once before this
+ function. \a on_done may be called directly in this function without being
+ scheduled with \a exec_ctx, so it must not try to acquire locks that are
being held by the caller. The returned grpc_ares_request object is owned
by the caller and it is safe to free after on_done is called back. */
extern grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
- const char* dns_server, const char* name, const char* default_port,
- grpc_pollset_set* interested_parties, grpc_closure* on_done,
+ 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>* addresses,
std::unique_ptr<grpc_core::ServerAddressList>* balancer_addresses,
char** service_config_json, int query_timeout_ms,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer);
-
-/* Cancel the pending grpc_ares_request \a request */
+
+/* Cancel the pending grpc_ares_request \a request */
extern void (*grpc_cancel_ares_request_locked)(grpc_ares_request* request);
-
-/* Initialize gRPC ares wrapper. Must be called at least once before
- grpc_resolve_address_ares(). */
-grpc_error* grpc_ares_init(void);
-
-/* Uninitialized gRPC ares wrapper. If there was more than one previous call to
- grpc_ares_init(), this function uninitializes the gRPC ares wrapper only if
- it has been called the same number of times as grpc_ares_init(). */
-void grpc_ares_cleanup(void);
-
+
+/* Initialize gRPC ares wrapper. Must be called at least once before
+ grpc_resolve_address_ares(). */
+grpc_error* grpc_ares_init(void);
+
+/* Uninitialized gRPC ares wrapper. If there was more than one previous call to
+ grpc_ares_init(), this function uninitializes the gRPC ares wrapper only if
+ it has been called the same number of times as grpc_ares_init(). */
+void grpc_ares_cleanup(void);
+
/** Schedules the desired callback for request completion
* and destroys the grpc_ares_request */
void grpc_ares_complete_request_locked(grpc_ares_request* request);
-
+
/* Indicates whether or not AAAA queries should be attempted. */
/* E.g., return false if ipv6 is known to not be available. */
bool grpc_ares_query_ipv6();
@@ -93,5 +93,5 @@ bool grpc_ares_query_ipv6();
void grpc_cares_wrapper_address_sorting_sort(
const grpc_ares_request* request, grpc_core::ServerAddressList* addresses);
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_H \
- */
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_H \
+ */
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 2049f371184..3c1b0ae4e8d 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
@@ -1,68 +1,68 @@
-/*
- *
- * Copyright 2016-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>
-
+/*
+ *
+ * Copyright 2016-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>
+
#if GRPC_ARES != 1
-
-#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
-
-struct grpc_ares_request {
- char val;
-};
-
+
+#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
+
+struct grpc_ares_request {
+ char val;
+};
+
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,
+ 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,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) {
- return NULL;
-}
-
+ return NULL;
+}
+
grpc_ares_request* (*grpc_dns_lookup_ares_locked)(
- const char* dns_server, const char* name, const char* default_port,
- grpc_pollset_set* interested_parties, grpc_closure* on_done,
+ 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,
std::shared_ptr<grpc_core::WorkSerializer> work_serializer) =
grpc_dns_lookup_ares_locked_impl;
-
+
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;
-grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; }
-
-void grpc_ares_cleanup(void) {}
-
-static void grpc_resolve_address_ares_impl(const char* name,
- const char* default_port,
- grpc_pollset_set* interested_parties,
- grpc_closure* on_done,
- grpc_resolved_addresses** addrs) {}
-
-void (*grpc_resolve_address_ares)(
- const char* name, const char* default_port,
- grpc_pollset_set* interested_parties, grpc_closure* on_done,
- grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
-
+grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; }
+
+void grpc_ares_cleanup(void) {}
+
+static void grpc_resolve_address_ares_impl(const char* name,
+ const char* default_port,
+ grpc_pollset_set* interested_parties,
+ grpc_closure* on_done,
+ grpc_resolved_addresses** addrs) {}
+
+void (*grpc_resolve_address_ares)(
+ const char* name, const char* default_port,
+ grpc_pollset_set* interested_parties, grpc_closure* on_done,
+ grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
+
#endif /* GRPC_ARES != 1 */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/README.md b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/README.md
index 695de47b9f7..239447f61d4 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/README.md
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/README.md
@@ -1,2 +1,2 @@
-dns: scheme name resolution, using getaddrbyname
-(or other OS specific implementation)
+dns: scheme name resolution, using getaddrbyname
+(or other OS specific implementation)
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 a0e35661908..9276743b7bd 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
@@ -1,140 +1,140 @@
-/*
- *
- * 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 <inttypes.h>
-#include <climits>
-#include <cstring>
-
+/*
+ *
+ * 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 <inttypes.h>
+#include <climits>
+#include <cstring>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.h>
-
+#include <grpc/support/alloc.h>
+#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_registry.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"
-#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/resolve_address.h"
-#include "src/core/lib/iomgr/timer.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/resolve_address.h"
+#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/iomgr/work_serializer.h"
-
-#define GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS 1
-#define GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER 1.6
-#define GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS 120
-#define GRPC_DNS_RECONNECT_JITTER 0.2
-
-namespace grpc_core {
-
-namespace {
-
-const char kDefaultPort[] = "https";
-
-class NativeDnsResolver : public Resolver {
- public:
+
+#define GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS 1
+#define GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER 1.6
+#define GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS 120
+#define GRPC_DNS_RECONNECT_JITTER 0.2
+
+namespace grpc_core {
+
+namespace {
+
+const char kDefaultPort[] = "https";
+
+class NativeDnsResolver : public Resolver {
+ public:
explicit NativeDnsResolver(ResolverArgs args);
-
+
void StartLocked() override;
-
- void RequestReresolutionLocked() override;
-
+
+ void RequestReresolutionLocked() override;
+
void ResetBackoffLocked() override;
- void ShutdownLocked() override;
-
- private:
- virtual ~NativeDnsResolver();
-
- void MaybeStartResolvingLocked();
- void StartResolvingLocked();
-
+ void ShutdownLocked() override;
+
+ private:
+ virtual ~NativeDnsResolver();
+
+ void MaybeStartResolvingLocked();
+ void StartResolvingLocked();
+
static void OnNextResolution(void* arg, grpc_error* error);
void OnNextResolutionLocked(grpc_error* error);
static void OnResolved(void* arg, grpc_error* error);
void OnResolvedLocked(grpc_error* error);
-
- /// name to resolve
- char* name_to_resolve_ = nullptr;
- /// channel args
- grpc_channel_args* channel_args_ = nullptr;
- /// pollset_set to drive the name resolution process
- grpc_pollset_set* interested_parties_ = nullptr;
+
+ /// name to resolve
+ char* name_to_resolve_ = nullptr;
+ /// channel args
+ 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 currently resolving?
- bool resolving_ = false;
- grpc_closure on_resolved_;
- /// next resolution timer
- bool have_next_resolution_timer_ = false;
- grpc_timer next_resolution_timer_;
- grpc_closure on_next_resolution_;
- /// min time between DNS requests
- grpc_millis min_time_between_resolutions_;
- /// timestamp of last DNS request
- grpc_millis last_resolution_timestamp_ = -1;
- /// retry backoff state
- BackOff backoff_;
- /// currently resolving addresses
- grpc_resolved_addresses* addresses_ = nullptr;
-};
-
+ /// are we currently resolving?
+ bool resolving_ = false;
+ grpc_closure on_resolved_;
+ /// next resolution timer
+ bool have_next_resolution_timer_ = false;
+ grpc_timer next_resolution_timer_;
+ grpc_closure on_next_resolution_;
+ /// min time between DNS requests
+ grpc_millis min_time_between_resolutions_;
+ /// timestamp of last DNS request
+ grpc_millis last_resolution_timestamp_ = -1;
+ /// retry backoff state
+ BackOff backoff_;
+ /// currently resolving addresses
+ grpc_resolved_addresses* addresses_ = nullptr;
+};
+
NativeDnsResolver::NativeDnsResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer), std::move(args.result_handler)),
- backoff_(
- BackOff::Options()
- .set_initial_backoff(GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS *
- 1000)
- .set_multiplier(GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER)
- .set_jitter(GRPC_DNS_RECONNECT_JITTER)
- .set_max_backoff(GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000)) {
- char* path = args.uri->path;
- if (path[0] == '/') ++path;
- name_to_resolve_ = gpr_strdup(path);
- channel_args_ = grpc_channel_args_copy(args.args);
- const grpc_arg* arg = grpc_channel_args_find(
- args.args, GRPC_ARG_DNS_MIN_TIME_BETWEEN_RESOLUTIONS_MS);
- min_time_between_resolutions_ =
+ backoff_(
+ BackOff::Options()
+ .set_initial_backoff(GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS *
+ 1000)
+ .set_multiplier(GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER)
+ .set_jitter(GRPC_DNS_RECONNECT_JITTER)
+ .set_max_backoff(GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000)) {
+ char* path = args.uri->path;
+ if (path[0] == '/') ++path;
+ name_to_resolve_ = gpr_strdup(path);
+ channel_args_ = grpc_channel_args_copy(args.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});
- interested_parties_ = grpc_pollset_set_create();
- if (args.pollset_set != nullptr) {
- grpc_pollset_set_add_pollset_set(interested_parties_, args.pollset_set);
- }
-}
-
-NativeDnsResolver::~NativeDnsResolver() {
+ interested_parties_ = grpc_pollset_set_create();
+ if (args.pollset_set != nullptr) {
+ grpc_pollset_set_add_pollset_set(interested_parties_, args.pollset_set);
+ }
+}
+
+NativeDnsResolver::~NativeDnsResolver() {
grpc_channel_args_destroy(channel_args_);
- grpc_pollset_set_destroy(interested_parties_);
- gpr_free(name_to_resolve_);
-}
-
+ grpc_pollset_set_destroy(interested_parties_);
+ gpr_free(name_to_resolve_);
+}
+
void NativeDnsResolver::StartLocked() { MaybeStartResolvingLocked(); }
-
-void NativeDnsResolver::RequestReresolutionLocked() {
- if (!resolving_) {
- MaybeStartResolvingLocked();
- }
-}
-
+
+void NativeDnsResolver::RequestReresolutionLocked() {
+ if (!resolving_) {
+ MaybeStartResolvingLocked();
+ }
+}
+
void NativeDnsResolver::ResetBackoffLocked() {
if (have_next_resolution_timer_) {
grpc_timer_cancel(&next_resolution_timer_);
@@ -142,13 +142,13 @@ void NativeDnsResolver::ResetBackoffLocked() {
backoff_.Reset();
}
-void NativeDnsResolver::ShutdownLocked() {
+void NativeDnsResolver::ShutdownLocked() {
shutdown_ = true;
- if (have_next_resolution_timer_) {
- grpc_timer_cancel(&next_resolution_timer_);
- }
-}
-
+ 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);
GRPC_ERROR_REF(error); // ref owned by lambda
@@ -160,11 +160,11 @@ void NativeDnsResolver::OnNextResolutionLocked(grpc_error* error) {
have_next_resolution_timer_ = false;
if (error == GRPC_ERROR_NONE && !resolving_) {
StartResolvingLocked();
- }
+ }
Unref(DEBUG_LOCATION, "retry-timer");
GRPC_ERROR_UNREF(error);
-}
-
+}
+
void NativeDnsResolver::OnResolved(void* arg, grpc_error* error) {
NativeDnsResolver* r = static_cast<NativeDnsResolver*>(arg);
GRPC_ERROR_REF(error); // owned by lambda
@@ -189,14 +189,14 @@ void NativeDnsResolver::OnResolvedLocked(grpc_error* error) {
result.addresses.emplace_back(&addresses_->addrs[i].addr,
addresses_->addrs[i].len,
nullptr /* args */);
- }
+ }
grpc_resolved_addresses_destroy(addresses_);
result.args = grpc_channel_args_copy(channel_args_);
result_handler()->ReturnResult(std::move(result));
- // Reset backoff state so that we start from the beginning when the
- // next request gets triggered.
+ // Reset backoff state so that we start from the beginning when the
+ // next request gets triggered.
backoff_.Reset();
- } else {
+ } else {
gpr_log(GPR_INFO, "dns resolution failed (will retry): %s",
grpc_error_string(error));
// Return transient error.
@@ -208,118 +208,118 @@ void NativeDnsResolver::OnResolvedLocked(grpc_error* error) {
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();
+ grpc_millis timeout = next_try - ExecCtx::Get()->Now();
GPR_ASSERT(!have_next_resolution_timer_);
have_next_resolution_timer_ = true;
- // 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.
+ // 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").release();
- if (timeout > 0) {
+ if (timeout > 0) {
gpr_log(GPR_DEBUG, "retrying in %" PRId64 " milliseconds", timeout);
- } else {
- gpr_log(GPR_DEBUG, "retrying immediately");
- }
+ } else {
+ gpr_log(GPR_DEBUG, "retrying immediately");
+ }
GRPC_CLOSURE_INIT(&on_next_resolution_, NativeDnsResolver::OnNextResolution,
this, grpc_schedule_on_exec_ctx);
grpc_timer_init(&next_resolution_timer_, next_try, &on_next_resolution_);
- }
+ }
Unref(DEBUG_LOCATION, "dns-resolving");
GRPC_ERROR_UNREF(error);
-}
-
-void NativeDnsResolver::MaybeStartResolvingLocked() {
- // If there is an existing timer, the time it fires is the earliest time we
- // can start the next resolution.
+}
+
+void NativeDnsResolver::MaybeStartResolvingLocked() {
+ // If there is an existing timer, the time it fires is the earliest time we
+ // can start the next resolution.
if (have_next_resolution_timer_) return;
- if (last_resolution_timestamp_ >= 0) {
- const grpc_millis earliest_next_resolution =
- last_resolution_timestamp_ + min_time_between_resolutions_;
- const grpc_millis ms_until_next_resolution =
- earliest_next_resolution - grpc_core::ExecCtx::Get()->Now();
- if (ms_until_next_resolution > 0) {
- const grpc_millis last_resolution_ago =
- grpc_core::ExecCtx::Get()->Now() - last_resolution_timestamp_;
- gpr_log(GPR_DEBUG,
+ if (last_resolution_timestamp_ >= 0) {
+ const grpc_millis earliest_next_resolution =
+ last_resolution_timestamp_ + min_time_between_resolutions_;
+ const grpc_millis ms_until_next_resolution =
+ earliest_next_resolution - grpc_core::ExecCtx::Get()->Now();
+ if (ms_until_next_resolution > 0) {
+ const grpc_millis last_resolution_ago =
+ grpc_core::ExecCtx::Get()->Now() - last_resolution_timestamp_;
+ gpr_log(GPR_DEBUG,
"In cooldown from last resolution (from %" PRId64
" ms ago). Will resolve again in %" PRId64 " ms",
- last_resolution_ago, ms_until_next_resolution);
- have_next_resolution_timer_ = true;
- // 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.
+ last_resolution_ago, ms_until_next_resolution);
+ have_next_resolution_timer_ = true;
+ // 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,
- &on_next_resolution_);
- return;
- }
- }
- StartResolvingLocked();
-}
-
-void NativeDnsResolver::StartResolvingLocked() {
- gpr_log(GPR_DEBUG, "Start resolving.");
- // 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.
+ &on_next_resolution_);
+ return;
+ }
+ }
+ StartResolvingLocked();
+}
+
+void NativeDnsResolver::StartResolvingLocked() {
+ gpr_log(GPR_DEBUG, "Start resolving.");
+ // 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();
- GPR_ASSERT(!resolving_);
- resolving_ = true;
- addresses_ = nullptr;
+ GPR_ASSERT(!resolving_);
+ resolving_ = true;
+ addresses_ = nullptr;
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();
-}
-
-//
-// Factory
-//
-
-class NativeDnsResolverFactory : public ResolverFactory {
- public:
+ grpc_resolve_address(name_to_resolve_, kDefaultPort, interested_parties_,
+ &on_resolved_, &addresses_);
+ last_resolution_timestamp_ = grpc_core::ExecCtx::Get()->Now();
+}
+
+//
+// Factory
+//
+
+class NativeDnsResolverFactory : public ResolverFactory {
+ public:
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");
+ gpr_log(GPR_ERROR, "authority based dns uri's not supported");
return false;
- }
+ }
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"; }
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-void grpc_resolver_dns_native_init() {
+ const char* scheme() const override { return "dns"; }
+};
+
+} // namespace
+
+} // 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) {
- gpr_log(GPR_DEBUG, "Using native dns resolver");
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+ gpr_log(GPR_DEBUG, "Using native dns resolver");
+ grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::NativeDnsResolverFactory>());
- } else {
- grpc_core::ResolverRegistry::Builder::InitRegistry();
- grpc_core::ResolverFactory* existing_factory =
- grpc_core::ResolverRegistry::LookupResolverFactory("dns");
- if (existing_factory == nullptr) {
- gpr_log(GPR_DEBUG, "Using native dns resolver");
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+ } else {
+ grpc_core::ResolverRegistry::Builder::InitRegistry();
+ grpc_core::ResolverFactory* existing_factory =
+ grpc_core::ResolverRegistry::LookupResolverFactory("dns");
+ if (existing_factory == nullptr) {
+ gpr_log(GPR_DEBUG, "Using native dns resolver");
+ grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::NativeDnsResolverFactory>());
- }
- }
-}
-
-void grpc_resolver_dns_native_shutdown() {}
+ }
+ }
+}
+
+void grpc_resolver_dns_native_shutdown() {}
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 792146ed049..07208229ec6 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
@@ -1,93 +1,93 @@
-//
-// 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.
-//
-
-// 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 <limits.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/resolver_registry.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.
+//
+
+// 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 <limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.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/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/parse_address.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/iomgr/work_serializer.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-
-#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
-
-namespace grpc_core {
-
-// This cannot be in an anonymous namespace, because it is a friend of
-// FakeResolverResponseGenerator.
-class FakeResolver : public Resolver {
- public:
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+
+#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
+
+namespace grpc_core {
+
+// This cannot be in an anonymous namespace, because it is a friend of
+// FakeResolverResponseGenerator.
+class FakeResolver : public Resolver {
+ public:
explicit FakeResolver(ResolverArgs args);
-
+
void StartLocked() override;
-
- void RequestReresolutionLocked() override;
-
- private:
- friend class FakeResolverResponseGenerator;
+
+ void RequestReresolutionLocked() override;
+
+ private:
+ friend class FakeResolverResponseGenerator;
friend class FakeResolverResponseSetter;
-
- virtual ~FakeResolver();
-
+
+ virtual ~FakeResolver();
+
void ShutdownLocked() override;
-
+
void MaybeSendResultLocked();
-
+
void ReturnReresolutionResult();
- // passed-in parameters
- grpc_channel_args* channel_args_ = nullptr;
+ // 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
- // RequestReresolutionLocked().
+ // 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;
- // if true, return failure
- bool return_failure_ = false;
+ // if true, return failure
+ bool return_failure_ = false;
// pending re-resolution
bool reresolution_closure_pending_ = false;
-};
-
+};
+
FakeResolver::FakeResolver(ResolverArgs args)
: Resolver(std::move(args.work_serializer), std::move(args.result_handler)),
response_generator_(
@@ -102,16 +102,16 @@ FakeResolver::FakeResolver(ResolverArgs args)
if (response_generator_ != nullptr) {
response_generator_->SetFakeResolver(Ref());
}
-}
-
+}
+
FakeResolver::~FakeResolver() { grpc_channel_args_destroy(channel_args_); }
-
+
void FakeResolver::StartLocked() {
started_ = true;
MaybeSendResultLocked();
-}
-
-void FakeResolver::RequestReresolutionLocked() {
+}
+
+void FakeResolver::RequestReresolutionLocked() {
if (has_reresolution_result_ || return_failure_) {
next_result_ = reresolution_result_;
has_next_result_ = true;
@@ -124,9 +124,9 @@ void FakeResolver::RequestReresolutionLocked() {
work_serializer()->Run([this]() { ReturnReresolutionResult(); },
DEBUG_LOCATION);
}
- }
-}
-
+ }
+}
+
void FakeResolver::ShutdownLocked() {
shutdown_ = true;
if (response_generator_ != nullptr) {
@@ -143,7 +143,7 @@ void FakeResolver::MaybeSendResultLocked() {
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;
+ return_failure_ = false;
} else if (has_next_result_) {
Result result;
result.addresses = std::move(next_result_.addresses);
@@ -157,15 +157,15 @@ void FakeResolver::MaybeSendResultLocked() {
result.args = grpc_channel_args_union(next_result_.args, channel_args_);
result_handler()->ReturnResult(std::move(result));
has_next_result_ = false;
- }
-}
-
+ }
+}
+
void FakeResolver::ReturnReresolutionResult() {
reresolution_closure_pending_ = false;
MaybeSendResultLocked();
Unref();
-}
-
+}
+
class FakeResolverResponseSetter {
public:
explicit FakeResolverResponseSetter(RefCountedPtr<FakeResolver> resolver,
@@ -215,10 +215,10 @@ void FakeResolverResponseSetter::SetFailureLocked() {
delete this;
}
-//
-// FakeResolverResponseGenerator
-//
-
+//
+// FakeResolverResponseGenerator
+//
+
FakeResolverResponseGenerator::FakeResolverResponseGenerator() {}
FakeResolverResponseGenerator::~FakeResolverResponseGenerator() {}
@@ -238,9 +238,9 @@ void FakeResolverResponseGenerator::SetResponse(Resolver::Result result) {
new FakeResolverResponseSetter(resolver, std::move(result));
resolver->work_serializer()->Run([arg]() { arg->SetResponseLocked(); },
DEBUG_LOCATION);
-}
-
-void FakeResolverResponseGenerator::SetReresolutionResponse(
+}
+
+void FakeResolverResponseGenerator::SetReresolutionResponse(
Resolver::Result result) {
RefCountedPtr<FakeResolver> resolver;
{
@@ -252,8 +252,8 @@ void FakeResolverResponseGenerator::SetReresolutionResponse(
resolver, std::move(result), true /* has_result */);
resolver->work_serializer()->Run(
[arg]() { arg->SetReresolutionResponseLocked(); }, DEBUG_LOCATION);
-}
-
+}
+
void FakeResolverResponseGenerator::UnsetReresolutionResponse() {
RefCountedPtr<FakeResolver> resolver;
{
@@ -267,7 +267,7 @@ void FakeResolverResponseGenerator::UnsetReresolutionResponse() {
[arg]() { arg->SetReresolutionResponseLocked(); }, DEBUG_LOCATION);
}
-void FakeResolverResponseGenerator::SetFailure() {
+void FakeResolverResponseGenerator::SetFailure() {
RefCountedPtr<FakeResolver> resolver;
{
MutexLock lock(&mu_);
@@ -278,8 +278,8 @@ void FakeResolverResponseGenerator::SetFailure() {
new FakeResolverResponseSetter(resolver, Resolver::Result());
resolver->work_serializer()->Run([arg]() { arg->SetFailureLocked(); },
DEBUG_LOCATION);
-}
-
+}
+
void FakeResolverResponseGenerator::SetFailureOnReresolution() {
RefCountedPtr<FakeResolver> resolver;
{
@@ -308,76 +308,76 @@ void FakeResolverResponseGenerator::SetFakeResolver(
}
}
-namespace {
-
-static void* response_generator_arg_copy(void* p) {
- FakeResolverResponseGenerator* generator =
- static_cast<FakeResolverResponseGenerator*>(p);
- // TODO(roth): We currently deal with this ref manually. Once the
- // new channel args code is converted to C++, find a way to track this ref
- // in a cleaner way.
- RefCountedPtr<FakeResolverResponseGenerator> copy = generator->Ref();
- copy.release();
- return p;
-}
-
-static void response_generator_arg_destroy(void* p) {
- FakeResolverResponseGenerator* generator =
- static_cast<FakeResolverResponseGenerator*>(p);
- generator->Unref();
-}
-
-static int response_generator_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
-
-static const grpc_arg_pointer_vtable response_generator_arg_vtable = {
- response_generator_arg_copy, response_generator_arg_destroy,
- response_generator_cmp};
-
-} // namespace
-
-grpc_arg FakeResolverResponseGenerator::MakeChannelArg(
- FakeResolverResponseGenerator* generator) {
- grpc_arg arg;
- arg.type = GRPC_ARG_POINTER;
- arg.key = (char*)GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR;
- arg.value.pointer.p = generator;
- arg.value.pointer.vtable = &response_generator_arg_vtable;
- return arg;
-}
-
+namespace {
+
+static void* response_generator_arg_copy(void* p) {
+ FakeResolverResponseGenerator* generator =
+ static_cast<FakeResolverResponseGenerator*>(p);
+ // TODO(roth): We currently deal with this ref manually. Once the
+ // new channel args code is converted to C++, find a way to track this ref
+ // in a cleaner way.
+ RefCountedPtr<FakeResolverResponseGenerator> copy = generator->Ref();
+ copy.release();
+ return p;
+}
+
+static void response_generator_arg_destroy(void* p) {
+ FakeResolverResponseGenerator* generator =
+ static_cast<FakeResolverResponseGenerator*>(p);
+ generator->Unref();
+}
+
+static int response_generator_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
+
+static const grpc_arg_pointer_vtable response_generator_arg_vtable = {
+ response_generator_arg_copy, response_generator_arg_destroy,
+ response_generator_cmp};
+
+} // namespace
+
+grpc_arg FakeResolverResponseGenerator::MakeChannelArg(
+ FakeResolverResponseGenerator* generator) {
+ grpc_arg arg;
+ arg.type = GRPC_ARG_POINTER;
+ arg.key = (char*)GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR;
+ arg.value.pointer.p = generator;
+ arg.value.pointer.vtable = &response_generator_arg_vtable;
+ return arg;
+}
+
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;
+ 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();
-}
-
-//
-// Factory
-//
-
-namespace {
-
-class FakeResolverFactory : public ResolverFactory {
- public:
+}
+
+//
+// Factory
+//
+
+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));
- }
-
- const char* scheme() const override { return "fake"; }
-};
-
-} // namespace
-
-} // namespace grpc_core
-
-void grpc_resolver_fake_init() {
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+ }
+
+ const char* scheme() const override { return "fake"; }
+};
+
+} // namespace
+
+} // namespace grpc_core
+
+void grpc_resolver_fake_init() {
+ grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::FakeResolverFactory>());
-}
-
-void grpc_resolver_fake_shutdown() {}
+}
+
+void grpc_resolver_fake_shutdown() {}
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 b9fd90c069f..533d9b0f02e 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
@@ -1,93 +1,93 @@
-//
-// 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_RESOLVER_FAKE_FAKE_RESOLVER_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FAKE_FAKE_RESOLVER_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_RESOLVER_FAKE_FAKE_RESOLVER_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FAKE_FAKE_RESOLVER_H
+
+#include <grpc/support/port_platform.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/channel/channel_args.h"
+#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/iomgr/error.h"
-
-#define GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR \
- "grpc.fake_resolver.response_generator"
-
-namespace grpc_core {
-
-class FakeResolver;
-
-/// A mechanism for generating responses for the fake resolver.
-/// An instance of this class is passed to the fake resolver via a channel
-/// argument (see \a MakeChannelArg()) and used to inject and trigger custom
-/// resolutions.
-// TODO(roth): I would ideally like this to be InternallyRefCounted
-// instead of RefCounted, but external refs are currently needed to
-// encode this in channel args. Once channel_args are converted to C++,
-// see if we can find a way to fix this.
-class FakeResolverResponseGenerator
- : public RefCounted<FakeResolverResponseGenerator> {
- public:
+
+#define GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR \
+ "grpc.fake_resolver.response_generator"
+
+namespace grpc_core {
+
+class FakeResolver;
+
+/// A mechanism for generating responses for the fake resolver.
+/// An instance of this class is passed to the fake resolver via a channel
+/// argument (see \a MakeChannelArg()) and used to inject and trigger custom
+/// resolutions.
+// TODO(roth): I would ideally like this to be InternallyRefCounted
+// instead of RefCounted, but external refs are currently needed to
+// encode this in channel args. Once channel_args are converted to C++,
+// see if we can find a way to fix this.
+class FakeResolverResponseGenerator
+ : public RefCounted<FakeResolverResponseGenerator> {
+ public:
FakeResolverResponseGenerator();
~FakeResolverResponseGenerator();
-
- // Instructs the fake resolver associated with the response generator
+
+ // 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);
-
- // 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.
+
+ // 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);
-
+
// 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();
-
+ void SetFailure();
+
// Same as SetFailure(), but instead of returning the error
// immediately, waits for the next call to RequestReresolutionLocked().
void SetFailureOnReresolution();
- // Returns a channel arg containing \a generator.
- static grpc_arg MakeChannelArg(FakeResolverResponseGenerator* generator);
-
- // Returns the response generator in \a args, or null if not found.
+ // Returns a channel arg containing \a generator.
+ static grpc_arg MakeChannelArg(FakeResolverResponseGenerator* generator);
+
+ // Returns the response generator in \a args, or null if not found.
static RefCountedPtr<FakeResolverResponseGenerator> GetFromArgs(
- const grpc_channel_args* args);
-
- private:
- friend class FakeResolver;
+ 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;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FAKE_FAKE_RESOLVER_H \
- */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FAKE_FAKE_RESOLVER_H \
+ */
diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/README.md b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/README.md
index e307ba88f57..a9cbd444e64 100644
--- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/README.md
+++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/README.md
@@ -1 +1 @@
-Support for resolving ipv4:, ipv6:, unix: schemes
+Support for resolving ipv4:, ipv6:, unix: schemes
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 b52bd8afba5..94a772e7880 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
@@ -1,70 +1,70 @@
-/*
- *
- * 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/resolver_registry.h"
+/*
+ *
+ * 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.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/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/parse_address.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/iomgr/work_serializer.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-
-namespace grpc_core {
-
-namespace {
-
-class SockaddrResolver : public Resolver {
- public:
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+
+namespace grpc_core {
+
+namespace {
+
+class SockaddrResolver : public Resolver {
+ public:
SockaddrResolver(ServerAddressList addresses, ResolverArgs args);
~SockaddrResolver() override;
-
+
void StartLocked() override;
-
+
void ShutdownLocked() override {}
-
- private:
+
+ private:
ServerAddressList addresses_;
const grpc_channel_args* channel_args_ = nullptr;
-};
-
+};
+
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)) {}
-
-SockaddrResolver::~SockaddrResolver() {
- grpc_channel_args_destroy(channel_args_);
-}
-
+ channel_args_(grpc_channel_args_copy(args.args)) {}
+
+SockaddrResolver::~SockaddrResolver() {
+ grpc_channel_args_destroy(channel_args_);
+}
+
void SockaddrResolver::StartLocked() {
Result result;
result.addresses = std::move(addresses_);
@@ -72,29 +72,29 @@ void SockaddrResolver::StartLocked() {
result.args = channel_args_;
channel_args_ = nullptr;
result_handler()->ReturnResult(std::move(result));
-}
-
-//
-// Factory
-//
-
+}
+
+//
+// Factory
+//
+
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, "")) {
- gpr_log(GPR_ERROR, "authority-based URIs not supported by the %s scheme",
+ gpr_log(GPR_ERROR, "authority-based URIs not supported by the %s scheme",
uri->scheme);
return false;
- }
- // Construct addresses.
- grpc_slice path_slice =
+ }
+ // Construct addresses.
+ grpc_slice path_slice =
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;
+ 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(
@@ -104,13 +104,13 @@ bool ParseUri(const grpc_uri* uri,
if (!parse(&ith_uri, &addr)) {
errors_found = true;
break;
- }
+ }
if (addresses != nullptr) {
addresses->emplace_back(addr, nullptr /* args */);
}
- }
- grpc_slice_buffer_destroy_internal(&path_parts);
- grpc_slice_unref_internal(path_slice);
+ }
+ grpc_slice_buffer_destroy_internal(&path_parts);
+ grpc_slice_unref_internal(path_slice);
return !errors_found;
}
@@ -119,70 +119,70 @@ OrphanablePtr<Resolver> CreateSockaddrResolver(
bool parse(const grpc_uri* uri, grpc_resolved_address* dst)) {
ServerAddressList addresses;
if (!ParseUri(args.uri, parse, &addresses)) return nullptr;
- // Instantiate resolver.
+ // Instantiate resolver.
return MakeOrphanable<SockaddrResolver>(std::move(addresses),
std::move(args));
-}
-
-class IPv4ResolverFactory : public ResolverFactory {
- public:
+}
+
+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);
}
- const char* scheme() const override { return "ipv4"; }
-};
-
-class IPv6ResolverFactory : public ResolverFactory {
- public:
+ 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);
}
- const char* scheme() const override { return "ipv6"; }
-};
-
-#ifdef GRPC_HAVE_UNIX_SOCKET
-class UnixResolverFactory : public ResolverFactory {
- public:
+ 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);
- }
-
+ }
+
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
-
-} // namespace
-
-} // namespace grpc_core
-
-void grpc_resolver_sockaddr_init() {
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+ const char* scheme() const override { return "unix"; }
+};
+#endif // GRPC_HAVE_UNIX_SOCKET
+
+} // namespace
+
+} // namespace grpc_core
+
+void grpc_resolver_sockaddr_init() {
+ grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::IPv4ResolverFactory>());
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+ grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::IPv6ResolverFactory>());
-#ifdef GRPC_HAVE_UNIX_SOCKET
- grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
+#ifdef GRPC_HAVE_UNIX_SOCKET
+ grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
y_absl::make_unique<grpc_core::UnixResolverFactory>());
-#endif
-}
-
-void grpc_resolver_sockaddr_shutdown() {}
+#endif
+}
+
+void grpc_resolver_sockaddr_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 d8dd801ae09..b82ad6aea3b 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
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FACTORY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FACTORY_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/resolver.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/iomgr/pollset_set.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_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FACTORY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FACTORY_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/resolver.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/iomgr/pollset_set.h"
#include "src/core/lib/uri/uri_parser.h"
-
-namespace grpc_core {
-
-struct ResolverArgs {
- /// The parsed URI to resolve.
- grpc_uri* uri = nullptr;
- /// Channel args to be included in resolver results.
- const grpc_channel_args* args = nullptr;
- /// Used to drive I/O in the name resolution process.
- grpc_pollset_set* pollset_set = nullptr;
+
+namespace grpc_core {
+
+struct ResolverArgs {
+ /// The parsed URI to resolve.
+ grpc_uri* uri = nullptr;
+ /// Channel args to be included in resolver results.
+ const grpc_channel_args* args = nullptr;
+ /// Used to drive I/O in the name resolution process.
+ 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;
-};
-
-class ResolverFactory {
- public:
+};
+
+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 new resolver instance.
+ /// Returns a new resolver instance.
virtual OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const = 0;
-
- /// Returns a string representing the default authority to use for this
- /// scheme.
+
+ /// Returns a string representing the default authority to use for this
+ /// scheme.
virtual grpc_core::UniquePtr<char> GetDefaultAuthority(grpc_uri* uri) const {
- const char* path = uri->path;
- if (path[0] == '/') ++path;
+ const char* path = uri->path;
+ if (path[0] == '/') ++path;
return grpc_core::UniquePtr<char>(gpr_strdup(path));
- }
-
- /// Returns the URI scheme that this factory implements.
- /// Caller does NOT take ownership of result.
+ }
+
+ /// Returns the URI scheme that this factory implements.
+ /// Caller does NOT take ownership of result.
virtual const char* scheme() const = 0;
-
- virtual ~ResolverFactory() {}
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FACTORY_H */
+
+ virtual ~ResolverFactory() {}
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FACTORY_H */
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 4cea1ec382c..20d467bd136 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
@@ -1,140 +1,140 @@
-/*
- *
- * 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/resolver_registry.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/resolver_registry.h"
+
+#include <string.h>
+
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-namespace grpc_core {
-
-namespace {
-
-class RegistryState {
- public:
- RegistryState() : default_prefix_(gpr_strdup("dns:///")) {}
-
- void SetDefaultPrefix(const char* default_resolver_prefix) {
- GPR_ASSERT(default_resolver_prefix != nullptr);
- GPR_ASSERT(*default_resolver_prefix != '\0');
- default_prefix_.reset(gpr_strdup(default_resolver_prefix));
- }
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+namespace grpc_core {
+
+namespace {
+
+class RegistryState {
+ public:
+ RegistryState() : default_prefix_(gpr_strdup("dns:///")) {}
+
+ void SetDefaultPrefix(const char* default_resolver_prefix) {
+ GPR_ASSERT(default_resolver_prefix != nullptr);
+ GPR_ASSERT(*default_resolver_prefix != '\0');
+ default_prefix_.reset(gpr_strdup(default_resolver_prefix));
+ }
+
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);
- }
- factories_.push_back(std::move(factory));
- }
-
- ResolverFactory* LookupResolverFactory(const char* scheme) const {
- for (size_t i = 0; i < factories_.size(); ++i) {
- if (strcmp(scheme, factories_[i]->scheme()) == 0) {
- return factories_[i].get();
- }
- }
- return nullptr;
- }
-
- // Returns the factory for the scheme of \a target. If \a target does
- // not parse as a URI, prepends \a default_prefix_ and tries again.
- // If URI parsing is successful (in either attempt), sets \a uri to
- // point to the parsed URI.
- // If \a default_prefix_ needs to be prepended, sets \a canonical_target
- // to the canonical target string.
- ResolverFactory* FindResolverFactory(const char* target, grpc_uri** uri,
+ for (size_t i = 0; i < factories_.size(); ++i) {
+ GPR_ASSERT(strcmp(factories_[i]->scheme(), factory->scheme()) != 0);
+ }
+ factories_.push_back(std::move(factory));
+ }
+
+ ResolverFactory* LookupResolverFactory(const char* scheme) const {
+ for (size_t i = 0; i < factories_.size(); ++i) {
+ if (strcmp(scheme, factories_[i]->scheme()) == 0) {
+ return factories_[i].get();
+ }
+ }
+ return nullptr;
+ }
+
+ // Returns the factory for the scheme of \a target. If \a target does
+ // not parse as a URI, prepends \a default_prefix_ and tries again.
+ // If URI parsing is successful (in either attempt), sets \a uri to
+ // point to the parsed URI.
+ // If \a default_prefix_ needs to be prepended, sets \a canonical_target
+ // to the canonical target string.
+ ResolverFactory* FindResolverFactory(const char* target, grpc_uri** uri,
TString* canonical_target) const {
- GPR_ASSERT(uri != nullptr);
- *uri = grpc_uri_parse(target, 1);
- ResolverFactory* factory =
- *uri == nullptr ? nullptr : LookupResolverFactory((*uri)->scheme);
- if (factory == nullptr) {
- grpc_uri_destroy(*uri);
+ GPR_ASSERT(uri != nullptr);
+ *uri = grpc_uri_parse(target, 1);
+ ResolverFactory* factory =
+ *uri == nullptr ? nullptr : LookupResolverFactory((*uri)->scheme);
+ if (factory == nullptr) {
+ grpc_uri_destroy(*uri);
*canonical_target = y_absl::StrCat(default_prefix_.get(), target);
*uri = grpc_uri_parse(canonical_target->c_str(), 1);
- factory =
- *uri == nullptr ? nullptr : LookupResolverFactory((*uri)->scheme);
- if (factory == nullptr) {
- grpc_uri_destroy(grpc_uri_parse(target, 0));
+ factory =
+ *uri == nullptr ? nullptr : LookupResolverFactory((*uri)->scheme);
+ if (factory == nullptr) {
+ grpc_uri_destroy(grpc_uri_parse(target, 0));
grpc_uri_destroy(grpc_uri_parse(canonical_target->c_str(), 0));
- gpr_log(GPR_ERROR, "don't know how to resolve '%s' or '%s'", target,
+ gpr_log(GPR_ERROR, "don't know how to resolve '%s' or '%s'", target,
canonical_target->c_str());
- }
- }
- return factory;
- }
-
- private:
- // We currently support 10 factories without doing additional
- // allocation. This number could be raised if there is a case where
- // more factories are needed and the additional allocations are
- // hurting performance (which is unlikely, since these allocations
- // only occur at gRPC initialization time).
+ }
+ }
+ return factory;
+ }
+
+ private:
+ // We currently support 10 factories without doing additional
+ // allocation. This number could be raised if there is a case where
+ // more factories are needed and the additional allocations are
+ // 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_;
-};
-
-static RegistryState* g_state = nullptr;
-
-} // namespace
-
-//
-// ResolverRegistry::Builder
-//
-
-void ResolverRegistry::Builder::InitRegistry() {
+};
+
+static RegistryState* g_state = nullptr;
+
+} // namespace
+
+//
+// ResolverRegistry::Builder
+//
+
+void ResolverRegistry::Builder::InitRegistry() {
if (g_state == nullptr) g_state = new RegistryState();
-}
-
-void ResolverRegistry::Builder::ShutdownRegistry() {
+}
+
+void ResolverRegistry::Builder::ShutdownRegistry() {
delete g_state;
- g_state = nullptr;
-}
-
-void ResolverRegistry::Builder::SetDefaultPrefix(
- const char* default_resolver_prefix) {
- InitRegistry();
- g_state->SetDefaultPrefix(default_resolver_prefix);
-}
-
-void ResolverRegistry::Builder::RegisterResolverFactory(
+ g_state = nullptr;
+}
+
+void ResolverRegistry::Builder::SetDefaultPrefix(
+ const char* default_resolver_prefix) {
+ InitRegistry();
+ g_state->SetDefaultPrefix(default_resolver_prefix);
+}
+
+void ResolverRegistry::Builder::RegisterResolverFactory(
std::unique_ptr<ResolverFactory> factory) {
- InitRegistry();
- g_state->RegisterResolverFactory(std::move(factory));
-}
-
-//
-// ResolverRegistry
-//
-
-ResolverFactory* ResolverRegistry::LookupResolverFactory(const char* scheme) {
- GPR_ASSERT(g_state != nullptr);
- return g_state->LookupResolverFactory(scheme);
-}
-
+ InitRegistry();
+ g_state->RegisterResolverFactory(std::move(factory));
+}
+
+//
+// ResolverRegistry
+//
+
+ResolverFactory* ResolverRegistry::LookupResolverFactory(const char* scheme) {
+ GPR_ASSERT(g_state != nullptr);
+ return g_state->LookupResolverFactory(scheme);
+}
+
bool ResolverRegistry::IsValidTarget(const char* target) {
grpc_uri* uri = nullptr;
TString canonical_target;
@@ -145,52 +145,52 @@ bool ResolverRegistry::IsValidTarget(const char* target) {
return result;
}
-OrphanablePtr<Resolver> ResolverRegistry::CreateResolver(
- const char* target, const grpc_channel_args* args,
+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) {
- GPR_ASSERT(g_state != nullptr);
- grpc_uri* uri = nullptr;
+ GPR_ASSERT(g_state != nullptr);
+ grpc_uri* uri = nullptr;
TString canonical_target;
- ResolverFactory* factory =
- g_state->FindResolverFactory(target, &uri, &canonical_target);
- ResolverArgs resolver_args;
- resolver_args.uri = uri;
- resolver_args.args = args;
- resolver_args.pollset_set = pollset_set;
+ ResolverFactory* factory =
+ g_state->FindResolverFactory(target, &uri, &canonical_target);
+ ResolverArgs resolver_args;
+ resolver_args.uri = uri;
+ 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);
- OrphanablePtr<Resolver> resolver =
+ OrphanablePtr<Resolver> resolver =
factory == nullptr ? nullptr
: factory->CreateResolver(std::move(resolver_args));
- grpc_uri_destroy(uri);
- return resolver;
-}
-
+ grpc_uri_destroy(uri);
+ return resolver;
+}
+
grpc_core::UniquePtr<char> ResolverRegistry::GetDefaultAuthority(
const char* target) {
- GPR_ASSERT(g_state != nullptr);
- grpc_uri* uri = nullptr;
+ GPR_ASSERT(g_state != nullptr);
+ grpc_uri* uri = nullptr;
TString canonical_target;
- ResolverFactory* factory =
- g_state->FindResolverFactory(target, &uri, &canonical_target);
+ ResolverFactory* factory =
+ g_state->FindResolverFactory(target, &uri, &canonical_target);
grpc_core::UniquePtr<char> authority =
- factory == nullptr ? nullptr : factory->GetDefaultAuthority(uri);
- grpc_uri_destroy(uri);
- return authority;
-}
-
+ factory == nullptr ? nullptr : factory->GetDefaultAuthority(uri);
+ grpc_uri_destroy(uri);
+ return authority;
+}
+
grpc_core::UniquePtr<char> ResolverRegistry::AddDefaultPrefixIfNeeded(
const char* target) {
- GPR_ASSERT(g_state != nullptr);
- grpc_uri* uri = nullptr;
+ GPR_ASSERT(g_state != nullptr);
+ grpc_uri* uri = nullptr;
TString canonical_target;
- g_state->FindResolverFactory(target, &uri, &canonical_target);
- grpc_uri_destroy(uri);
+ g_state->FindResolverFactory(target, &uri, &canonical_target);
+ grpc_uri_destroy(uri);
return grpc_core::UniquePtr<char>(canonical_target.empty()
? gpr_strdup(target)
: gpr_strdup(canonical_target.c_str()));
-}
-
-} // namespace grpc_core
+}
+
+} // namespace grpc_core
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 bf34216b2cf..ea1b3971563 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
@@ -1,65 +1,65 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_REGISTRY_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_REGISTRY_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/resolver_factory.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/iomgr/pollset_set.h"
-
-namespace grpc_core {
-
-class ResolverRegistry {
- public:
- /// Methods used to create and populate the ResolverRegistry.
- /// NOT THREAD SAFE -- to be used only during global gRPC
- /// initialization and shutdown.
- class Builder {
- public:
- /// Global initialization and shutdown hooks.
- static void InitRegistry();
- static void ShutdownRegistry();
-
- /// Sets the default URI prefix to \a default_prefix.
- /// Calls InitRegistry() if it has not already been called.
- static void SetDefaultPrefix(const char* default_prefix);
-
- /// 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.
+/*
+ *
+ * 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_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_REGISTRY_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_REGISTRY_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/client_channel/resolver_factory.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/iomgr/pollset_set.h"
+
+namespace grpc_core {
+
+class ResolverRegistry {
+ public:
+ /// Methods used to create and populate the ResolverRegistry.
+ /// NOT THREAD SAFE -- to be used only during global gRPC
+ /// initialization and shutdown.
+ class Builder {
+ public:
+ /// Global initialization and shutdown hooks.
+ static void InitRegistry();
+ static void ShutdownRegistry();
+
+ /// Sets the default URI prefix to \a default_prefix.
+ /// Calls InitRegistry() if it has not already been called.
+ static void SetDefaultPrefix(const char* default_prefix);
+
+ /// 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);
- };
-
+ };
+
/// 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.
- /// If parsing fails or there is no factory for the URI's scheme,
- /// prepends default_prefix to target and tries again.
- /// If a resolver factory is found, uses it to instantiate a resolver and
- /// returns it; otherwise, returns nullptr.
+ /// 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.
+ /// If parsing fails or there is no factory for the URI's scheme,
+ /// prepends default_prefix to target and tries again.
+ /// If a resolver factory is found, uses it to instantiate a resolver and
+ /// returns it; otherwise, returns nullptr.
/// \a args, \a pollset_set, and \a work_serializer are passed to the
/// factory's \a CreateResolver() method. \a args are the channel args to be
/// included in resolver results. \a pollset_set is used to drive I/O in the
@@ -71,19 +71,19 @@ class ResolverRegistry {
grpc_pollset_set* pollset_set,
std::shared_ptr<WorkSerializer> work_serializer,
std::unique_ptr<Resolver::ResultHandler> result_handler);
-
- /// Returns the default authority to pass from a client for \a target.
+
+ /// Returns the default authority to pass from a client for \a target.
static grpc_core::UniquePtr<char> GetDefaultAuthority(const char* target);
-
- /// Returns \a target with the default prefix prepended, if needed.
+
+ /// Returns \a target with the default prefix prepended, if needed.
static grpc_core::UniquePtr<char> AddDefaultPrefixIfNeeded(
const char* target);
-
- /// Returns the resolver factory for \a scheme.
- /// Caller does NOT own the return value.
- static ResolverFactory* LookupResolverFactory(const char* scheme);
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_REGISTRY_H */
+
+ /// Returns the resolver factory for \a scheme.
+ /// Caller does NOT own the return value.
+ static ResolverFactory* LookupResolverFactory(const char* scheme);
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_REGISTRY_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 65df8034d71..486f0016e59 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
@@ -1,191 +1,191 @@
-/*
- *
- * 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/ext/filters/client_channel/retry_throttle.h"
-
-#include <limits.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/avl/avl.h"
-
-namespace grpc_core {
-namespace internal {
-
-//
-// ServerRetryThrottleData
-//
-
-ServerRetryThrottleData::ServerRetryThrottleData(
- intptr_t max_milli_tokens, intptr_t milli_token_ratio,
- ServerRetryThrottleData* old_throttle_data)
- : max_milli_tokens_(max_milli_tokens),
- milli_token_ratio_(milli_token_ratio) {
- intptr_t initial_milli_tokens = max_milli_tokens;
- // If there was a pre-existing entry for this server name, initialize
- // the token count by scaling proportionately to the old data. This
- // ensures that if we're already throttling retries on the old scale,
- // we will start out doing the same thing on the new one.
- if (old_throttle_data != nullptr) {
- double token_fraction =
- static_cast<intptr_t>(
- gpr_atm_acq_load(&old_throttle_data->milli_tokens_)) /
- static_cast<double>(old_throttle_data->max_milli_tokens_);
- initial_milli_tokens =
- static_cast<intptr_t>(token_fraction * max_milli_tokens);
- }
- gpr_atm_rel_store(&milli_tokens_, static_cast<gpr_atm>(initial_milli_tokens));
- // If there was a pre-existing entry, mark it as stale and give it a
- // pointer to the new entry, which is its replacement.
- if (old_throttle_data != nullptr) {
- Ref().release(); // Ref held by pre-existing entry.
- gpr_atm_rel_store(&old_throttle_data->replacement_,
- reinterpret_cast<gpr_atm>(this));
- }
-}
-
-ServerRetryThrottleData::~ServerRetryThrottleData() {
- ServerRetryThrottleData* replacement =
- reinterpret_cast<ServerRetryThrottleData*>(
- gpr_atm_acq_load(&replacement_));
- if (replacement != nullptr) {
- replacement->Unref();
- }
-}
-
-void ServerRetryThrottleData::GetReplacementThrottleDataIfNeeded(
- ServerRetryThrottleData** throttle_data) {
- while (true) {
- ServerRetryThrottleData* new_throttle_data =
- reinterpret_cast<ServerRetryThrottleData*>(
- gpr_atm_acq_load(&(*throttle_data)->replacement_));
- if (new_throttle_data == nullptr) return;
- *throttle_data = new_throttle_data;
- }
-}
-
-bool ServerRetryThrottleData::RecordFailure() {
- // First, check if we are stale and need to be replaced.
- ServerRetryThrottleData* throttle_data = this;
- GetReplacementThrottleDataIfNeeded(&throttle_data);
- // We decrement milli_tokens by 1000 (1 token) for each failure.
- const intptr_t new_value =
- static_cast<intptr_t>(gpr_atm_no_barrier_clamped_add(
- &throttle_data->milli_tokens_, static_cast<gpr_atm>(-1000),
- static_cast<gpr_atm>(0),
- static_cast<gpr_atm>(throttle_data->max_milli_tokens_)));
- // Retries are allowed as long as the new value is above the threshold
- // (max_milli_tokens / 2).
- return new_value > throttle_data->max_milli_tokens_ / 2;
-}
-
-void ServerRetryThrottleData::RecordSuccess() {
- // First, check if we are stale and need to be replaced.
- ServerRetryThrottleData* throttle_data = this;
- GetReplacementThrottleDataIfNeeded(&throttle_data);
- // We increment milli_tokens by milli_token_ratio for each success.
- gpr_atm_no_barrier_clamped_add(
- &throttle_data->milli_tokens_,
- static_cast<gpr_atm>(throttle_data->milli_token_ratio_),
- static_cast<gpr_atm>(0),
- static_cast<gpr_atm>(throttle_data->max_milli_tokens_));
-}
-
-//
-// avl vtable for string -> server_retry_throttle_data map
-//
-
-namespace {
-
+/*
+ *
+ * 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/ext/filters/client_channel/retry_throttle.h"
+
+#include <limits.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/avl/avl.h"
+
+namespace grpc_core {
+namespace internal {
+
+//
+// ServerRetryThrottleData
+//
+
+ServerRetryThrottleData::ServerRetryThrottleData(
+ intptr_t max_milli_tokens, intptr_t milli_token_ratio,
+ ServerRetryThrottleData* old_throttle_data)
+ : max_milli_tokens_(max_milli_tokens),
+ milli_token_ratio_(milli_token_ratio) {
+ intptr_t initial_milli_tokens = max_milli_tokens;
+ // If there was a pre-existing entry for this server name, initialize
+ // the token count by scaling proportionately to the old data. This
+ // ensures that if we're already throttling retries on the old scale,
+ // we will start out doing the same thing on the new one.
+ if (old_throttle_data != nullptr) {
+ double token_fraction =
+ static_cast<intptr_t>(
+ gpr_atm_acq_load(&old_throttle_data->milli_tokens_)) /
+ static_cast<double>(old_throttle_data->max_milli_tokens_);
+ initial_milli_tokens =
+ static_cast<intptr_t>(token_fraction * max_milli_tokens);
+ }
+ gpr_atm_rel_store(&milli_tokens_, static_cast<gpr_atm>(initial_milli_tokens));
+ // If there was a pre-existing entry, mark it as stale and give it a
+ // pointer to the new entry, which is its replacement.
+ if (old_throttle_data != nullptr) {
+ Ref().release(); // Ref held by pre-existing entry.
+ gpr_atm_rel_store(&old_throttle_data->replacement_,
+ reinterpret_cast<gpr_atm>(this));
+ }
+}
+
+ServerRetryThrottleData::~ServerRetryThrottleData() {
+ ServerRetryThrottleData* replacement =
+ reinterpret_cast<ServerRetryThrottleData*>(
+ gpr_atm_acq_load(&replacement_));
+ if (replacement != nullptr) {
+ replacement->Unref();
+ }
+}
+
+void ServerRetryThrottleData::GetReplacementThrottleDataIfNeeded(
+ ServerRetryThrottleData** throttle_data) {
+ while (true) {
+ ServerRetryThrottleData* new_throttle_data =
+ reinterpret_cast<ServerRetryThrottleData*>(
+ gpr_atm_acq_load(&(*throttle_data)->replacement_));
+ if (new_throttle_data == nullptr) return;
+ *throttle_data = new_throttle_data;
+ }
+}
+
+bool ServerRetryThrottleData::RecordFailure() {
+ // First, check if we are stale and need to be replaced.
+ ServerRetryThrottleData* throttle_data = this;
+ GetReplacementThrottleDataIfNeeded(&throttle_data);
+ // We decrement milli_tokens by 1000 (1 token) for each failure.
+ const intptr_t new_value =
+ static_cast<intptr_t>(gpr_atm_no_barrier_clamped_add(
+ &throttle_data->milli_tokens_, static_cast<gpr_atm>(-1000),
+ static_cast<gpr_atm>(0),
+ static_cast<gpr_atm>(throttle_data->max_milli_tokens_)));
+ // Retries are allowed as long as the new value is above the threshold
+ // (max_milli_tokens / 2).
+ return new_value > throttle_data->max_milli_tokens_ / 2;
+}
+
+void ServerRetryThrottleData::RecordSuccess() {
+ // First, check if we are stale and need to be replaced.
+ ServerRetryThrottleData* throttle_data = this;
+ GetReplacementThrottleDataIfNeeded(&throttle_data);
+ // We increment milli_tokens by milli_token_ratio for each success.
+ gpr_atm_no_barrier_clamped_add(
+ &throttle_data->milli_tokens_,
+ static_cast<gpr_atm>(throttle_data->milli_token_ratio_),
+ static_cast<gpr_atm>(0),
+ static_cast<gpr_atm>(throttle_data->max_milli_tokens_));
+}
+
+//
+// avl vtable for string -> server_retry_throttle_data map
+//
+
+namespace {
+
void* copy_server_name(void* key, void* /*unused*/) {
- return gpr_strdup(static_cast<const char*>(key));
-}
-
+ return gpr_strdup(static_cast<const char*>(key));
+}
+
long compare_server_name(void* key1, void* key2, void* /*unused*/) {
- return strcmp(static_cast<const char*>(key1), static_cast<const char*>(key2));
-}
-
+ return strcmp(static_cast<const char*>(key1), static_cast<const char*>(key2));
+}
+
void destroy_server_retry_throttle_data(void* value, void* /*unused*/) {
- ServerRetryThrottleData* throttle_data =
- static_cast<ServerRetryThrottleData*>(value);
- throttle_data->Unref();
-}
-
+ ServerRetryThrottleData* throttle_data =
+ static_cast<ServerRetryThrottleData*>(value);
+ throttle_data->Unref();
+}
+
void* copy_server_retry_throttle_data(void* value, void* /*unused*/) {
- ServerRetryThrottleData* throttle_data =
- static_cast<ServerRetryThrottleData*>(value);
- return throttle_data->Ref().release();
-}
-
+ ServerRetryThrottleData* throttle_data =
+ static_cast<ServerRetryThrottleData*>(value);
+ return throttle_data->Ref().release();
+}
+
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,
- destroy_server_retry_throttle_data, copy_server_retry_throttle_data};
-
-} // namespace
-
-//
-// ServerRetryThrottleMap
-//
-
-static gpr_mu g_mu;
-static grpc_avl g_avl;
-
-void ServerRetryThrottleMap::Init() {
- gpr_mu_init(&g_mu);
- g_avl = grpc_avl_create(&avl_vtable);
-}
-
-void ServerRetryThrottleMap::Shutdown() {
- gpr_mu_destroy(&g_mu);
- grpc_avl_unref(g_avl, nullptr);
-}
-
-RefCountedPtr<ServerRetryThrottleData> ServerRetryThrottleMap::GetDataForServer(
- const char* server_name, intptr_t max_milli_tokens,
- intptr_t milli_token_ratio) {
- RefCountedPtr<ServerRetryThrottleData> result;
- gpr_mu_lock(&g_mu);
- ServerRetryThrottleData* throttle_data =
- static_cast<ServerRetryThrottleData*>(
- grpc_avl_get(g_avl, const_cast<char*>(server_name), nullptr));
- if (throttle_data == nullptr ||
- throttle_data->max_milli_tokens() != max_milli_tokens ||
- throttle_data->milli_token_ratio() != milli_token_ratio) {
- // Entry not found, or found with old parameters. Create a new one.
- result = MakeRefCounted<ServerRetryThrottleData>(
- max_milli_tokens, milli_token_ratio, throttle_data);
- g_avl = grpc_avl_add(g_avl, gpr_strdup(server_name),
- result->Ref().release(), nullptr);
- } else {
- // Entry found. Return a new ref to it.
- result = throttle_data->Ref();
- }
- gpr_mu_unlock(&g_mu);
- return result;
-}
-
-} // namespace internal
-} // namespace grpc_core
+
+const grpc_avl_vtable avl_vtable = {
+ destroy_server_name, copy_server_name, compare_server_name,
+ destroy_server_retry_throttle_data, copy_server_retry_throttle_data};
+
+} // namespace
+
+//
+// ServerRetryThrottleMap
+//
+
+static gpr_mu g_mu;
+static grpc_avl g_avl;
+
+void ServerRetryThrottleMap::Init() {
+ gpr_mu_init(&g_mu);
+ g_avl = grpc_avl_create(&avl_vtable);
+}
+
+void ServerRetryThrottleMap::Shutdown() {
+ gpr_mu_destroy(&g_mu);
+ grpc_avl_unref(g_avl, nullptr);
+}
+
+RefCountedPtr<ServerRetryThrottleData> ServerRetryThrottleMap::GetDataForServer(
+ const char* server_name, intptr_t max_milli_tokens,
+ intptr_t milli_token_ratio) {
+ RefCountedPtr<ServerRetryThrottleData> result;
+ gpr_mu_lock(&g_mu);
+ ServerRetryThrottleData* throttle_data =
+ static_cast<ServerRetryThrottleData*>(
+ grpc_avl_get(g_avl, const_cast<char*>(server_name), nullptr));
+ if (throttle_data == nullptr ||
+ throttle_data->max_milli_tokens() != max_milli_tokens ||
+ throttle_data->milli_token_ratio() != milli_token_ratio) {
+ // Entry not found, or found with old parameters. Create a new one.
+ result = MakeRefCounted<ServerRetryThrottleData>(
+ max_milli_tokens, milli_token_ratio, throttle_data);
+ g_avl = grpc_avl_add(g_avl, gpr_strdup(server_name),
+ result->Ref().release(), nullptr);
+ } else {
+ // Entry found. Return a new ref to it.
+ result = throttle_data->Ref();
+ }
+ gpr_mu_unlock(&g_mu);
+ return result;
+}
+
+} // namespace internal
+} // namespace grpc_core
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 897a617f59a..38390a50f48 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
@@ -1,77 +1,77 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_RETRY_THROTTLE_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RETRY_THROTTLE_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RETRY_THROTTLE_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RETRY_THROTTLE_H
+
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/ref_counted.h"
-
-namespace grpc_core {
-namespace internal {
-
-/// Tracks retry throttling data for an individual server name.
-class ServerRetryThrottleData : public RefCounted<ServerRetryThrottleData> {
- public:
- ServerRetryThrottleData(intptr_t max_milli_tokens, intptr_t milli_token_ratio,
- ServerRetryThrottleData* old_throttle_data);
+#include "src/core/lib/gprpp/ref_counted.h"
+
+namespace grpc_core {
+namespace internal {
+
+/// Tracks retry throttling data for an individual server name.
+class ServerRetryThrottleData : public RefCounted<ServerRetryThrottleData> {
+ public:
+ ServerRetryThrottleData(intptr_t max_milli_tokens, intptr_t milli_token_ratio,
+ ServerRetryThrottleData* old_throttle_data);
~ServerRetryThrottleData();
-
- /// Records a failure. Returns true if it's okay to send a retry.
- bool RecordFailure();
-
- /// Records a success.
- void RecordSuccess();
-
- intptr_t max_milli_tokens() const { return max_milli_tokens_; }
- intptr_t milli_token_ratio() const { return milli_token_ratio_; }
-
- private:
- void GetReplacementThrottleDataIfNeeded(
- ServerRetryThrottleData** throttle_data);
-
- const intptr_t max_milli_tokens_;
- const intptr_t milli_token_ratio_;
- gpr_atm milli_tokens_;
- // A pointer to the replacement for this ServerRetryThrottleData entry.
- // If non-nullptr, then this entry is stale and must not be used.
- // We hold a reference to the replacement.
- gpr_atm replacement_ = 0;
-};
-
-/// Global map of server name to retry throttle data.
-class ServerRetryThrottleMap {
- public:
- /// Initializes global map of failure data for each server name.
- static void Init();
- /// Shuts down global map of failure data for each server name.
- static void Shutdown();
-
- /// Returns the failure data for \a server_name, creating a new entry if
- /// needed.
- static RefCountedPtr<ServerRetryThrottleData> GetDataForServer(
- const char* server_name, intptr_t max_milli_tokens,
- intptr_t milli_token_ratio);
-};
-
-} // namespace internal
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RETRY_THROTTLE_H */
+
+ /// Records a failure. Returns true if it's okay to send a retry.
+ bool RecordFailure();
+
+ /// Records a success.
+ void RecordSuccess();
+
+ intptr_t max_milli_tokens() const { return max_milli_tokens_; }
+ intptr_t milli_token_ratio() const { return milli_token_ratio_; }
+
+ private:
+ void GetReplacementThrottleDataIfNeeded(
+ ServerRetryThrottleData** throttle_data);
+
+ const intptr_t max_milli_tokens_;
+ const intptr_t milli_token_ratio_;
+ gpr_atm milli_tokens_;
+ // A pointer to the replacement for this ServerRetryThrottleData entry.
+ // If non-nullptr, then this entry is stale and must not be used.
+ // We hold a reference to the replacement.
+ gpr_atm replacement_ = 0;
+};
+
+/// Global map of server name to retry throttle data.
+class ServerRetryThrottleMap {
+ public:
+ /// Initializes global map of failure data for each server name.
+ static void Init();
+ /// Shuts down global map of failure data for each server name.
+ static void Shutdown();
+
+ /// Returns the failure data for \a server_name, creating a new entry if
+ /// needed.
+ static RefCountedPtr<ServerRetryThrottleData> GetDataForServer(
+ const char* server_name, intptr_t max_milli_tokens,
+ intptr_t milli_token_ratio);
+};
+
+} // namespace internal
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RETRY_THROTTLE_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 39800681e0f..e0fceee4db4 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/client_channel/subchannel.h"
-
-#include <inttypes.h>
-#include <limits.h>
-
-#include <algorithm>
-#include <cstring>
-
+/*
+ *
+ * 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/subchannel.h"
+
+#include <inttypes.h>
+#include <limits.h>
+
+#include <algorithm>
+#include <cstring>
+
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#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/proxy_mapper_registry.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"
-#include "src/core/lib/channel/connected_channel.h"
-#include "src/core/lib/debug/stats.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/debug/stats.h"
#include "src/core/lib/gpr/alloc.h"
-#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/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/iomgr/parse_address.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/channel.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/error_utils.h"
#include "src/core/lib/transport/status_metadata.h"
#include "src/core/lib/uri/uri_parser.h"
-
+
// Strong and weak refs.
-#define INTERNAL_REF_BITS 16
-#define STRONG_REF_MASK (~(gpr_atm)((1 << INTERNAL_REF_BITS) - 1))
-
+#define INTERNAL_REF_BITS 16
+#define STRONG_REF_MASK (~(gpr_atm)((1 << INTERNAL_REF_BITS) - 1))
+
// Backoff parameters.
-#define GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS 1
-#define GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER 1.6
-#define GRPC_SUBCHANNEL_RECONNECT_MIN_TIMEOUT_SECONDS 20
-#define GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS 120
-#define GRPC_SUBCHANNEL_RECONNECT_JITTER 0.2
-
+#define GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS 1
+#define GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER 1.6
+#define GRPC_SUBCHANNEL_RECONNECT_MIN_TIMEOUT_SECONDS 20
+#define GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS 120
+#define GRPC_SUBCHANNEL_RECONNECT_JITTER 0.2
+
// Conversion between subchannel call and call stack.
#define SUBCHANNEL_CALL_TO_CALL_STACK(call) \
(grpc_call_stack*)((char*)(call) + \
@@ -74,16 +74,16 @@
#define CALL_STACK_TO_SUBCHANNEL_CALL(callstack) \
(SubchannelCall*)(((char*)(call_stack)) - \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)))
-
+
namespace grpc_core {
-
+
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)
@@ -91,12 +91,12 @@ ConnectedSubchannel::ConnectedSubchannel(
channel_stack_(channel_stack),
args_(grpc_channel_args_copy(args)),
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) {
@@ -107,7 +107,7 @@ void ConnectedSubchannel::StartWatch(
grpc_channel_element* elem = grpc_channel_stack_element(channel_stack_, 0);
elem->filter->start_transport_op(elem, op);
}
-
+
void ConnectedSubchannel::Ping(grpc_closure* on_initiate,
grpc_closure* on_ack) {
grpc_transport_op* op = grpc_make_transport_op(nullptr);
@@ -117,7 +117,7 @@ void ConnectedSubchannel::Ping(grpc_closure* on_initiate,
elem = grpc_channel_stack_element(channel_stack_, 0);
elem->filter->start_transport_op(elem, op);
}
-
+
size_t ConnectedSubchannel::GetInitialCallSizeEstimate(
size_t parent_data_size) const {
size_t allocation_size =
@@ -173,7 +173,7 @@ SubchannelCall::SubchannelCall(Args args, grpc_error** error)
channelz_node->RecordCallStarted();
}
}
-
+
void SubchannelCall::StartTransportStreamOpBatch(
grpc_transport_stream_op_batch* batch) {
GPR_TIMER_SCOPE("subchannel_call_process_op", 0);
@@ -183,43 +183,43 @@ void SubchannelCall::StartTransportStreamOpBatch(
GRPC_CALL_LOG_OP(GPR_INFO, top_elem, batch);
top_elem->filter->start_transport_stream_op_batch(top_elem, batch);
}
-
+
void* SubchannelCall::GetParentData() {
grpc_channel_stack* chanstk = connected_subchannel_->channel_stack();
return (char*)this + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(chanstk->call_stack_size);
}
-
+
grpc_call_stack* SubchannelCall::GetCallStack() {
return SUBCHANNEL_CALL_TO_CALL_STACK(this);
}
-
+
void SubchannelCall::SetAfterCallStackDestroy(grpc_closure* closure) {
GPR_ASSERT(after_call_stack_destroy_ == nullptr);
GPR_ASSERT(closure != nullptr);
after_call_stack_destroy_ = closure;
}
-
+
RefCountedPtr<SubchannelCall> SubchannelCall::Ref() {
IncrementRefCount();
return RefCountedPtr<SubchannelCall>(this);
}
-
+
RefCountedPtr<SubchannelCall> SubchannelCall::Ref(
const grpc_core::DebugLocation& location, const char* reason) {
IncrementRefCount(location, reason);
return RefCountedPtr<SubchannelCall>(this);
}
-
+
void SubchannelCall::Unref() {
GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), "");
}
-
+
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*/) {
GPR_TIMER_SCOPE("subchannel_call_destroy", 0);
SubchannelCall* self = static_cast<SubchannelCall*>(arg);
@@ -238,7 +238,7 @@ void SubchannelCall::Destroy(void* arg, grpc_error* /*error*/) {
// the call stack, because destroying call stack needs access to the channel
// stack.
}
-
+
void SubchannelCall::MaybeInterceptRecvTrailingMetadata(
grpc_transport_stream_op_batch* batch) {
// only intercept payloads with recv trailing.
@@ -260,9 +260,9 @@ void SubchannelCall::MaybeInterceptRecvTrailingMetadata(
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&recv_trailing_metadata_ready_;
}
-
+
namespace {
-
+
// Sets *status based on the rest of the parameters.
void GetCallStatus(grpc_status_code* status, grpc_millis deadline,
grpc_metadata_batch* md_batch, grpc_error* error) {
@@ -277,10 +277,10 @@ void GetCallStatus(grpc_status_code* status, grpc_millis deadline,
}
}
GRPC_ERROR_UNREF(error);
-}
-
+}
+
} // namespace
-
+
void SubchannelCall::RecvTrailingMetadataReady(void* arg, grpc_error* error) {
SubchannelCall* call = static_cast<SubchannelCall*>(arg);
GPR_ASSERT(call->recv_trailing_metadata_ != nullptr);
@@ -294,20 +294,20 @@ void SubchannelCall::RecvTrailingMetadataReady(void* arg, grpc_error* error) {
channelz_subchannel->RecordCallSucceeded();
} else {
channelz_subchannel->RecordCallFailed();
- }
+ }
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) {
GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason);
-}
-
+}
+
//
// Subchannel::ConnectedSubchannelStateWatcher
//
@@ -359,7 +359,7 @@ class Subchannel::ConnectedSubchannelStateWatcher
c->backoff_.Reset();
}
break;
- }
+ }
default: {
// In principle, this should never happen. We should not get
// a callback for READY, because that was the state we started
@@ -367,9 +367,9 @@ class Subchannel::ConnectedSubchannelStateWatcher
// from READY to CONNECTING or IDLE.
c->SetConnectivityStateLocked(new_state, status);
}
- }
- }
-
+ }
+ }
+
Subchannel* subchannel_;
};
@@ -467,7 +467,7 @@ class Subchannel::HealthWatcherMap::HealthWatcher
}
watcher_list_.AddWatcherLocked(std::move(watcher));
}
-
+
void RemoveWatcherLocked(
Subchannel::ConnectivityStateWatcherInterface* watcher) {
watcher_list_.RemoveWatcherLocked(watcher);
@@ -549,11 +549,11 @@ void Subchannel::HealthWatcherMap::AddWatcherLocked(
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) {
@@ -569,9 +569,9 @@ void Subchannel::HealthWatcherMap::NotifyLocked(grpc_connectivity_state state,
const y_absl::Status& status) {
for (const auto& p : map_) {
p.second->NotifyLocked(state, status);
- }
+ }
}
-
+
grpc_connectivity_state
Subchannel::HealthWatcherMap::CheckConnectivityStateLocked(
Subchannel* subchannel, const char* health_check_service_name) {
@@ -599,52 +599,52 @@ namespace {
BackOff::Options ParseArgsForBackoffValues(
const grpc_channel_args* args, grpc_millis* min_connect_timeout_ms) {
- grpc_millis initial_backoff_ms =
- GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS * 1000;
- *min_connect_timeout_ms =
- GRPC_SUBCHANNEL_RECONNECT_MIN_TIMEOUT_SECONDS * 1000;
- grpc_millis max_backoff_ms =
- GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS * 1000;
- bool fixed_reconnect_backoff = false;
- if (args != nullptr) {
- for (size_t i = 0; i < args->num_args; i++) {
- if (0 == strcmp(args->args[i].key,
- "grpc.testing.fixed_reconnect_backoff_ms")) {
- fixed_reconnect_backoff = true;
- initial_backoff_ms = *min_connect_timeout_ms = max_backoff_ms =
- grpc_channel_arg_get_integer(
- &args->args[i],
- {static_cast<int>(initial_backoff_ms), 100, INT_MAX});
- } else if (0 ==
- strcmp(args->args[i].key, GRPC_ARG_MIN_RECONNECT_BACKOFF_MS)) {
- fixed_reconnect_backoff = false;
- *min_connect_timeout_ms = grpc_channel_arg_get_integer(
- &args->args[i],
- {static_cast<int>(*min_connect_timeout_ms), 100, INT_MAX});
- } else if (0 ==
- strcmp(args->args[i].key, GRPC_ARG_MAX_RECONNECT_BACKOFF_MS)) {
- fixed_reconnect_backoff = false;
- max_backoff_ms = grpc_channel_arg_get_integer(
- &args->args[i], {static_cast<int>(max_backoff_ms), 100, INT_MAX});
- } else if (0 == strcmp(args->args[i].key,
- GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS)) {
- fixed_reconnect_backoff = false;
- initial_backoff_ms = grpc_channel_arg_get_integer(
- &args->args[i],
- {static_cast<int>(initial_backoff_ms), 100, INT_MAX});
- }
- }
- }
+ grpc_millis initial_backoff_ms =
+ GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS * 1000;
+ *min_connect_timeout_ms =
+ GRPC_SUBCHANNEL_RECONNECT_MIN_TIMEOUT_SECONDS * 1000;
+ grpc_millis max_backoff_ms =
+ GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS * 1000;
+ bool fixed_reconnect_backoff = false;
+ if (args != nullptr) {
+ for (size_t i = 0; i < args->num_args; i++) {
+ if (0 == strcmp(args->args[i].key,
+ "grpc.testing.fixed_reconnect_backoff_ms")) {
+ fixed_reconnect_backoff = true;
+ initial_backoff_ms = *min_connect_timeout_ms = max_backoff_ms =
+ grpc_channel_arg_get_integer(
+ &args->args[i],
+ {static_cast<int>(initial_backoff_ms), 100, INT_MAX});
+ } else if (0 ==
+ strcmp(args->args[i].key, GRPC_ARG_MIN_RECONNECT_BACKOFF_MS)) {
+ fixed_reconnect_backoff = false;
+ *min_connect_timeout_ms = grpc_channel_arg_get_integer(
+ &args->args[i],
+ {static_cast<int>(*min_connect_timeout_ms), 100, INT_MAX});
+ } else if (0 ==
+ strcmp(args->args[i].key, GRPC_ARG_MAX_RECONNECT_BACKOFF_MS)) {
+ fixed_reconnect_backoff = false;
+ max_backoff_ms = grpc_channel_arg_get_integer(
+ &args->args[i], {static_cast<int>(max_backoff_ms), 100, INT_MAX});
+ } else if (0 == strcmp(args->args[i].key,
+ GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS)) {
+ fixed_reconnect_backoff = false;
+ initial_backoff_ms = grpc_channel_arg_get_integer(
+ &args->args[i],
+ {static_cast<int>(initial_backoff_ms), 100, INT_MAX});
+ }
+ }
+ }
return BackOff::Options()
.set_initial_backoff(initial_backoff_ms)
- .set_multiplier(fixed_reconnect_backoff
- ? 1.0
- : GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER)
- .set_jitter(fixed_reconnect_backoff ? 0.0
- : GRPC_SUBCHANNEL_RECONNECT_JITTER)
- .set_max_backoff(max_backoff_ms);
-}
-
+ .set_multiplier(fixed_reconnect_backoff
+ ? 1.0
+ : GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER)
+ .set_jitter(fixed_reconnect_backoff ? 0.0
+ : GRPC_SUBCHANNEL_RECONNECT_JITTER)
+ .set_max_backoff(max_backoff_ms);
+}
+
} // namespace
void Subchannel::ConnectivityStateWatcherInterface::PushConnectivityStateChange(
@@ -668,29 +668,29 @@ Subchannel::Subchannel(SubchannelKey* key,
: key_(key),
connector_(std::move(connector)),
backoff_(ParseArgsForBackoffValues(args, &min_connect_timeout_ms_)) {
- GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED();
+ GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED();
gpr_atm_no_barrier_store(&ref_pair_, 1 << INTERNAL_REF_BITS);
pollset_set_ = grpc_pollset_set_create();
- grpc_resolved_address* addr =
- static_cast<grpc_resolved_address*>(gpr_malloc(sizeof(*addr)));
+ grpc_resolved_address* addr =
+ static_cast<grpc_resolved_address*>(gpr_malloc(sizeof(*addr)));
GetAddressFromSubchannelAddressArg(args, addr);
- grpc_resolved_address* new_address = nullptr;
- grpc_channel_args* new_args = nullptr;
+ grpc_resolved_address* new_address = nullptr;
+ grpc_channel_args* new_args = nullptr;
if (ProxyMapperRegistry::MapAddress(*addr, args, &new_address, &new_args)) {
- GPR_ASSERT(new_address != nullptr);
- gpr_free(addr);
- addr = new_address;
- }
- static const char* keys_to_remove[] = {GRPC_ARG_SUBCHANNEL_ADDRESS};
+ GPR_ASSERT(new_address != nullptr);
+ gpr_free(addr);
+ addr = new_address;
+ }
+ static const char* keys_to_remove[] = {GRPC_ARG_SUBCHANNEL_ADDRESS};
grpc_arg new_arg = CreateSubchannelAddressArg(addr);
- gpr_free(addr);
+ gpr_free(addr);
args_ = grpc_channel_args_copy_and_add_and_remove(
new_args != nullptr ? new_args : args, keys_to_remove,
- GPR_ARRAY_SIZE(keys_to_remove), &new_arg, 1);
- gpr_free(new_arg.value.string);
- if (new_args != nullptr) grpc_channel_args_destroy(new_args);
+ GPR_ARRAY_SIZE(keys_to_remove), &new_arg, 1);
+ gpr_free(new_arg.value.string);
+ if (new_args != nullptr) grpc_channel_args_destroy(new_args);
GRPC_CLOSURE_INIT(&on_connecting_finished_, OnConnectingFinished, this,
- grpc_schedule_on_exec_ctx);
+ grpc_schedule_on_exec_ctx);
const grpc_arg* arg = grpc_channel_args_find(args_, GRPC_ARG_ENABLE_CHANNELZ);
const bool channelz_enabled =
grpc_channel_arg_get_bool(arg, GRPC_ENABLE_CHANNELZ_DEFAULT);
@@ -708,7 +708,7 @@ Subchannel::Subchannel(SubchannelKey* key,
grpc_slice_from_static_string("subchannel created"));
}
}
-
+
Subchannel::~Subchannel() {
if (channelz_node_ != nullptr) {
channelz_node_->AddTraceEvent(
@@ -720,8 +720,8 @@ Subchannel::~Subchannel() {
connector_.reset();
grpc_pollset_set_destroy(pollset_set_);
delete key_;
-}
-
+}
+
Subchannel* Subchannel::Create(OrphanablePtr<SubchannelConnector> connector,
const grpc_channel_args* args) {
SubchannelKey* key = new SubchannelKey(args);
@@ -741,8 +741,8 @@ Subchannel* Subchannel::Create(OrphanablePtr<SubchannelConnector> connector,
Subchannel* registered = subchannel_pool->RegisterSubchannel(key, c);
if (registered == c) c->subchannel_pool_ = subchannel_pool->Ref();
return registered;
-}
-
+}
+
void Subchannel::ThrottleKeepaliveTime(int new_keepalive_time) {
MutexLock lock(&mu_);
// Only update the value if the new keepalive time is larger.
@@ -768,8 +768,8 @@ Subchannel* Subchannel::Ref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
0 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("STRONG_REF"));
GPR_ASSERT((old_refs & STRONG_REF_MASK) != 0);
return this;
-}
-
+}
+
void Subchannel::Unref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
gpr_atm old_refs;
// add a weak ref and subtract a strong ref (atomically)
@@ -778,26 +778,26 @@ void Subchannel::Unref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
1 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("STRONG_UNREF"));
if ((old_refs & STRONG_REF_MASK) == (1 << INTERNAL_REF_BITS)) {
Disconnect();
- }
+ }
GRPC_SUBCHANNEL_WEAK_UNREF(this, "strong-unref");
-}
-
+}
+
Subchannel* Subchannel::WeakRef(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
gpr_atm old_refs;
old_refs = RefMutate(1, 0 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("WEAK_REF"));
GPR_ASSERT(old_refs != 0);
return this;
-}
-
+}
+
namespace {
-
+
void subchannel_destroy(void* arg, grpc_error* /*error*/) {
Subchannel* self = static_cast<Subchannel*>(arg);
delete self;
}
-
+
} // namespace
-
+
void Subchannel::WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
gpr_atm old_refs;
old_refs = RefMutate(-static_cast<gpr_atm>(1),
@@ -807,9 +807,9 @@ void Subchannel::WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) {
GRPC_CLOSURE_CREATE(subchannel_destroy, this,
grpc_schedule_on_exec_ctx),
GRPC_ERROR_NONE);
- }
+ }
}
-
+
Subchannel* Subchannel::RefFromWeakRef() {
for (;;) {
gpr_atm old_refs = gpr_atm_acq_load(&ref_pair_);
@@ -818,12 +818,12 @@ Subchannel* Subchannel::RefFromWeakRef() {
if (gpr_atm_rel_cas(&ref_pair_, old_refs, new_refs)) {
return this;
}
- } else {
+ } else {
return nullptr;
- }
- }
-}
-
+ }
+ }
+}
+
const char* Subchannel::GetTargetAddress() {
const grpc_arg* addr_arg =
grpc_channel_args_find(args_, GRPC_ARG_SUBCHANNEL_ADDRESS);
@@ -865,15 +865,15 @@ void Subchannel::WatchConnectivityState(
if (health_check_service_name == nullptr) {
if (state_ != initial_state) {
new AsyncWatcherNotifierLocked(watcher, this, state_, status_);
- }
+ }
watcher_list_.AddWatcherLocked(std::move(watcher));
- } else {
+ } 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) {
@@ -905,14 +905,14 @@ void Subchannel::ResetBackoff() {
MaybeStartConnectingLocked();
}
}
-
+
grpc_arg Subchannel::CreateSubchannelAddressArg(
const grpc_resolved_address* addr) {
return grpc_channel_arg_string_create(
(char*)GRPC_ARG_SUBCHANNEL_ADDRESS,
gpr_strdup(addr->len > 0 ? grpc_sockaddr_to_uri(addr).c_str() : ""));
}
-
+
const char* Subchannel::GetUriFromSubchannelAddressArg(
const grpc_channel_args* args) {
const grpc_arg* addr_arg =
@@ -939,11 +939,11 @@ void Subchannel::GetAddressFromSubchannelAddressArg(
memset(addr, 0, sizeof(*addr));
if (*addr_uri_str != '\0') {
UriToSockaddr(addr_uri_str, addr);
- }
-}
-
+ }
+}
+
namespace {
-
+
// Returns a string indicating the subchannel's connectivity state change to
// \a state.
const char* SubchannelConnectivityStateChangeString(
@@ -959,12 +959,12 @@ const char* SubchannelConnectivityStateChangeString(
return "Subchannel state change to TRANSIENT_FAILURE";
case GRPC_CHANNEL_SHUTDOWN:
return "Subchannel state change to SHUTDOWN";
- }
+ }
GPR_UNREACHABLE_CODE(return "UNKNOWN");
}
-
+
} // namespace
-
+
// 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) {
@@ -976,13 +976,13 @@ void Subchannel::SetConnectivityStateLocked(grpc_connectivity_state state,
channelz::ChannelTrace::Severity::Info,
grpc_slice_from_static_string(
SubchannelConnectivityStateChangeString(state)));
- }
+ }
// Notify non-health watchers.
watcher_list_.NotifyLocked(this, state, status);
// Notify health watchers.
health_watcher_map_.NotifyLocked(state, status);
}
-
+
void Subchannel::MaybeStartConnectingLocked() {
if (disconnected_) {
// Don't try to connect if we're already disconnected.
@@ -1017,7 +1017,7 @@ void Subchannel::MaybeStartConnectingLocked() {
grpc_timer_init(&retry_alarm_, next_attempt_deadline_, &on_retry_alarm_);
}
}
-
+
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
@@ -1043,7 +1043,7 @@ void Subchannel::OnRetryAlarm(void* arg, grpc_error* error) {
}
GRPC_ERROR_UNREF(error);
}
-
+
void Subchannel::ContinueConnectingLocked() {
SubchannelConnector::Args args;
args.interested_parties = pollset_set_;
@@ -1054,8 +1054,8 @@ void Subchannel::ContinueConnectingLocked() {
args.channel_args = args_;
SetConnectivityStateLocked(GRPC_CHANNEL_CONNECTING, y_absl::Status());
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 =
@@ -1075,21 +1075,21 @@ void Subchannel::OnConnectingFinished(void* arg, grpc_error* error) {
grpc_error_to_absl_status(error));
GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting");
}
- }
+ }
GRPC_SUBCHANNEL_WEAK_UNREF(c, "on_connecting_finished");
- grpc_channel_args_destroy(delete_channel_args);
-}
-
+ grpc_channel_args_destroy(delete_channel_args);
+}
+
namespace {
-
+
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);
-}
-
+}
+
} // namespace
-
+
bool Subchannel::PublishTransportLocked() {
// Construct channel stack.
grpc_channel_stack_builder* builder = grpc_channel_stack_builder_create();
@@ -1134,23 +1134,23 @@ bool Subchannel::PublishTransportLocked() {
// Report initial state.
SetConnectivityStateLocked(GRPC_CHANNEL_READY, y_absl::Status());
return true;
-}
-
+}
+
void Subchannel::Disconnect() {
// The subchannel_pool is only used once here in this subchannel, so the
// access can be outside of the lock.
if (subchannel_pool_ != nullptr) {
subchannel_pool_->UnregisterSubchannel(key_);
subchannel_pool_.reset();
- }
+ }
MutexLock lock(&mu_);
GPR_ASSERT(!disconnected_);
disconnected_ = true;
connector_.reset();
connected_subchannel_.reset();
health_watcher_map_.ShutdownLocked();
-}
-
+}
+
gpr_atm Subchannel::RefMutate(
gpr_atm delta, int barrier GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS) {
gpr_atm old_val = barrier ? gpr_atm_full_fetch_add(&ref_pair_, delta)
@@ -1160,9 +1160,9 @@ gpr_atm Subchannel::RefMutate(
gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
"SUBCHANNEL: %p %12s 0x%" PRIxPTR " -> 0x%" PRIxPTR " [%s]", this,
purpose, old_val, old_val + delta, reason);
- }
+ }
#endif
return old_val;
-}
-
-} // namespace grpc_core
+}
+
+} // namespace grpc_core
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 0ced846c385..805b60dc41a 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
@@ -1,88 +1,88 @@
-/*
- *
- * 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_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_H
-#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_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_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_H
+#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_H
+
+#include <grpc/support/port_platform.h>
+
#include <deque>
#include "src/core/ext/filters/client_channel/client_channel_channelz.h"
-#include "src/core/ext/filters/client_channel/connector.h"
+#include "src/core/ext/filters/client_channel/connector.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_stack.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/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.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/iomgr/polling_entity.h"
+#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/transport/connectivity_state.h"
-#include "src/core/lib/transport/metadata.h"
-
+#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/metadata.h"
+
// Channel arg containing a URI indicating the address to connect to.
-#define GRPC_ARG_SUBCHANNEL_ADDRESS "grpc.subchannel_address"
-
+#define GRPC_ARG_SUBCHANNEL_ADDRESS "grpc.subchannel_address"
+
// For debugging refcounting.
-#ifndef NDEBUG
+#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_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))
-#define GRPC_SUBCHANNEL_REF_EXTRA_ARGS \
+#define GRPC_SUBCHANNEL_REF_EXTRA_ARGS \
const char *file, int line, const char *reason
#define GRPC_SUBCHANNEL_REF_REASON reason
#define GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS \
, GRPC_SUBCHANNEL_REF_EXTRA_ARGS, const char* purpose
#define GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE(x) , file, line, reason, x
-#else
+#else
#define GRPC_SUBCHANNEL_REF(p, r) (p)->Ref()
#define GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(p, r) (p)->RefFromWeakRef()
#define GRPC_SUBCHANNEL_UNREF(p, r) (p)->Unref()
#define GRPC_SUBCHANNEL_WEAK_REF(p, r) (p)->WeakRef()
#define GRPC_SUBCHANNEL_WEAK_UNREF(p, r) (p)->WeakUnref()
-#define GRPC_SUBCHANNEL_REF_EXTRA_ARGS
+#define GRPC_SUBCHANNEL_REF_EXTRA_ARGS
#define GRPC_SUBCHANNEL_REF_REASON ""
#define GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS
#define GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE(x)
-#endif
-
-namespace grpc_core {
-
+#endif
+
+namespace grpc_core {
+
class SubchannelCall;
class ConnectedSubchannel : public RefCounted<ConnectedSubchannel> {
- public:
+ public:
ConnectedSubchannel(
grpc_channel_stack* channel_stack, const grpc_channel_args* args,
RefCountedPtr<channelz::SubchannelNode> channelz_subchannel);
- ~ConnectedSubchannel();
-
+ ~ConnectedSubchannel();
+
void StartWatch(grpc_pollset_set* interested_parties,
OrphanablePtr<ConnectivityStateWatcherInterface> watcher);
- void Ping(grpc_closure* on_initiate, grpc_closure* on_ack);
-
+ void Ping(grpc_closure* on_initiate, grpc_closure* on_ack);
+
grpc_channel_stack* channel_stack() const { return channel_stack_; }
const grpc_channel_args* args() const { return args_; }
channelz::SubchannelNode* channelz_subchannel() const {
@@ -91,14 +91,14 @@ class ConnectedSubchannel : public RefCounted<ConnectedSubchannel> {
size_t GetInitialCallSizeEstimate(size_t parent_data_size) const;
- private:
- grpc_channel_stack* channel_stack_;
+ private:
+ grpc_channel_stack* channel_stack_;
grpc_channel_args* args_;
// ref counted pointer to the channelz node in this connected subchannel's
// owning subchannel.
RefCountedPtr<channelz::SubchannelNode> channelz_subchannel_;
-};
-
+};
+
// Implements the interface of RefCounted<>.
class SubchannelCall {
public:
@@ -114,22 +114,22 @@ class SubchannelCall {
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);
-
+
// Returns a pointer to the parent data associated with the subchannel call.
// The data will be of the size specified in \a parent_data_size field of
// the args passed to \a ConnectedSubchannel::CreateCall().
void* GetParentData();
-
+
// Returns the call stack of the subchannel call.
grpc_call_stack* GetCallStack();
-
+
// Sets the 'then_schedule_closure' argument for call stack destruction.
// Must be called once per call.
void SetAfterCallStackDestroy(grpc_closure* closure);
-
+
// Interface of RefCounted<>.
RefCountedPtr<SubchannelCall> Ref() GRPC_MUST_USE_RESULT;
RefCountedPtr<SubchannelCall> Ref(const DebugLocation& location,
@@ -138,27 +138,27 @@ class SubchannelCall {
// but does NOT free the memory because it's in the call arena.
void Unref();
void Unref(const DebugLocation& location, const char* reason);
-
+
static void Destroy(void* arg, grpc_error* error);
-
+
private:
// Allow RefCountedPtr<> to access IncrementRefCount().
template <typename T>
friend class RefCountedPtr;
-
+
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(
grpc_transport_stream_op_batch* batch);
-
+
static void RecvTrailingMetadataReady(void* arg, grpc_error* error);
-
+
// Interface of RefCounted<>.
void IncrementRefCount();
void IncrementRefCount(const DebugLocation& location, const char* reason);
-
+
RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
grpc_closure* after_call_stack_destroy_ = nullptr;
// State needed to support channelz interception of recv trailing metadata.
@@ -166,8 +166,8 @@ class SubchannelCall {
grpc_closure* original_recv_trailing_metadata_ = nullptr;
grpc_metadata_batch* recv_trailing_metadata_ = nullptr;
grpc_millis deadline_;
-};
-
+};
+
// A subchannel that knows how to connect to exactly one target address. It
// provides a target for load balancing.
//
@@ -223,11 +223,11 @@ class Subchannel {
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,
const grpc_channel_args* args);
-
+
// Throttles keepalive time to \a new_keepalive_time iff \a new_keepalive_time
// is larger than the subchannel's current keepalive time. The updated value
// will have an affect when the subchannel creates a new ConnectedSubchannel.
@@ -242,7 +242,7 @@ class Subchannel {
// 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();
@@ -436,4 +436,4 @@ class Subchannel {
} // namespace grpc_core
-#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_H */
+#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_H */
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 e4027b0719f..a8aa80d10e0 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
@@ -1,143 +1,143 @@
-//
-// 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/ext/filters/deadline/deadline_filter.h"
-
-#include <stdbool.h>
-#include <string.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/channel/channel_stack_builder.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/ext/filters/deadline/deadline_filter.h"
+
+#include <stdbool.h>
+#include <string.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/channel/channel_stack_builder.h"
#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/channel_init.h"
-
-//
-// grpc_deadline_state
-//
-
-// The on_complete callback used when sending a cancel_error batch down the
-// filter stack. Yields the call combiner when the batch returns.
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/channel_init.h"
+
+//
+// grpc_deadline_state
+//
+
+// 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*/) {
- 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");
- GRPC_CALL_STACK_UNREF(deadline_state->call_stack, "deadline_timer");
-}
-
-// This is called via the call combiner, so access to deadline_state is
-// synchronized.
-static void send_cancel_op_in_call_combiner(void* arg, grpc_error* error) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
- grpc_deadline_state* deadline_state =
- static_cast<grpc_deadline_state*>(elem->call_data);
- grpc_transport_stream_op_batch* batch = grpc_make_transport_stream_op(
- GRPC_CLOSURE_INIT(&deadline_state->timer_callback, yield_call_combiner,
- deadline_state, grpc_schedule_on_exec_ctx));
- batch->cancel_stream = true;
- batch->payload->cancel_stream.cancel_error = GRPC_ERROR_REF(error);
- elem->filter->start_transport_stream_op_batch(elem, batch);
-}
-
-// Timer callback.
-static void timer_callback(void* arg, grpc_error* error) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
- grpc_deadline_state* deadline_state =
- static_cast<grpc_deadline_state*>(elem->call_data);
- if (error != GRPC_ERROR_CANCELLED) {
- error = grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Deadline Exceeded"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_DEADLINE_EXCEEDED);
+ 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");
+ GRPC_CALL_STACK_UNREF(deadline_state->call_stack, "deadline_timer");
+}
+
+// This is called via the call combiner, so access to deadline_state is
+// synchronized.
+static void send_cancel_op_in_call_combiner(void* arg, grpc_error* error) {
+ grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
+ grpc_deadline_state* deadline_state =
+ static_cast<grpc_deadline_state*>(elem->call_data);
+ grpc_transport_stream_op_batch* batch = grpc_make_transport_stream_op(
+ GRPC_CLOSURE_INIT(&deadline_state->timer_callback, yield_call_combiner,
+ deadline_state, grpc_schedule_on_exec_ctx));
+ batch->cancel_stream = true;
+ batch->payload->cancel_stream.cancel_error = GRPC_ERROR_REF(error);
+ elem->filter->start_transport_stream_op_batch(elem, batch);
+}
+
+// Timer callback.
+static void timer_callback(void* arg, grpc_error* error) {
+ grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
+ grpc_deadline_state* deadline_state =
+ static_cast<grpc_deadline_state*>(elem->call_data);
+ if (error != GRPC_ERROR_CANCELLED) {
+ 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));
- GRPC_CLOSURE_INIT(&deadline_state->timer_callback,
- send_cancel_op_in_call_combiner, elem,
- grpc_schedule_on_exec_ctx);
- GRPC_CALL_COMBINER_START(deadline_state->call_combiner,
- &deadline_state->timer_callback, error,
- "deadline exceeded -- sending cancel_stream op");
- } else {
- GRPC_CALL_STACK_UNREF(deadline_state->call_stack, "deadline_timer");
- }
-}
-
-// Starts the deadline timer.
-// This is called via the call combiner, so access to deadline_state is
-// synchronized.
-static void start_timer_if_needed(grpc_call_element* elem,
- grpc_millis deadline) {
- if (deadline == GRPC_MILLIS_INF_FUTURE) {
- return;
- }
- grpc_deadline_state* deadline_state =
- static_cast<grpc_deadline_state*>(elem->call_data);
- grpc_closure* closure = nullptr;
- switch (deadline_state->timer_state) {
- case GRPC_DEADLINE_STATE_PENDING:
- // Note: We do not start the timer if there is already a timer
- return;
- case GRPC_DEADLINE_STATE_FINISHED:
- deadline_state->timer_state = GRPC_DEADLINE_STATE_PENDING;
- // If we've already created and destroyed a timer, we always create a
- // new closure: we have no other guarantee that the inlined closure is
- // not in use (it may hold a pending call to timer_callback)
- closure =
- GRPC_CLOSURE_CREATE(timer_callback, elem, grpc_schedule_on_exec_ctx);
- break;
- case GRPC_DEADLINE_STATE_INITIAL:
- deadline_state->timer_state = GRPC_DEADLINE_STATE_PENDING;
- closure =
- GRPC_CLOSURE_INIT(&deadline_state->timer_callback, timer_callback,
- elem, grpc_schedule_on_exec_ctx);
- break;
- }
- GPR_ASSERT(closure != nullptr);
- GRPC_CALL_STACK_REF(deadline_state->call_stack, "deadline_timer");
- grpc_timer_init(&deadline_state->timer, deadline, closure);
-}
-
-// Cancels the deadline timer.
-// This is called via the call combiner, so access to deadline_state is
-// synchronized.
-static void cancel_timer_if_needed(grpc_deadline_state* deadline_state) {
- if (deadline_state->timer_state == GRPC_DEADLINE_STATE_PENDING) {
- deadline_state->timer_state = GRPC_DEADLINE_STATE_FINISHED;
- grpc_timer_cancel(&deadline_state->timer);
- } else {
+ GRPC_CLOSURE_INIT(&deadline_state->timer_callback,
+ send_cancel_op_in_call_combiner, elem,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CALL_COMBINER_START(deadline_state->call_combiner,
+ &deadline_state->timer_callback, error,
+ "deadline exceeded -- sending cancel_stream op");
+ } else {
+ GRPC_CALL_STACK_UNREF(deadline_state->call_stack, "deadline_timer");
+ }
+}
+
+// Starts the deadline timer.
+// This is called via the call combiner, so access to deadline_state is
+// synchronized.
+static void start_timer_if_needed(grpc_call_element* elem,
+ grpc_millis deadline) {
+ if (deadline == GRPC_MILLIS_INF_FUTURE) {
+ return;
+ }
+ grpc_deadline_state* deadline_state =
+ static_cast<grpc_deadline_state*>(elem->call_data);
+ grpc_closure* closure = nullptr;
+ switch (deadline_state->timer_state) {
+ case GRPC_DEADLINE_STATE_PENDING:
+ // Note: We do not start the timer if there is already a timer
+ return;
+ case GRPC_DEADLINE_STATE_FINISHED:
+ deadline_state->timer_state = GRPC_DEADLINE_STATE_PENDING;
+ // If we've already created and destroyed a timer, we always create a
+ // new closure: we have no other guarantee that the inlined closure is
+ // not in use (it may hold a pending call to timer_callback)
+ closure =
+ GRPC_CLOSURE_CREATE(timer_callback, elem, grpc_schedule_on_exec_ctx);
+ break;
+ case GRPC_DEADLINE_STATE_INITIAL:
+ deadline_state->timer_state = GRPC_DEADLINE_STATE_PENDING;
+ closure =
+ GRPC_CLOSURE_INIT(&deadline_state->timer_callback, timer_callback,
+ elem, grpc_schedule_on_exec_ctx);
+ break;
+ }
+ GPR_ASSERT(closure != nullptr);
+ GRPC_CALL_STACK_REF(deadline_state->call_stack, "deadline_timer");
+ grpc_timer_init(&deadline_state->timer, deadline, closure);
+}
+
+// Cancels the deadline timer.
+// This is called via the call combiner, so access to deadline_state is
+// synchronized.
+static void cancel_timer_if_needed(grpc_deadline_state* deadline_state) {
+ if (deadline_state->timer_state == GRPC_DEADLINE_STATE_PENDING) {
+ deadline_state->timer_state = GRPC_DEADLINE_STATE_FINISHED;
+ grpc_timer_cancel(&deadline_state->timer);
+ } else {
// timer was either in STATE_INITIAL (nothing to cancel)
- // OR in STATE_FINISHED (again nothing to cancel)
- }
-}
-
+ // OR in STATE_FINISHED (again nothing to cancel)
+ }
+}
+
// Callback run when we receive trailing metadata.
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);
+ 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));
-}
-
+}
+
// Inject our own recv_trailing_metadata_ready callback into op.
static void inject_recv_trailing_metadata_ready(
grpc_deadline_state* deadline_state, grpc_transport_stream_op_batch* op) {
@@ -145,242 +145,242 @@ static void inject_recv_trailing_metadata_ready(
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready;
GRPC_CLOSURE_INIT(&deadline_state->recv_trailing_metadata_ready,
recv_trailing_metadata_ready, deadline_state,
- grpc_schedule_on_exec_ctx);
+ grpc_schedule_on_exec_ctx);
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&deadline_state->recv_trailing_metadata_ready;
-}
-
-// Callback and associated state for starting the timer after call stack
-// initialization has been completed.
-struct start_timer_after_init_state {
+}
+
+// Callback and associated state for starting the timer after call stack
+// initialization has been completed.
+struct start_timer_after_init_state {
start_timer_after_init_state(grpc_call_element* elem, grpc_millis deadline)
: elem(elem), deadline(deadline) {}
~start_timer_after_init_state() { start_timer_if_needed(elem, deadline); }
bool in_call_combiner = false;
- grpc_call_element* elem;
- grpc_millis deadline;
- grpc_closure closure;
-};
-static void start_timer_after_init(void* arg, grpc_error* error) {
- struct start_timer_after_init_state* state =
- static_cast<struct start_timer_after_init_state*>(arg);
- grpc_deadline_state* deadline_state =
- static_cast<grpc_deadline_state*>(state->elem->call_data);
- if (!state->in_call_combiner) {
- // We are initially called without holding the call combiner, so we
- // need to bounce ourselves into it.
- state->in_call_combiner = true;
- GRPC_CALL_COMBINER_START(deadline_state->call_combiner, &state->closure,
- GRPC_ERROR_REF(error),
- "scheduling deadline timer");
- return;
- }
+ grpc_call_element* elem;
+ grpc_millis deadline;
+ grpc_closure closure;
+};
+static void start_timer_after_init(void* arg, grpc_error* error) {
+ struct start_timer_after_init_state* state =
+ static_cast<struct start_timer_after_init_state*>(arg);
+ grpc_deadline_state* deadline_state =
+ static_cast<grpc_deadline_state*>(state->elem->call_data);
+ if (!state->in_call_combiner) {
+ // We are initially called without holding the call combiner, so we
+ // need to bounce ourselves into it.
+ state->in_call_combiner = true;
+ GRPC_CALL_COMBINER_START(deadline_state->call_combiner, &state->closure,
+ GRPC_ERROR_REF(error),
+ "scheduling deadline timer");
+ return;
+ }
delete state;
- GRPC_CALL_COMBINER_STOP(deadline_state->call_combiner,
- "done scheduling deadline timer");
-}
-
+ 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_millis deadline)
: call_stack(call_stack), call_combiner(call_combiner) {
- // Deadline will always be infinite on servers, so the timer will only be
- // set on clients with a finite deadline.
- if (deadline != GRPC_MILLIS_INF_FUTURE) {
- // When the deadline passes, we indicate the failure by sending down
- // an op with cancel_error set. However, we can't send down any ops
- // until after the call stack is fully initialized. If we start the
- // timer here, we have no guarantee that the timer won't pop before
- // call stack initialization is finished. To avoid that problem, we
- // 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 =
+ // Deadline will always be infinite on servers, so the timer will only be
+ // set on clients with a finite deadline.
+ if (deadline != GRPC_MILLIS_INF_FUTURE) {
+ // When the deadline passes, we indicate the failure by sending down
+ // an op with cancel_error set. However, we can't send down any ops
+ // until after the call stack is fully initialized. If we start the
+ // timer here, we have no guarantee that the timer won't pop before
+ // call stack initialization is finished. To avoid that problem, we
+ // 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);
- GRPC_CLOSURE_INIT(&state->closure, start_timer_after_init, state,
- grpc_schedule_on_exec_ctx);
+ 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_deadline_state::~grpc_deadline_state() { cancel_timer_if_needed(this); }
-
-void grpc_deadline_state_reset(grpc_call_element* elem,
- grpc_millis new_deadline) {
- grpc_deadline_state* deadline_state =
- static_cast<grpc_deadline_state*>(elem->call_data);
- cancel_timer_if_needed(deadline_state);
- start_timer_if_needed(elem, new_deadline);
-}
-
-void grpc_deadline_state_client_start_transport_stream_op_batch(
- grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
- grpc_deadline_state* deadline_state =
- static_cast<grpc_deadline_state*>(elem->call_data);
- if (op->cancel_stream) {
- cancel_timer_if_needed(deadline_state);
- } else {
- // Make sure we know when the call is complete, so that we can cancel
- // the timer.
- if (op->recv_trailing_metadata) {
+
+void grpc_deadline_state_reset(grpc_call_element* elem,
+ grpc_millis new_deadline) {
+ grpc_deadline_state* deadline_state =
+ static_cast<grpc_deadline_state*>(elem->call_data);
+ cancel_timer_if_needed(deadline_state);
+ start_timer_if_needed(elem, new_deadline);
+}
+
+void grpc_deadline_state_client_start_transport_stream_op_batch(
+ grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
+ grpc_deadline_state* deadline_state =
+ static_cast<grpc_deadline_state*>(elem->call_data);
+ if (op->cancel_stream) {
+ cancel_timer_if_needed(deadline_state);
+ } else {
+ // Make sure we know when the call is complete, so that we can cancel
+ // the timer.
+ if (op->recv_trailing_metadata) {
inject_recv_trailing_metadata_ready(deadline_state, op);
- }
- }
-}
-
-//
-// filter code
-//
-
-// Constructor for channel_data. Used for both client and server filters.
+ }
+ }
+}
+
+//
+// filter code
+//
+
+// 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) {
- GPR_ASSERT(!args->is_last);
- return GRPC_ERROR_NONE;
-}
-
-// Destructor for channel_data. Used for both client and server filters.
+ 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*/) {}
-
-// Call data used for both client and server filter.
-typedef struct base_call_data {
- grpc_deadline_state deadline_state;
-} base_call_data;
-
-// Additional call data used only for the server filter.
-typedef struct server_call_data {
- base_call_data base; // Must be first.
- // The closure for receiving initial metadata.
- grpc_closure recv_initial_metadata_ready;
- // Received initial metadata batch.
- grpc_metadata_batch* recv_initial_metadata;
- // The original recv_initial_metadata_ready closure, which we chain to
- // after our own closure is invoked.
- grpc_closure* next_recv_initial_metadata_ready;
-} server_call_data;
-
-// Constructor for call_data. Used for both client and server filters.
+
+// Call data used for both client and server filter.
+typedef struct base_call_data {
+ grpc_deadline_state deadline_state;
+} base_call_data;
+
+// Additional call data used only for the server filter.
+typedef struct server_call_data {
+ base_call_data base; // Must be first.
+ // The closure for receiving initial metadata.
+ grpc_closure recv_initial_metadata_ready;
+ // Received initial metadata batch.
+ grpc_metadata_batch* recv_initial_metadata;
+ // The original recv_initial_metadata_ready closure, which we chain to
+ // after our own closure is invoked.
+ grpc_closure* next_recv_initial_metadata_ready;
+} 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) {
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.
+ 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*/) {
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.
+}
+
+// Method for starting a call op for client filter.
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.
- grpc_call_next_op(elem, op);
-}
-
-// Callback for receiving initial metadata on the server.
-static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
- 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_call_element* elem, grpc_transport_stream_op_batch* op) {
+ grpc_deadline_state_client_start_transport_stream_op_batch(elem, op);
+ // Chain to next filter.
+ grpc_call_next_op(elem, op);
+}
+
+// Callback for receiving initial metadata on the server.
+static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
+ grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
+ 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));
-}
-
-// Method for starting a call op for server filter.
+}
+
+// Method for starting a call op for server filter.
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) {
- cancel_timer_if_needed(&calld->base.deadline_state);
- } else {
- // If we're receiving initial metadata, we need to get the deadline
- // from the recv_initial_metadata_ready callback. So we inject our
- // own callback into that hook.
- if (op->recv_initial_metadata) {
- calld->next_recv_initial_metadata_ready =
- op->payload->recv_initial_metadata.recv_initial_metadata_ready;
- calld->recv_initial_metadata =
- op->payload->recv_initial_metadata.recv_initial_metadata;
- GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready,
- recv_initial_metadata_ready, elem,
- grpc_schedule_on_exec_ctx);
- op->payload->recv_initial_metadata.recv_initial_metadata_ready =
- &calld->recv_initial_metadata_ready;
- }
- // Make sure we know when the call is complete, so that we can cancel
- // the timer.
- // Note that we trigger this on recv_trailing_metadata, even though
- // the client never sends trailing metadata, because this is the
- // hook that tells us when the call is complete on the server side.
- if (op->recv_trailing_metadata) {
+ 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) {
+ cancel_timer_if_needed(&calld->base.deadline_state);
+ } else {
+ // If we're receiving initial metadata, we need to get the deadline
+ // from the recv_initial_metadata_ready callback. So we inject our
+ // own callback into that hook.
+ if (op->recv_initial_metadata) {
+ calld->next_recv_initial_metadata_ready =
+ op->payload->recv_initial_metadata.recv_initial_metadata_ready;
+ calld->recv_initial_metadata =
+ op->payload->recv_initial_metadata.recv_initial_metadata;
+ GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready,
+ recv_initial_metadata_ready, elem,
+ grpc_schedule_on_exec_ctx);
+ op->payload->recv_initial_metadata.recv_initial_metadata_ready =
+ &calld->recv_initial_metadata_ready;
+ }
+ // Make sure we know when the call is complete, so that we can cancel
+ // the timer.
+ // Note that we trigger this on recv_trailing_metadata, even though
+ // the client never sends trailing metadata, because this is the
+ // hook that tells us when the call is complete on the server side.
+ if (op->recv_trailing_metadata) {
inject_recv_trailing_metadata_ready(&calld->base.deadline_state, op);
- }
- }
- // Chain to next filter.
- grpc_call_next_op(elem, op);
-}
-
-const grpc_channel_filter grpc_client_deadline_filter = {
+ }
+ }
+ // Chain to next filter.
+ grpc_call_next_op(elem, op);
+}
+
+const grpc_channel_filter grpc_client_deadline_filter = {
deadline_client_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(base_call_data),
+ grpc_channel_next_op,
+ sizeof(base_call_data),
deadline_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
deadline_destroy_call_elem,
- 0, // sizeof(channel_data)
+ 0, // sizeof(channel_data)
deadline_init_channel_elem,
deadline_destroy_channel_elem,
- grpc_channel_next_get_info,
- "deadline",
-};
-
-const grpc_channel_filter grpc_server_deadline_filter = {
+ grpc_channel_next_get_info,
+ "deadline",
+};
+
+const grpc_channel_filter grpc_server_deadline_filter = {
deadline_server_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(server_call_data),
+ grpc_channel_next_op,
+ sizeof(server_call_data),
deadline_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
deadline_destroy_call_elem,
- 0, // sizeof(channel_data)
+ 0, // sizeof(channel_data)
deadline_init_channel_elem,
deadline_destroy_channel_elem,
- grpc_channel_next_get_info,
- "deadline",
-};
-
-bool grpc_deadline_checking_enabled(const grpc_channel_args* channel_args) {
- return grpc_channel_arg_get_bool(
- grpc_channel_args_find(channel_args, GRPC_ARG_ENABLE_DEADLINE_CHECKS),
- !grpc_channel_args_want_minimal_stack(channel_args));
-}
-
-static bool maybe_add_deadline_filter(grpc_channel_stack_builder* builder,
- void* arg) {
- return grpc_deadline_checking_enabled(
- grpc_channel_stack_builder_get_channel_arguments(builder))
- ? grpc_channel_stack_builder_prepend_filter(
- builder, static_cast<const grpc_channel_filter*>(arg),
- nullptr, nullptr)
- : true;
-}
-
-void grpc_deadline_filter_init(void) {
- grpc_channel_init_register_stage(
- GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_deadline_filter, (void*)&grpc_client_deadline_filter);
- grpc_channel_init_register_stage(
- GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_deadline_filter, (void*)&grpc_server_deadline_filter);
-}
-
-void grpc_deadline_filter_shutdown(void) {}
+ grpc_channel_next_get_info,
+ "deadline",
+};
+
+bool grpc_deadline_checking_enabled(const grpc_channel_args* channel_args) {
+ return grpc_channel_arg_get_bool(
+ grpc_channel_args_find(channel_args, GRPC_ARG_ENABLE_DEADLINE_CHECKS),
+ !grpc_channel_args_want_minimal_stack(channel_args));
+}
+
+static bool maybe_add_deadline_filter(grpc_channel_stack_builder* builder,
+ void* arg) {
+ return grpc_deadline_checking_enabled(
+ grpc_channel_stack_builder_get_channel_arguments(builder))
+ ? grpc_channel_stack_builder_prepend_filter(
+ builder, static_cast<const grpc_channel_filter*>(arg),
+ nullptr, nullptr)
+ : true;
+}
+
+void grpc_deadline_filter_init(void) {
+ grpc_channel_init_register_stage(
+ GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ maybe_add_deadline_filter, (void*)&grpc_client_deadline_filter);
+ grpc_channel_init_register_stage(
+ GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ maybe_add_deadline_filter, (void*)&grpc_server_deadline_filter);
+}
+
+void grpc_deadline_filter_shutdown(void) {}
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 7c4e9aaed0e..041dcd855f0 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
@@ -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.
-//
-
-#ifndef GRPC_CORE_EXT_FILTERS_DEADLINE_DEADLINE_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_DEADLINE_DEADLINE_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/iomgr/timer.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_DEADLINE_DEADLINE_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_DEADLINE_DEADLINE_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+#include "src/core/lib/iomgr/timer.h"
+
enum grpc_deadline_timer_state {
- GRPC_DEADLINE_STATE_INITIAL,
- GRPC_DEADLINE_STATE_PENDING,
- GRPC_DEADLINE_STATE_FINISHED
+ GRPC_DEADLINE_STATE_INITIAL,
+ GRPC_DEADLINE_STATE_PENDING,
+ GRPC_DEADLINE_STATE_FINISHED
};
-
-// State used for filters that enforce call deadlines.
-// Must be the first field in the filter's call_data.
+
+// State used for filters that enforce call deadlines.
+// 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_deadline_state();
- // We take a reference to the call stack for the timer callback.
- grpc_call_stack* call_stack;
+ // We take a reference to the call stack for the timer callback.
+ grpc_call_stack* call_stack;
grpc_core::CallCombiner* call_combiner;
grpc_deadline_timer_state timer_state = GRPC_DEADLINE_STATE_INITIAL;
- grpc_timer timer;
- grpc_closure timer_callback;
+ grpc_timer timer;
+ grpc_closure timer_callback;
// Closure to invoke when we receive trailing metadata.
- // We use this to cancel the timer.
+ // We use this to cancel the timer.
grpc_closure recv_trailing_metadata_ready;
// The original recv_trailing_metadata_ready closure, which we chain to
// after our own closure is invoked.
grpc_closure* original_recv_trailing_metadata_ready;
};
-
-//
-// NOTE: All of these functions require that the first field in
-// elem->call_data is a grpc_deadline_state.
-//
-
-// Cancels the existing timer and starts a new one with new_deadline.
-//
-// Note: It is generally safe to call this with an earlier deadline
-// value than the current one, but not the reverse. No checks are done
-// to ensure that the timer callback is not invoked while it is in the
-// process of being reset, which means that attempting to increase the
-// deadline may result in the timer being called twice.
-//
-// Note: Must be called while holding the call combiner.
-void grpc_deadline_state_reset(grpc_call_element* elem,
- grpc_millis new_deadline);
-
-// To be called from the client-side filter's start_transport_stream_op_batch()
-// method. Ensures that the deadline timer is cancelled when the call
-// is completed.
-//
-// Note: It is the caller's responsibility to chain to the next filter if
-// necessary after this function returns.
-//
-// Note: Must be called while holding the call combiner.
-void grpc_deadline_state_client_start_transport_stream_op_batch(
- grpc_call_element* elem, grpc_transport_stream_op_batch* op);
-
-// Should deadline checking be performed (according to channel args)
-bool grpc_deadline_checking_enabled(const grpc_channel_args* args);
-
-// Deadline filters for direct client channels and server channels.
-// Note: Deadlines for non-direct client channels are handled by the
-// client_channel filter.
-extern const grpc_channel_filter grpc_client_deadline_filter;
-extern const grpc_channel_filter grpc_server_deadline_filter;
-
-#endif /* GRPC_CORE_EXT_FILTERS_DEADLINE_DEADLINE_FILTER_H */
+
+//
+// NOTE: All of these functions require that the first field in
+// elem->call_data is a grpc_deadline_state.
+//
+
+// Cancels the existing timer and starts a new one with new_deadline.
+//
+// Note: It is generally safe to call this with an earlier deadline
+// value than the current one, but not the reverse. No checks are done
+// to ensure that the timer callback is not invoked while it is in the
+// process of being reset, which means that attempting to increase the
+// deadline may result in the timer being called twice.
+//
+// Note: Must be called while holding the call combiner.
+void grpc_deadline_state_reset(grpc_call_element* elem,
+ grpc_millis new_deadline);
+
+// To be called from the client-side filter's start_transport_stream_op_batch()
+// method. Ensures that the deadline timer is cancelled when the call
+// is completed.
+//
+// Note: It is the caller's responsibility to chain to the next filter if
+// necessary after this function returns.
+//
+// Note: Must be called while holding the call combiner.
+void grpc_deadline_state_client_start_transport_stream_op_batch(
+ grpc_call_element* elem, grpc_transport_stream_op_batch* op);
+
+// Should deadline checking be performed (according to channel args)
+bool grpc_deadline_checking_enabled(const grpc_channel_args* args);
+
+// Deadline filters for direct client channels and server channels.
+// Note: Deadlines for non-direct client channels are handled by the
+// client_channel filter.
+extern const grpc_channel_filter grpc_client_deadline_filter;
+extern const grpc_channel_filter grpc_server_deadline_filter;
+
+#endif /* GRPC_CORE_EXT_FILTERS_DEADLINE_DEADLINE_FILTER_H */
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 f5f18474da8..e055455dd1c 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
@@ -1,22 +1,22 @@
-/*
- * 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>
-
+/*
+ * 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 <stdint.h>
#include <string.h>
@@ -27,34 +27,34 @@
#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 "src/core/ext/filters/http/client/http_client_filter.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/slice/b64.h"
-#include "src/core/lib/slice/percent_encoding.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/transport/static_metadata.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/ext/filters/http/client/http_client_filter.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/slice/b64.h"
+#include "src/core/lib/slice/percent_encoding.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/transport/static_metadata.h"
#include "src/core/lib/transport/status_conversion.h"
-#include "src/core/lib/transport/transport_impl.h"
-
-#define EXPECTED_CONTENT_TYPE "application/grpc"
-#define EXPECTED_CONTENT_TYPE_LENGTH sizeof(EXPECTED_CONTENT_TYPE) - 1
-
+#include "src/core/lib/transport/transport_impl.h"
+
+#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 */
static constexpr size_t kMaxPayloadSizeForGet = 2048;
-
+
static void recv_initial_metadata_ready(void* user_data, grpc_error* error);
static void recv_trailing_metadata_ready(void* user_data, grpc_error* error);
static void on_send_message_next_done(void* arg, grpc_error* error);
static void send_message_on_complete(void* arg, grpc_error* error);
-namespace {
-struct call_data {
+namespace {
+struct call_data {
call_data(grpc_call_element* elem, const grpc_call_element_args& args)
: call_combiner(args.call_combiner) {
GRPC_CLOSURE_INIT(&recv_initial_metadata_ready,
@@ -72,44 +72,44 @@ struct call_data {
~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); }
grpc_core::CallCombiner* call_combiner;
- // State for handling send_initial_metadata ops.
- grpc_linked_mdelem method;
- grpc_linked_mdelem scheme;
- grpc_linked_mdelem authority;
- grpc_linked_mdelem te_trailers;
- grpc_linked_mdelem content_type;
- grpc_linked_mdelem user_agent;
- // State for handling recv_initial_metadata ops.
- grpc_metadata_batch* recv_initial_metadata;
+ // State for handling send_initial_metadata ops.
+ grpc_linked_mdelem method;
+ grpc_linked_mdelem scheme;
+ grpc_linked_mdelem authority;
+ grpc_linked_mdelem te_trailers;
+ grpc_linked_mdelem content_type;
+ grpc_linked_mdelem user_agent;
+ // State for handling recv_initial_metadata ops.
+ grpc_metadata_batch* recv_initial_metadata;
grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE;
grpc_closure* original_recv_initial_metadata_ready = nullptr;
- grpc_closure recv_initial_metadata_ready;
- // State for handling recv_trailing_metadata ops.
- grpc_metadata_batch* recv_trailing_metadata;
+ grpc_closure recv_initial_metadata_ready;
+ // State for handling recv_trailing_metadata ops.
+ grpc_metadata_batch* recv_trailing_metadata;
grpc_closure* original_recv_trailing_metadata_ready;
grpc_closure recv_trailing_metadata_ready;
grpc_error* recv_trailing_metadata_error = GRPC_ERROR_NONE;
bool seen_recv_trailing_metadata_ready = false;
- // State for handling send_message ops.
- grpc_transport_stream_op_batch* send_message_batch;
+ // State for handling send_message ops.
+ grpc_transport_stream_op_batch* send_message_batch;
size_t send_message_bytes_read = 0;
- grpc_core::ManualConstructor<grpc_core::ByteStreamCache> send_message_cache;
- grpc_core::ManualConstructor<grpc_core::ByteStreamCache::CachingByteStream>
- send_message_caching_stream;
- grpc_closure on_send_message_next_done;
- grpc_closure* original_send_message_on_complete;
- grpc_closure send_message_on_complete;
-};
-
-struct channel_data {
- grpc_mdelem static_scheme;
- grpc_mdelem user_agent;
- size_t max_payload_size_for_get;
-};
-} // namespace
-
+ grpc_core::ManualConstructor<grpc_core::ByteStreamCache> send_message_cache;
+ grpc_core::ManualConstructor<grpc_core::ByteStreamCache::CachingByteStream>
+ send_message_caching_stream;
+ grpc_closure on_send_message_next_done;
+ grpc_closure* original_send_message_on_complete;
+ grpc_closure send_message_on_complete;
+};
+
+struct channel_data {
+ grpc_mdelem static_scheme;
+ grpc_mdelem user_agent;
+ size_t max_payload_size_for_get;
+};
+} // namespace
+
static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
- if (b->idx.named.status != nullptr) {
+ 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.
@@ -118,79 +118,79 @@ static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
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);
+ } else {
+ char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.status->md),
+ GPR_DUMP_ASCII);
TString msg =
y_absl::StrCat("Received http2 header with status: ", val);
- grpc_error* e = grpc_error_set_str(
- grpc_error_set_int(
- grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Received http2 :status header with non-200 OK status"),
- GRPC_ERROR_STR_VALUE, grpc_slice_from_copied_string(val)),
+ grpc_error* e = grpc_error_set_str(
+ grpc_error_set_int(
+ grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Received http2 :status header with non-200 OK status"),
+ GRPC_ERROR_STR_VALUE, grpc_slice_from_copied_string(val)),
GRPC_ERROR_INT_GRPC_STATUS,
grpc_http2_status_to_grpc_status(atoi(val))),
GRPC_ERROR_STR_GRPC_MESSAGE,
grpc_slice_from_cpp_string(std::move(msg)));
- gpr_free(val);
- return e;
- }
- }
-
- if (b->idx.named.grpc_message != nullptr) {
- grpc_slice pct_decoded_msg = grpc_permissive_percent_decode_slice(
- GRPC_MDVALUE(b->idx.named.grpc_message->md));
- if (grpc_slice_is_equivalent(pct_decoded_msg,
- GRPC_MDVALUE(b->idx.named.grpc_message->md))) {
- grpc_slice_unref_internal(pct_decoded_msg);
- } else {
- grpc_metadata_batch_set_value(b->idx.named.grpc_message, pct_decoded_msg);
- }
- }
-
- if (b->idx.named.content_type != nullptr) {
+ gpr_free(val);
+ return e;
+ }
+ }
+
+ if (b->idx.named.grpc_message != nullptr) {
+ grpc_slice pct_decoded_msg = grpc_permissive_percent_decode_slice(
+ GRPC_MDVALUE(b->idx.named.grpc_message->md));
+ if (grpc_slice_is_equivalent(pct_decoded_msg,
+ GRPC_MDVALUE(b->idx.named.grpc_message->md))) {
+ grpc_slice_unref_internal(pct_decoded_msg);
+ } else {
+ grpc_metadata_batch_set_value(b->idx.named.grpc_message, pct_decoded_msg);
+ }
+ }
+
+ 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_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md),
- EXPECTED_CONTENT_TYPE,
- EXPECTED_CONTENT_TYPE_LENGTH) &&
- (GRPC_SLICE_START_PTR(GRPC_MDVALUE(
- b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
- '+' ||
- GRPC_SLICE_START_PTR(GRPC_MDVALUE(
- b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
- ';')) {
- /* Although the C implementation doesn't (currently) generate them,
- any custom +-suffix is explicitly valid. */
- /* TODO(klempner): We should consider preallocating common values such
- as +proto or +json, or at least stashing them if we see them. */
- /* TODO(klempner): Should we be surfacing this to application code? */
- } else {
- /* TODO(klempner): We're currently allowing this, but we shouldn't
- see it without a proxy so log for now. */
- char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md),
- GPR_DUMP_ASCII);
- gpr_log(GPR_INFO, "Unexpected content-type '%s'", val);
- gpr_free(val);
- }
- }
+ if (grpc_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md),
+ EXPECTED_CONTENT_TYPE,
+ EXPECTED_CONTENT_TYPE_LENGTH) &&
+ (GRPC_SLICE_START_PTR(GRPC_MDVALUE(
+ b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
+ '+' ||
+ GRPC_SLICE_START_PTR(GRPC_MDVALUE(
+ b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
+ ';')) {
+ /* Although the C implementation doesn't (currently) generate them,
+ any custom +-suffix is explicitly valid. */
+ /* TODO(klempner): We should consider preallocating common values such
+ as +proto or +json, or at least stashing them if we see them. */
+ /* TODO(klempner): Should we be surfacing this to application code? */
+ } else {
+ /* TODO(klempner): We're currently allowing this, but we shouldn't
+ see it without a proxy so log for now. */
+ char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md),
+ GPR_DUMP_ASCII);
+ gpr_log(GPR_INFO, "Unexpected content-type '%s'", val);
+ gpr_free(val);
+ }
+ }
grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_TYPE);
- }
-
- return GRPC_ERROR_NONE;
-}
-
-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) {
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+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);
calld->recv_initial_metadata_error = GRPC_ERROR_REF(error);
- } else {
- GRPC_ERROR_REF(error);
- }
+ } else {
+ GRPC_ERROR_REF(error);
+ }
grpc_closure* closure = calld->original_recv_initial_metadata_ready;
calld->original_recv_initial_metadata_ready = nullptr;
if (calld->seen_recv_trailing_metadata_ready) {
@@ -199,11 +199,11 @@ static void recv_initial_metadata_ready(void* user_data, grpc_error* error) {
calld->recv_trailing_metadata_error, "continue recv_trailing_metadata");
}
grpc_core::Closure::Run(DEBUG_LOCATION, closure, error);
-}
-
+}
+
static void recv_trailing_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);
+ grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
if (calld->original_recv_initial_metadata_ready != nullptr) {
calld->recv_trailing_metadata_error = GRPC_ERROR_REF(error);
calld->seen_recv_trailing_metadata_ready = true;
@@ -212,385 +212,385 @@ static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) {
"after recv_initial_metadata_ready");
return;
}
- if (error == GRPC_ERROR_NONE) {
+ if (error == GRPC_ERROR_NONE) {
error = client_filter_incoming_metadata(calld->recv_trailing_metadata);
- } else {
- GRPC_ERROR_REF(error);
- }
+ } 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);
-}
-
-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();
+}
+
+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));
-}
-
-// Pulls a slice from the send_message byte stream, updating
-// calld->send_message_bytes_read.
-static grpc_error* pull_slice_from_send_message(call_data* calld) {
- grpc_slice incoming_slice;
- grpc_error* error = calld->send_message_caching_stream->Pull(&incoming_slice);
- if (error == GRPC_ERROR_NONE) {
- calld->send_message_bytes_read += GRPC_SLICE_LENGTH(incoming_slice);
- grpc_slice_unref_internal(incoming_slice);
- }
- return error;
-}
-
-// Reads as many slices as possible from the send_message byte stream.
-// Upon successful return, if calld->send_message_bytes_read ==
-// calld->send_message_caching_stream->length(), then we have completed
-// reading from the byte stream; otherwise, an async read has been dispatched
-// and on_send_message_next_done() will be invoked when it is complete.
-static grpc_error* read_all_available_send_message_data(call_data* calld) {
- while (calld->send_message_caching_stream->Next(
- SIZE_MAX, &calld->on_send_message_next_done)) {
- grpc_error* error = pull_slice_from_send_message(calld);
- if (error != GRPC_ERROR_NONE) return error;
- if (calld->send_message_bytes_read ==
- calld->send_message_caching_stream->length()) {
- break;
- }
- }
- return GRPC_ERROR_NONE;
-}
-
-// Async callback for ByteStream::Next().
-static void on_send_message_next_done(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);
- if (error != GRPC_ERROR_NONE) {
- grpc_transport_stream_op_batch_finish_with_failure(
- calld->send_message_batch, error, calld->call_combiner);
- return;
- }
- error = pull_slice_from_send_message(calld);
- if (error != GRPC_ERROR_NONE) {
- grpc_transport_stream_op_batch_finish_with_failure(
- calld->send_message_batch, error, calld->call_combiner);
- return;
- }
- // There may or may not be more to read, but we don't care. If we got
- // here, then we know that all of the data was not available
- // synchronously, so we were not able to do a cached call. Instead,
- // we just reset the byte stream and then send down the batch as-is.
- calld->send_message_caching_stream->Reset();
- grpc_call_next_op(elem, calld->send_message_batch);
-}
-
-static char* slice_buffer_to_string(grpc_slice_buffer* slice_buffer) {
- char* payload_bytes =
- static_cast<char*>(gpr_malloc(slice_buffer->length + 1));
- size_t offset = 0;
- for (size_t i = 0; i < slice_buffer->count; ++i) {
- memcpy(payload_bytes + offset,
- GRPC_SLICE_START_PTR(slice_buffer->slices[i]),
- GRPC_SLICE_LENGTH(slice_buffer->slices[i]));
- offset += GRPC_SLICE_LENGTH(slice_buffer->slices[i]);
- }
- *(payload_bytes + offset) = '\0';
- return payload_bytes;
-}
-
-// Modifies the path entry in the batch's send_initial_metadata to
-// append the base64-encoded query for a GET request.
-static grpc_error* update_path_for_get(grpc_call_element* elem,
- grpc_transport_stream_op_batch* batch) {
- call_data* calld = static_cast<call_data*>(elem->call_data);
- grpc_slice path_slice =
- GRPC_MDVALUE(batch->payload->send_initial_metadata.send_initial_metadata
- ->idx.named.path->md);
- /* sum up individual component's lengths and allocate enough memory to
- * hold combined path+query */
- size_t estimated_len = GRPC_SLICE_LENGTH(path_slice);
- estimated_len++; /* for the '?' */
- estimated_len += grpc_base64_estimate_encoded_size(
+}
+
+// Pulls a slice from the send_message byte stream, updating
+// calld->send_message_bytes_read.
+static grpc_error* pull_slice_from_send_message(call_data* calld) {
+ grpc_slice incoming_slice;
+ grpc_error* error = calld->send_message_caching_stream->Pull(&incoming_slice);
+ if (error == GRPC_ERROR_NONE) {
+ calld->send_message_bytes_read += GRPC_SLICE_LENGTH(incoming_slice);
+ grpc_slice_unref_internal(incoming_slice);
+ }
+ return error;
+}
+
+// Reads as many slices as possible from the send_message byte stream.
+// Upon successful return, if calld->send_message_bytes_read ==
+// calld->send_message_caching_stream->length(), then we have completed
+// reading from the byte stream; otherwise, an async read has been dispatched
+// and on_send_message_next_done() will be invoked when it is complete.
+static grpc_error* read_all_available_send_message_data(call_data* calld) {
+ while (calld->send_message_caching_stream->Next(
+ SIZE_MAX, &calld->on_send_message_next_done)) {
+ grpc_error* error = pull_slice_from_send_message(calld);
+ if (error != GRPC_ERROR_NONE) return error;
+ if (calld->send_message_bytes_read ==
+ calld->send_message_caching_stream->length()) {
+ break;
+ }
+ }
+ return GRPC_ERROR_NONE;
+}
+
+// Async callback for ByteStream::Next().
+static void on_send_message_next_done(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);
+ if (error != GRPC_ERROR_NONE) {
+ grpc_transport_stream_op_batch_finish_with_failure(
+ calld->send_message_batch, error, calld->call_combiner);
+ return;
+ }
+ error = pull_slice_from_send_message(calld);
+ if (error != GRPC_ERROR_NONE) {
+ grpc_transport_stream_op_batch_finish_with_failure(
+ calld->send_message_batch, error, calld->call_combiner);
+ return;
+ }
+ // There may or may not be more to read, but we don't care. If we got
+ // here, then we know that all of the data was not available
+ // synchronously, so we were not able to do a cached call. Instead,
+ // we just reset the byte stream and then send down the batch as-is.
+ calld->send_message_caching_stream->Reset();
+ grpc_call_next_op(elem, calld->send_message_batch);
+}
+
+static char* slice_buffer_to_string(grpc_slice_buffer* slice_buffer) {
+ char* payload_bytes =
+ static_cast<char*>(gpr_malloc(slice_buffer->length + 1));
+ size_t offset = 0;
+ for (size_t i = 0; i < slice_buffer->count; ++i) {
+ memcpy(payload_bytes + offset,
+ GRPC_SLICE_START_PTR(slice_buffer->slices[i]),
+ GRPC_SLICE_LENGTH(slice_buffer->slices[i]));
+ offset += GRPC_SLICE_LENGTH(slice_buffer->slices[i]);
+ }
+ *(payload_bytes + offset) = '\0';
+ return payload_bytes;
+}
+
+// Modifies the path entry in the batch's send_initial_metadata to
+// append the base64-encoded query for a GET request.
+static grpc_error* update_path_for_get(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* batch) {
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_slice path_slice =
+ GRPC_MDVALUE(batch->payload->send_initial_metadata.send_initial_metadata
+ ->idx.named.path->md);
+ /* sum up individual component's lengths and allocate enough memory to
+ * hold combined path+query */
+ 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(),
- false /* multi_line */);
+ false /* multi_line */);
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);
- char* original_path =
- reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_slice);
- memcpy(write_ptr, original_path, GRPC_SLICE_LENGTH(path_slice));
- write_ptr += GRPC_SLICE_LENGTH(path_slice);
- *write_ptr++ = '?';
- char* payload_bytes =
- slice_buffer_to_string(calld->send_message_cache->cache_buffer());
- grpc_base64_encode_core(write_ptr, payload_bytes,
- batch->payload->send_message.send_message->length(),
- true /* url_safe */, false /* multi_line */);
- gpr_free(payload_bytes);
- /* remove trailing unused memory and add trailing 0 to terminate string */
- char* t = reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_with_query_slice);
- /* safe to use strlen since base64_encode will always add '\0' */
- path_with_query_slice =
- grpc_slice_sub_no_ref(path_with_query_slice, 0, strlen(t));
- /* substitute previous path with the new path+query */
- grpc_mdelem mdelem_path_and_query =
- grpc_mdelem_from_slices(GRPC_MDSTR_PATH, path_with_query_slice);
- grpc_metadata_batch* b =
- batch->payload->send_initial_metadata.send_initial_metadata;
- return grpc_metadata_batch_substitute(b, b->idx.named.path,
- mdelem_path_and_query);
-}
-
-static void remove_if_present(grpc_metadata_batch* batch,
- grpc_metadata_batch_callouts_index idx) {
- if (batch->idx.array[idx] != nullptr) {
+ /* memcopy individual pieces into this slice */
+ char* write_ptr =
+ reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_with_query_slice);
+ char* original_path =
+ reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_slice);
+ memcpy(write_ptr, original_path, GRPC_SLICE_LENGTH(path_slice));
+ write_ptr += GRPC_SLICE_LENGTH(path_slice);
+ *write_ptr++ = '?';
+ char* payload_bytes =
+ slice_buffer_to_string(calld->send_message_cache->cache_buffer());
+ grpc_base64_encode_core(write_ptr, payload_bytes,
+ batch->payload->send_message.send_message->length(),
+ true /* url_safe */, false /* multi_line */);
+ gpr_free(payload_bytes);
+ /* remove trailing unused memory and add trailing 0 to terminate string */
+ char* t = reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_with_query_slice);
+ /* safe to use strlen since base64_encode will always add '\0' */
+ path_with_query_slice =
+ grpc_slice_sub_no_ref(path_with_query_slice, 0, strlen(t));
+ /* substitute previous path with the new path+query */
+ grpc_mdelem mdelem_path_and_query =
+ grpc_mdelem_from_slices(GRPC_MDSTR_PATH, path_with_query_slice);
+ grpc_metadata_batch* b =
+ batch->payload->send_initial_metadata.send_initial_metadata;
+ return grpc_metadata_batch_substitute(b, b->idx.named.path,
+ mdelem_path_and_query);
+}
+
+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);
- }
-}
-
+ }
+}
+
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);
+ 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);
-
- if (batch->recv_initial_metadata) {
- /* substitute our callback for the higher callback */
- calld->recv_initial_metadata =
- batch->payload->recv_initial_metadata.recv_initial_metadata;
- calld->original_recv_initial_metadata_ready =
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready;
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
- &calld->recv_initial_metadata_ready;
- }
-
- if (batch->recv_trailing_metadata) {
- /* substitute our callback for the higher callback */
- calld->recv_trailing_metadata =
- batch->payload->recv_trailing_metadata.recv_trailing_metadata;
+
+ if (batch->recv_initial_metadata) {
+ /* substitute our callback for the higher callback */
+ calld->recv_initial_metadata =
+ batch->payload->recv_initial_metadata.recv_initial_metadata;
+ calld->original_recv_initial_metadata_ready =
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready;
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
+ &calld->recv_initial_metadata_ready;
+ }
+
+ if (batch->recv_trailing_metadata) {
+ /* substitute our callback for the higher callback */
+ calld->recv_trailing_metadata =
+ batch->payload->recv_trailing_metadata.recv_trailing_metadata;
calld->original_recv_trailing_metadata_ready =
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready;
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&calld->recv_trailing_metadata_ready;
- }
-
- grpc_error* error = GRPC_ERROR_NONE;
- bool batch_will_be_handled_asynchronously = false;
- if (batch->send_initial_metadata) {
- // Decide which HTTP VERB to use. We use GET if the request is marked
- // cacheable, and the operation contains both initial metadata and send
- // message, and the payload is below the size threshold, and all the data
- // for this request is immediately available.
- grpc_mdelem method = GRPC_MDELEM_METHOD_POST;
- if (batch->send_message &&
- (batch->payload->send_initial_metadata.send_initial_metadata_flags &
- GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) &&
- batch->payload->send_message.send_message->length() <
- channeld->max_payload_size_for_get) {
- calld->send_message_bytes_read = 0;
- calld->send_message_cache.Init(
- std::move(batch->payload->send_message.send_message));
- calld->send_message_caching_stream.Init(calld->send_message_cache.get());
- batch->payload->send_message.send_message.reset(
- calld->send_message_caching_stream.get());
- calld->original_send_message_on_complete = batch->on_complete;
- batch->on_complete = &calld->send_message_on_complete;
- calld->send_message_batch = batch;
- error = read_all_available_send_message_data(calld);
- if (error != GRPC_ERROR_NONE) goto done;
- // If all the data has been read, then we can use GET.
- if (calld->send_message_bytes_read ==
- calld->send_message_caching_stream->length()) {
- method = GRPC_MDELEM_METHOD_GET;
- error = update_path_for_get(elem, batch);
- if (error != GRPC_ERROR_NONE) goto done;
- batch->send_message = false;
- calld->send_message_caching_stream->Orphan();
- } else {
- // Not all data is available. The batch will be sent down
- // asynchronously in on_send_message_next_done().
- batch_will_be_handled_asynchronously = true;
- // Fall back to POST.
- gpr_log(GPR_DEBUG,
- "Request is marked Cacheable but not all data is available. "
- "Falling back to POST");
- }
- } else if (batch->payload->send_initial_metadata
- .send_initial_metadata_flags &
- GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST) {
- method = GRPC_MDELEM_METHOD_PUT;
- }
-
- remove_if_present(
- batch->payload->send_initial_metadata.send_initial_metadata,
- GRPC_BATCH_METHOD);
- remove_if_present(
- batch->payload->send_initial_metadata.send_initial_metadata,
- GRPC_BATCH_SCHEME);
- remove_if_present(
- batch->payload->send_initial_metadata.send_initial_metadata,
- GRPC_BATCH_TE);
- remove_if_present(
- batch->payload->send_initial_metadata.send_initial_metadata,
- GRPC_BATCH_CONTENT_TYPE);
- remove_if_present(
- batch->payload->send_initial_metadata.send_initial_metadata,
- GRPC_BATCH_USER_AGENT);
-
- /* Send : prefixed headers, which have to be before any application
- layer headers. */
- error = grpc_metadata_batch_add_head(
- batch->payload->send_initial_metadata.send_initial_metadata,
+ }
+
+ grpc_error* error = GRPC_ERROR_NONE;
+ bool batch_will_be_handled_asynchronously = false;
+ if (batch->send_initial_metadata) {
+ // Decide which HTTP VERB to use. We use GET if the request is marked
+ // cacheable, and the operation contains both initial metadata and send
+ // message, and the payload is below the size threshold, and all the data
+ // for this request is immediately available.
+ grpc_mdelem method = GRPC_MDELEM_METHOD_POST;
+ if (batch->send_message &&
+ (batch->payload->send_initial_metadata.send_initial_metadata_flags &
+ GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) &&
+ batch->payload->send_message.send_message->length() <
+ channeld->max_payload_size_for_get) {
+ calld->send_message_bytes_read = 0;
+ calld->send_message_cache.Init(
+ std::move(batch->payload->send_message.send_message));
+ calld->send_message_caching_stream.Init(calld->send_message_cache.get());
+ batch->payload->send_message.send_message.reset(
+ calld->send_message_caching_stream.get());
+ calld->original_send_message_on_complete = batch->on_complete;
+ batch->on_complete = &calld->send_message_on_complete;
+ calld->send_message_batch = batch;
+ error = read_all_available_send_message_data(calld);
+ if (error != GRPC_ERROR_NONE) goto done;
+ // If all the data has been read, then we can use GET.
+ if (calld->send_message_bytes_read ==
+ calld->send_message_caching_stream->length()) {
+ method = GRPC_MDELEM_METHOD_GET;
+ error = update_path_for_get(elem, batch);
+ if (error != GRPC_ERROR_NONE) goto done;
+ batch->send_message = false;
+ calld->send_message_caching_stream->Orphan();
+ } else {
+ // Not all data is available. The batch will be sent down
+ // asynchronously in on_send_message_next_done().
+ batch_will_be_handled_asynchronously = true;
+ // Fall back to POST.
+ gpr_log(GPR_DEBUG,
+ "Request is marked Cacheable but not all data is available. "
+ "Falling back to POST");
+ }
+ } else if (batch->payload->send_initial_metadata
+ .send_initial_metadata_flags &
+ GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST) {
+ method = GRPC_MDELEM_METHOD_PUT;
+ }
+
+ remove_if_present(
+ batch->payload->send_initial_metadata.send_initial_metadata,
+ GRPC_BATCH_METHOD);
+ remove_if_present(
+ batch->payload->send_initial_metadata.send_initial_metadata,
+ GRPC_BATCH_SCHEME);
+ remove_if_present(
+ batch->payload->send_initial_metadata.send_initial_metadata,
+ GRPC_BATCH_TE);
+ remove_if_present(
+ batch->payload->send_initial_metadata.send_initial_metadata,
+ GRPC_BATCH_CONTENT_TYPE);
+ remove_if_present(
+ batch->payload->send_initial_metadata.send_initial_metadata,
+ GRPC_BATCH_USER_AGENT);
+
+ /* Send : prefixed headers, which have to be before any application
+ layer headers. */
+ error = grpc_metadata_batch_add_head(
+ batch->payload->send_initial_metadata.send_initial_metadata,
&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,
+ 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);
- if (error != GRPC_ERROR_NONE) goto done;
- error = grpc_metadata_batch_add_tail(
- batch->payload->send_initial_metadata.send_initial_metadata,
+ 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);
- if (error != GRPC_ERROR_NONE) goto done;
- error = grpc_metadata_batch_add_tail(
- batch->payload->send_initial_metadata.send_initial_metadata,
+ 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);
- if (error != GRPC_ERROR_NONE) goto done;
- error = grpc_metadata_batch_add_tail(
- batch->payload->send_initial_metadata.send_initial_metadata,
+ 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);
- if (error != GRPC_ERROR_NONE) goto done;
- }
-
-done:
- if (error != GRPC_ERROR_NONE) {
- grpc_transport_stream_op_batch_finish_with_failure(
- calld->send_message_batch, error, calld->call_combiner);
- } else if (!batch_will_be_handled_asynchronously) {
- grpc_call_next_op(elem, batch);
- }
-}
-
-/* Constructor for call_data */
+ if (error != GRPC_ERROR_NONE) goto done;
+ }
+
+done:
+ if (error != GRPC_ERROR_NONE) {
+ grpc_transport_stream_op_batch_finish_with_failure(
+ calld->send_message_batch, error, calld->call_combiner);
+ } else if (!batch_will_be_handled_asynchronously) {
+ grpc_call_next_op(elem, batch);
+ }
+}
+
+/* Constructor for call_data */
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 */
+ 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*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->~call_data();
}
-
-static grpc_mdelem scheme_from_args(const grpc_channel_args* args) {
- unsigned i;
- size_t j;
- grpc_mdelem valid_schemes[] = {GRPC_MDELEM_SCHEME_HTTP,
- GRPC_MDELEM_SCHEME_HTTPS};
- if (args != nullptr) {
- for (i = 0; i < args->num_args; ++i) {
- if (args->args[i].type == GRPC_ARG_STRING &&
- strcmp(args->args[i].key, GRPC_ARG_HTTP2_SCHEME) == 0) {
- for (j = 0; j < GPR_ARRAY_SIZE(valid_schemes); j++) {
- if (0 == grpc_slice_str_cmp(GRPC_MDVALUE(valid_schemes[j]),
- args->args[i].value.string)) {
- return valid_schemes[j];
- }
- }
- }
- }
- }
- return GRPC_MDELEM_SCHEME_HTTP;
-}
-
-static size_t max_payload_size_from_args(const grpc_channel_args* args) {
- if (args != nullptr) {
- for (size_t i = 0; i < args->num_args; ++i) {
- if (0 == strcmp(args->args[i].key, GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET)) {
- if (args->args[i].type != GRPC_ARG_INTEGER) {
- gpr_log(GPR_ERROR, "%s: must be an integer",
- GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET);
- } else {
- return static_cast<size_t>(args->args[i].value.integer);
- }
- }
- }
- }
- return kMaxPayloadSizeForGet;
-}
-
+
+static grpc_mdelem scheme_from_args(const grpc_channel_args* args) {
+ unsigned i;
+ size_t j;
+ grpc_mdelem valid_schemes[] = {GRPC_MDELEM_SCHEME_HTTP,
+ GRPC_MDELEM_SCHEME_HTTPS};
+ if (args != nullptr) {
+ for (i = 0; i < args->num_args; ++i) {
+ if (args->args[i].type == GRPC_ARG_STRING &&
+ strcmp(args->args[i].key, GRPC_ARG_HTTP2_SCHEME) == 0) {
+ for (j = 0; j < GPR_ARRAY_SIZE(valid_schemes); j++) {
+ if (0 == grpc_slice_str_cmp(GRPC_MDVALUE(valid_schemes[j]),
+ args->args[i].value.string)) {
+ return valid_schemes[j];
+ }
+ }
+ }
+ }
+ }
+ return GRPC_MDELEM_SCHEME_HTTP;
+}
+
+static size_t max_payload_size_from_args(const grpc_channel_args* args) {
+ if (args != nullptr) {
+ for (size_t i = 0; i < args->num_args; ++i) {
+ if (0 == strcmp(args->args[i].key, GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET)) {
+ if (args->args[i].type != GRPC_ARG_INTEGER) {
+ gpr_log(GPR_ERROR, "%s: must be an integer",
+ GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET);
+ } else {
+ return static_cast<size_t>(args->args[i].value.integer);
+ }
+ }
+ }
+ }
+ return kMaxPayloadSizeForGet;
+}
+
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++) {
- if (0 == strcmp(args->args[i].key, GRPC_ARG_PRIMARY_USER_AGENT_STRING)) {
- if (args->args[i].type != GRPC_ARG_STRING) {
- gpr_log(GPR_ERROR, "Channel argument '%s' should be a string",
- GRPC_ARG_PRIMARY_USER_AGENT_STRING);
- } else {
+ if (0 == strcmp(args->args[i].key, GRPC_ARG_PRIMARY_USER_AGENT_STRING)) {
+ if (args->args[i].type != GRPC_ARG_STRING) {
+ gpr_log(GPR_ERROR, "Channel argument '%s' should be a string",
+ GRPC_ARG_PRIMARY_USER_AGENT_STRING);
+ } else {
user_agent_fields.push_back(args->args[i].value.string);
- }
- }
- }
-
+ }
+ }
+ }
+
user_agent_fields.push_back(
y_absl::StrFormat("grpc-c/%s (%s; %s)", grpc_version_string(),
GPR_PLATFORM_STRING, transport_name));
-
+
for (size_t i = 0; args && i < args->num_args; i++) {
- if (0 == strcmp(args->args[i].key, GRPC_ARG_SECONDARY_USER_AGENT_STRING)) {
- if (args->args[i].type != GRPC_ARG_STRING) {
- gpr_log(GPR_ERROR, "Channel argument '%s' should be a string",
- GRPC_ARG_SECONDARY_USER_AGENT_STRING);
- } else {
+ if (0 == strcmp(args->args[i].key, GRPC_ARG_SECONDARY_USER_AGENT_STRING)) {
+ if (args->args[i].type != GRPC_ARG_STRING) {
+ gpr_log(GPR_ERROR, "Channel argument '%s' should be a string",
+ GRPC_ARG_SECONDARY_USER_AGENT_STRING);
+ } else {
user_agent_fields.push_back(args->args[i].value.string);
- }
- }
- }
-
+ }
+ }
+ }
+
TString user_agent_string = y_absl::StrJoin(user_agent_fields, " ");
return grpc_core::ManagedMemorySlice(user_agent_string.c_str());
-}
-
-/* Constructor for channel_data */
+}
+
+/* Constructor for channel_data */
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);
- chand->static_scheme = scheme_from_args(args->channel_args);
- chand->max_payload_size_for_get =
- max_payload_size_from_args(args->channel_args);
- chand->user_agent = grpc_mdelem_from_slices(
- GRPC_MDSTR_USER_AGENT,
- user_agent_from_args(args->channel_args,
- args->optional_transport->vtable->name));
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel data */
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ GPR_ASSERT(!args->is_last);
+ GPR_ASSERT(args->optional_transport != nullptr);
+ chand->static_scheme = scheme_from_args(args->channel_args);
+ chand->max_payload_size_for_get =
+ max_payload_size_from_args(args->channel_args);
+ chand->user_agent = grpc_mdelem_from_slices(
+ GRPC_MDSTR_USER_AGENT,
+ user_agent_from_args(args->channel_args,
+ args->optional_transport->vtable->name));
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for channel data */
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 = {
+ 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,
- grpc_channel_next_op,
- sizeof(call_data),
+ grpc_channel_next_op,
+ sizeof(call_data),
http_client_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
http_client_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
http_client_init_channel_elem,
http_client_destroy_channel_elem,
- grpc_channel_next_get_info,
- "http-client"};
+ 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 a2f16ddbfbe..ead665faa1e 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
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_HTTP_CLIENT_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_HTTP_CLIENT_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-
-/* Processes metadata on the client side for HTTP2 transports */
-extern const grpc_channel_filter grpc_http_client_filter;
-
+/*
+ * 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_EXT_FILTERS_HTTP_CLIENT_HTTP_CLIENT_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_HTTP_CLIENT_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+
+/* 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 */
-#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 */
+#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 2c3cae6adbc..d2aed990c50 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
@@ -1,159 +1,159 @@
-/*
- *
- * 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 <assert.h>
-#include <limits.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/http/client_authority_filter.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/surface/channel_stack_type.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-namespace {
-
-struct call_data {
- grpc_linked_mdelem authority_storage;
+/*
+ *
+ * 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 <assert.h>
+#include <limits.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/http/client_authority_filter.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/surface/channel_stack_type.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+namespace {
+
+struct call_data {
+ grpc_linked_mdelem authority_storage;
grpc_core::CallCombiner* call_combiner;
-};
-
-struct channel_data {
+};
+
+struct channel_data {
grpc_core::ManagedMemorySlice default_authority;
grpc_mdelem default_authority_mdelem;
-};
-
+};
+
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);
- // Handle send_initial_metadata.
- // If the initial metadata doesn't already contain :authority, add it.
- if (batch->send_initial_metadata &&
+ 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);
+ // Handle send_initial_metadata.
+ // If the initial metadata doesn't already contain :authority, add it.
+ if (batch->send_initial_metadata &&
batch->payload->send_initial_metadata.send_initial_metadata->idx.named
.authority == nullptr) {
- grpc_error* error = grpc_metadata_batch_add_head(
+ 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);
- if (error != GRPC_ERROR_NONE) {
- grpc_transport_stream_op_batch_finish_with_failure(batch, error,
- calld->call_combiner);
- return;
- }
- }
- // Pass control down the stack.
- grpc_call_next_op(elem, batch);
-}
-
-/* Constructor for call_data */
+ if (error != GRPC_ERROR_NONE) {
+ grpc_transport_stream_op_batch_finish_with_failure(batch, error,
+ calld->call_combiner);
+ return;
+ }
+ }
+ // Pass control down the stack.
+ grpc_call_next_op(elem, batch);
+}
+
+/* Constructor for call_data */
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 */
+ 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*/) {}
-
-/* Constructor for channel_data */
+
+/* Constructor for channel_data */
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);
- if (default_authority_arg == nullptr) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "GRPC_ARG_DEFAULT_AUTHORITY channel arg. not found. Note that direct "
+ 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);
+ if (default_authority_arg == nullptr) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "GRPC_ARG_DEFAULT_AUTHORITY channel arg. not found. Note that direct "
"channels must explicitly specify a value for this argument.");
- }
- const char* default_authority_str =
- grpc_channel_arg_get_string(default_authority_arg);
- if (default_authority_str == nullptr) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "GRPC_ARG_DEFAULT_AUTHORITY channel arg. must be a string");
- }
- chand->default_authority =
+ }
+ const char* default_authority_str =
+ grpc_channel_arg_get_string(default_authority_arg);
+ if (default_authority_str == nullptr) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "GRPC_ARG_DEFAULT_AUTHORITY channel arg. must be a string");
+ }
+ chand->default_authority =
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);
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel data */
+ GPR_ASSERT(!args->is_last);
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for channel data */
void client_authority_destroy_channel_elem(grpc_channel_element* elem) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
grpc_slice_unref_internal(chand->default_authority);
GRPC_MDELEM_UNREF(chand->default_authority_mdelem);
-}
-} // namespace
-
-const grpc_channel_filter grpc_client_authority_filter = {
+}
+} // namespace
+
+const grpc_channel_filter grpc_client_authority_filter = {
client_authority_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(call_data),
+ grpc_channel_next_op,
+ sizeof(call_data),
client_authority_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
client_authority_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
client_authority_init_channel_elem,
client_authority_destroy_channel_elem,
- grpc_channel_next_get_info,
- "authority"};
-
-static bool add_client_authority_filter(grpc_channel_stack_builder* builder,
- void* arg) {
- const grpc_channel_args* channel_args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- const grpc_arg* disable_client_authority_filter_arg = grpc_channel_args_find(
- channel_args, GRPC_ARG_DISABLE_CLIENT_AUTHORITY_FILTER);
- if (disable_client_authority_filter_arg != nullptr) {
- const bool is_client_authority_filter_disabled =
- grpc_channel_arg_get_bool(disable_client_authority_filter_arg, false);
- if (is_client_authority_filter_disabled) {
- return true;
- }
- }
- return grpc_channel_stack_builder_prepend_filter(
- builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
-}
-
-void grpc_client_authority_filter_init(void) {
- grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, INT_MAX,
- add_client_authority_filter,
- (void*)&grpc_client_authority_filter);
- grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, INT_MAX,
- add_client_authority_filter,
- (void*)&grpc_client_authority_filter);
-}
-
-void grpc_client_authority_filter_shutdown(void) {}
+ grpc_channel_next_get_info,
+ "authority"};
+
+static bool add_client_authority_filter(grpc_channel_stack_builder* builder,
+ void* arg) {
+ const grpc_channel_args* channel_args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ const grpc_arg* disable_client_authority_filter_arg = grpc_channel_args_find(
+ channel_args, GRPC_ARG_DISABLE_CLIENT_AUTHORITY_FILTER);
+ if (disable_client_authority_filter_arg != nullptr) {
+ const bool is_client_authority_filter_disabled =
+ grpc_channel_arg_get_bool(disable_client_authority_filter_arg, false);
+ if (is_client_authority_filter_disabled) {
+ return true;
+ }
+ }
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
+}
+
+void grpc_client_authority_filter_init(void) {
+ grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, INT_MAX,
+ add_client_authority_filter,
+ (void*)&grpc_client_authority_filter);
+ grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, INT_MAX,
+ add_client_authority_filter,
+ (void*)&grpc_client_authority_filter);
+}
+
+void grpc_client_authority_filter_shutdown(void) {}
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.h b/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.h
index 5824e91ff21..eb9078bfb41 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.h
@@ -1,34 +1,34 @@
-/*
- *
- * 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_HTTP_CLIENT_AUTHORITY_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_AUTHORITY_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/compression_types.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-
-/// Filter responsible for setting the authority header, if not already set. It
-/// uses the value of the GRPC_ARG_DEFAULT_AUTHORITY channel arg if the initial
-/// metadata doesn't already contain an authority value.
-
-extern const grpc_channel_filter grpc_client_authority_filter;
-
-#endif /* GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_AUTHORITY_FILTER_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_HTTP_CLIENT_AUTHORITY_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_AUTHORITY_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/impl/codegen/compression_types.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+
+/// Filter responsible for setting the authority header, if not already set. It
+/// uses the value of the GRPC_ARG_DEFAULT_AUTHORITY channel arg if the initial
+/// metadata doesn't already contain an authority value.
+
+extern const grpc_channel_filter grpc_client_authority_filter;
+
+#endif /* GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_AUTHORITY_FILTER_H */
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/http_filters_plugin.cc b/contrib/libs/grpc/src/core/ext/filters/http/http_filters_plugin.cc
index 637dc3030f2..9519fd3571b 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/http_filters_plugin.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/http/http_filters_plugin.cc
@@ -1,80 +1,80 @@
-/*
- *
- * 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 <string.h>
-
-#include "src/core/ext/filters/http/client/http_client_filter.h"
-#include "src/core/ext/filters/http/message_compress/message_compress_filter.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <string.h>
+
+#include "src/core/ext/filters/http/client/http_client_filter.h"
+#include "src/core/ext/filters/http/message_compress/message_compress_filter.h"
#include "src/core/ext/filters/http/message_compress/message_decompress_filter.h"
-#include "src/core/ext/filters/http/server/http_server_filter.h"
-#include "src/core/lib/channel/channel_stack_builder.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/transport/transport_impl.h"
-
+#include "src/core/ext/filters/http/server/http_server_filter.h"
+#include "src/core/lib/channel/channel_stack_builder.h"
+#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/transport/transport_impl.h"
+
struct optional_filter {
- const grpc_channel_filter* filter;
- const char* control_channel_arg;
+ const grpc_channel_filter* filter;
+ const char* control_channel_arg;
};
-
-static optional_filter compress_filter = {
- &grpc_message_compress_filter, GRPC_ARG_ENABLE_PER_MESSAGE_COMPRESSION};
-
+
+static optional_filter compress_filter = {
+ &grpc_message_compress_filter, GRPC_ARG_ENABLE_PER_MESSAGE_COMPRESSION};
+
static optional_filter decompress_filter = {
&grpc_core::MessageDecompressFilter,
GRPC_ARG_ENABLE_PER_MESSAGE_DECOMPRESSION};
-static bool is_building_http_like_transport(
- grpc_channel_stack_builder* builder) {
- grpc_transport* t = grpc_channel_stack_builder_get_transport(builder);
- return t != nullptr && strstr(t->vtable->name, "http");
-}
-
+static bool is_building_http_like_transport(
+ grpc_channel_stack_builder* builder) {
+ grpc_transport* t = grpc_channel_stack_builder_get_transport(builder);
+ return t != nullptr && strstr(t->vtable->name, "http");
+}
+
template <bool enable_in_minimal_stack>
-static bool maybe_add_optional_filter(grpc_channel_stack_builder* builder,
- void* arg) {
- if (!is_building_http_like_transport(builder)) return true;
- optional_filter* filtarg = static_cast<optional_filter*>(arg);
- const grpc_channel_args* channel_args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- bool enable = grpc_channel_arg_get_bool(
- grpc_channel_args_find(channel_args, filtarg->control_channel_arg),
+static bool maybe_add_optional_filter(grpc_channel_stack_builder* builder,
+ void* arg) {
+ if (!is_building_http_like_transport(builder)) return true;
+ optional_filter* filtarg = static_cast<optional_filter*>(arg);
+ const grpc_channel_args* channel_args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ bool enable = grpc_channel_arg_get_bool(
+ grpc_channel_args_find(channel_args, filtarg->control_channel_arg),
enable_in_minimal_stack ||
!grpc_channel_args_want_minimal_stack(channel_args));
- return enable ? grpc_channel_stack_builder_prepend_filter(
- builder, filtarg->filter, nullptr, nullptr)
- : true;
-}
-
-static bool maybe_add_required_filter(grpc_channel_stack_builder* builder,
- void* arg) {
- return is_building_http_like_transport(builder)
- ? grpc_channel_stack_builder_prepend_filter(
- builder, static_cast<const grpc_channel_filter*>(arg),
- nullptr, nullptr)
- : true;
-}
-
-void grpc_http_filters_init(void) {
- grpc_channel_init_register_stage(
- GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ return enable ? grpc_channel_stack_builder_prepend_filter(
+ builder, filtarg->filter, nullptr, nullptr)
+ : true;
+}
+
+static bool maybe_add_required_filter(grpc_channel_stack_builder* builder,
+ void* arg) {
+ return is_building_http_like_transport(builder)
+ ? grpc_channel_stack_builder_prepend_filter(
+ builder, static_cast<const grpc_channel_filter*>(arg),
+ nullptr, nullptr)
+ : true;
+}
+
+void grpc_http_filters_init(void) {
+ grpc_channel_init_register_stage(
+ GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
maybe_add_optional_filter<false>, &compress_filter);
grpc_channel_init_register_stage(
GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
@@ -93,13 +93,13 @@ void grpc_http_filters_init(void) {
maybe_add_optional_filter<true>, &decompress_filter);
grpc_channel_init_register_stage(
GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_required_filter, (void*)&grpc_http_client_filter);
- grpc_channel_init_register_stage(
- GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_required_filter, (void*)&grpc_http_client_filter);
- grpc_channel_init_register_stage(
- GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_required_filter, (void*)&grpc_http_server_filter);
-}
-
-void grpc_http_filters_shutdown(void) {}
+ maybe_add_required_filter, (void*)&grpc_http_client_filter);
+ grpc_channel_init_register_stage(
+ GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ maybe_add_required_filter, (void*)&grpc_http_client_filter);
+ grpc_channel_init_register_stage(
+ GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ maybe_add_required_filter, (void*)&grpc_http_server_filter);
+}
+
+void grpc_http_filters_shutdown(void) {}
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 53f6e2b80de..877bacf83c7 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
@@ -1,48 +1,48 @@
-/*
- *
- * 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 <assert.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 <assert.h>
+#include <string.h>
+
#include "y_absl/types/optional.h"
-#include <grpc/compression.h>
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#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 <grpc/compression.h>
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#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_internal.h"
-#include "src/core/lib/compression/message_compress.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/manual_constructor.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/call.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-namespace {
+#include "src/core/lib/compression/compression_internal.h"
+#include "src/core/lib/compression/message_compress.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/manual_constructor.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/call.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+namespace {
class ChannelData {
public:
@@ -98,8 +98,8 @@ class ChannelData {
uint32_t enabled_message_compression_algorithms_bitset_;
/** Bitset of enabled stream compression algorithms */
uint32_t enabled_stream_compression_algorithms_bitset_;
-};
-
+};
+
class CallData {
public:
CallData(grpc_call_element* elem, const grpc_call_element_args& args)
@@ -170,17 +170,17 @@ class CallData {
grpc_closure* original_send_message_on_complete_ = nullptr;
grpc_closure send_message_on_complete_;
grpc_closure on_send_message_next_done_;
-};
-
+};
+
// 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 =
send_message_batch_->payload->send_message.send_message->flags();
- if (flags & (GRPC_WRITE_NO_COMPRESS | GRPC_WRITE_INTERNAL_COMPRESS)) {
- return true;
- }
+ 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.
return message_compression_algorithm_ == GRPC_MESSAGE_COMPRESS_NONE;
@@ -192,7 +192,7 @@ grpc_compression_algorithm FindCompressionAlgorithm(
grpc_metadata_batch* initial_metadata, ChannelData* channeld) {
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 =
@@ -220,8 +220,8 @@ grpc_compression_algorithm FindCompressionAlgorithm(
"Will not compress.",
algorithm_name);
return GRPC_COMPRESS_NONE;
-}
-
+}
+
void CallData::InitializeState(grpc_call_element* elem) {
GPR_DEBUG_ASSERT(!state_initialized_);
state_initialized_ = true;
@@ -242,14 +242,14 @@ grpc_error* CallData::ProcessSendInitialMetadata(
message_compression_algorithm_ =
grpc_compression_algorithm_to_message_compression_algorithm(
compression_algorithm);
- grpc_stream_compression_algorithm stream_compression_algorithm =
+ grpc_stream_compression_algorithm stream_compression_algorithm =
grpc_compression_algorithm_to_stream_compression_algorithm(
compression_algorithm);
// Hint compression algorithm.
- grpc_error* error = GRPC_ERROR_NONE;
+ grpc_error* error = GRPC_ERROR_NONE;
if (message_compression_algorithm_ != GRPC_MESSAGE_COMPRESS_NONE) {
InitializeState(elem);
- error = grpc_metadata_batch_add_tail(
+ error = grpc_metadata_batch_add_tail(
initial_metadata, &message_compression_algorithm_storage_,
grpc_message_compression_encoding_mdelem(
message_compression_algorithm_),
@@ -260,83 +260,83 @@ grpc_error* CallData::ProcessSendInitialMetadata(
initial_metadata, &stream_compression_algorithm_storage_,
grpc_stream_compression_encoding_mdelem(stream_compression_algorithm),
GRPC_BATCH_CONTENT_ENCODING);
- }
- if (error != GRPC_ERROR_NONE) return error;
+ }
+ if (error != GRPC_ERROR_NONE) return error;
// Convey supported compression algorithms.
- error = grpc_metadata_batch_add_tail(
+ error = grpc_metadata_batch_add_tail(
initial_metadata, &accept_encoding_storage_,
- GRPC_MDELEM_ACCEPT_ENCODING_FOR_ALGORITHMS(
+ GRPC_MDELEM_ACCEPT_ENCODING_FOR_ALGORITHMS(
channeld->enabled_message_compression_algorithms_bitset()),
GRPC_BATCH_GRPC_ACCEPT_ENCODING);
- if (error != GRPC_ERROR_NONE) return error;
+ if (error != GRPC_ERROR_NONE) return error;
// 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(
+ 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(
+ GRPC_MDELEM_ACCEPT_STREAM_ENCODING_FOR_ALGORITHMS(
channeld->enabled_stream_compression_algorithms_bitset()),
GRPC_BATCH_ACCEPT_ENCODING);
- }
- return error;
-}
-
+ }
+ return error;
+}
+
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,
calld->original_send_message_on_complete_,
GRPC_ERROR_REF(error));
-}
-
+}
+
void CallData::SendMessageBatchContinue(grpc_call_element* elem) {
- // Note: The call to grpc_call_next_op() results in yielding the
+ // Note: The call to grpc_call_next_op() results in yielding the
// call combiner, so we need to clear send_message_batch_ before we do that.
grpc_transport_stream_op_batch* send_message_batch = send_message_batch_;
send_message_batch_ = nullptr;
- grpc_call_next_op(elem, send_message_batch);
-}
-
+ grpc_call_next_op(elem, send_message_batch);
+}
+
void CallData::FinishSendMessage(grpc_call_element* elem) {
GPR_DEBUG_ASSERT(message_compression_algorithm_ !=
GRPC_MESSAGE_COMPRESS_NONE);
- // Compress the data if appropriate.
- grpc_slice_buffer tmp;
- grpc_slice_buffer_init(&tmp);
- uint32_t send_flags =
+ // Compress the data if appropriate.
+ grpc_slice_buffer tmp;
+ grpc_slice_buffer_init(&tmp);
+ uint32_t send_flags =
send_message_batch_->payload->send_message.send_message->flags();
bool did_compress =
grpc_msg_compress(message_compression_algorithm_, &slices_, &tmp);
- if (did_compress) {
+ if (did_compress) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
- const char* algo_name;
+ const char* algo_name;
const size_t before_size = slices_.length;
- const size_t after_size = tmp.length;
- const float savings_ratio = 1.0f - static_cast<float>(after_size) /
- static_cast<float>(before_size);
- GPR_ASSERT(grpc_message_compression_algorithm_name(
+ const size_t after_size = tmp.length;
+ const float savings_ratio = 1.0f - static_cast<float>(after_size) /
+ static_cast<float>(before_size);
+ GPR_ASSERT(grpc_message_compression_algorithm_name(
message_compression_algorithm_, &algo_name));
- gpr_log(GPR_INFO,
- "Compressed[%s] %" PRIuPTR " bytes vs. %" PRIuPTR
- " bytes (%.2f%% savings)",
- algo_name, before_size, after_size, 100 * savings_ratio);
- }
+ gpr_log(GPR_INFO,
+ "Compressed[%s] %" PRIuPTR " bytes vs. %" PRIuPTR
+ " bytes (%.2f%% savings)",
+ algo_name, before_size, after_size, 100 * savings_ratio);
+ }
grpc_slice_buffer_swap(&slices_, &tmp);
- send_flags |= GRPC_WRITE_INTERNAL_COMPRESS;
- } else {
+ send_flags |= GRPC_WRITE_INTERNAL_COMPRESS;
+ } else {
if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) {
- const char* algo_name;
- GPR_ASSERT(grpc_message_compression_algorithm_name(
+ const char* algo_name;
+ GPR_ASSERT(grpc_message_compression_algorithm_name(
message_compression_algorithm_, &algo_name));
- gpr_log(GPR_INFO,
- "Algorithm '%s' enabled but decided not to compress. Input size: "
- "%" PRIuPTR,
+ gpr_log(GPR_INFO,
+ "Algorithm '%s' enabled but decided not to compress. Input size: "
+ "%" PRIuPTR,
algo_name, slices_.length);
- }
- }
- grpc_slice_buffer_destroy_internal(&tmp);
- // Swap out the original byte stream with our new one and send the
- // batch down.
+ }
+ }
+ grpc_slice_buffer_destroy_internal(&tmp);
+ // Swap out the original byte stream with our new one and send the
+ // batch down.
new (&replacement_stream_)
grpc_core::SliceBufferByteStream(&slices_, send_flags);
send_message_batch_->payload->send_message.send_message.reset(
@@ -345,34 +345,34 @@ void CallData::FinishSendMessage(grpc_call_element* elem) {
original_send_message_on_complete_ = send_message_batch_->on_complete;
send_message_batch_->on_complete = &send_message_on_complete_;
SendMessageBatchContinue(elem);
-}
-
+}
+
void CallData::FailSendMessageBatchInCallCombiner(void* calld_arg,
grpc_error* error) {
CallData* calld = static_cast<CallData*>(calld_arg);
if (calld->send_message_batch_ != nullptr) {
- grpc_transport_stream_op_batch_finish_with_failure(
+ grpc_transport_stream_op_batch_finish_with_failure(
calld->send_message_batch_, GRPC_ERROR_REF(error),
calld->call_combiner_);
calld->send_message_batch_ = nullptr;
- }
-}
-
+ }
+}
+
// Pulls a slice from the send_message byte stream and adds it to slices_.
grpc_error* CallData::PullSliceFromSendMessage() {
- grpc_slice incoming_slice;
- grpc_error* error =
+ grpc_slice incoming_slice;
+ grpc_error* error =
send_message_batch_->payload->send_message.send_message->Pull(
- &incoming_slice);
- if (error == GRPC_ERROR_NONE) {
+ &incoming_slice);
+ if (error == GRPC_ERROR_NONE) {
grpc_slice_buffer_add(&slices_, incoming_slice);
- }
- return error;
-}
-
-// Reads as many slices as possible from the send_message byte stream.
+ }
+ return error;
+}
+
+// Reads as many slices as possible from the send_message byte stream.
// If all data has been read, invokes FinishSendMessage(). Otherwise,
-// an async call to ByteStream::Next() has been started, which will
+// an async call to ByteStream::Next() has been started, which will
// eventually result in calling OnSendMessageNextDone().
void CallData::ContinueReadingSendMessage(grpc_call_element* elem) {
if (slices_.length ==
@@ -383,164 +383,164 @@ void CallData::ContinueReadingSendMessage(grpc_call_element* elem) {
while (send_message_batch_->payload->send_message.send_message->Next(
~static_cast<size_t>(0), &on_send_message_next_done_)) {
grpc_error* error = PullSliceFromSendMessage();
- if (error != GRPC_ERROR_NONE) {
- // Closure callback; does not take ownership of error.
+ if (error != GRPC_ERROR_NONE) {
+ // Closure callback; does not take ownership of error.
FailSendMessageBatchInCallCombiner(this, error);
- GRPC_ERROR_UNREF(error);
- return;
- }
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
if (slices_.length ==
send_message_batch_->payload->send_message.send_message->length()) {
FinishSendMessage(elem);
- break;
- }
- }
-}
-
-// Async callback for ByteStream::Next().
+ break;
+ }
+ }
+}
+
+// Async callback for ByteStream::Next().
void CallData::OnSendMessageNextDone(void* elem_arg, grpc_error* error) {
grpc_call_element* elem = static_cast<grpc_call_element*>(elem_arg);
CallData* calld = static_cast<CallData*>(elem->call_data);
- if (error != GRPC_ERROR_NONE) {
- // Closure callback; does not take ownership of error.
+ if (error != GRPC_ERROR_NONE) {
+ // Closure callback; does not take ownership of error.
FailSendMessageBatchInCallCombiner(calld, error);
- return;
- }
+ return;
+ }
error = calld->PullSliceFromSendMessage();
- if (error != GRPC_ERROR_NONE) {
- // Closure callback; does not take ownership of error.
+ if (error != GRPC_ERROR_NONE) {
+ // Closure callback; does not take ownership of error.
FailSendMessageBatchInCallCombiner(calld, error);
- GRPC_ERROR_UNREF(error);
- return;
- }
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
if (calld->slices_.length == calld->send_message_batch_->payload->send_message
.send_message->length()) {
calld->FinishSendMessage(elem);
- } else {
+ } else {
calld->ContinueReadingSendMessage(elem);
- }
-}
-
+ }
+}
+
void CallData::StartSendMessageBatch(void* elem_arg, grpc_error* /*unused*/) {
grpc_call_element* elem = static_cast<grpc_call_element*>(elem_arg);
CallData* calld = static_cast<CallData*>(elem->call_data);
if (calld->SkipMessageCompression()) {
calld->SendMessageBatchContinue(elem);
- } else {
+ } else {
calld->ContinueReadingSendMessage(elem);
- }
-}
-
+ }
+}
+
void CallData::CompressStartTransportStreamOpBatch(
- grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
- GPR_TIMER_SCOPE("compress_start_transport_stream_op_batch", 0);
- // Handle cancel_stream.
- if (batch->cancel_stream) {
+ grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
+ GPR_TIMER_SCOPE("compress_start_transport_stream_op_batch", 0);
+ // Handle cancel_stream.
+ if (batch->cancel_stream) {
GRPC_ERROR_UNREF(cancel_error_);
cancel_error_ = GRPC_ERROR_REF(batch->payload->cancel_stream.cancel_error);
if (send_message_batch_ != nullptr) {
if (!seen_initial_metadata_) {
- GRPC_CALL_COMBINER_START(
+ GRPC_CALL_COMBINER_START(
call_combiner_,
GRPC_CLOSURE_CREATE(FailSendMessageBatchInCallCombiner, this,
- grpc_schedule_on_exec_ctx),
+ grpc_schedule_on_exec_ctx),
GRPC_ERROR_REF(cancel_error_), "failing send_message op");
- } else {
+ } else {
send_message_batch_->payload->send_message.send_message->Shutdown(
GRPC_ERROR_REF(cancel_error_));
- }
- }
+ }
+ }
} else if (cancel_error_ != GRPC_ERROR_NONE) {
- grpc_transport_stream_op_batch_finish_with_failure(
+ grpc_transport_stream_op_batch_finish_with_failure(
batch, GRPC_ERROR_REF(cancel_error_), call_combiner_);
- return;
- }
- // Handle send_initial_metadata.
- if (batch->send_initial_metadata) {
+ return;
+ }
+ // Handle send_initial_metadata.
+ if (batch->send_initial_metadata) {
GPR_ASSERT(!seen_initial_metadata_);
grpc_error* error = ProcessSendInitialMetadata(
elem, batch->payload->send_initial_metadata.send_initial_metadata);
- if (error != GRPC_ERROR_NONE) {
- grpc_transport_stream_op_batch_finish_with_failure(batch, error,
+ if (error != GRPC_ERROR_NONE) {
+ grpc_transport_stream_op_batch_finish_with_failure(batch, error,
call_combiner_);
- return;
- }
+ return;
+ }
seen_initial_metadata_ = true;
- // If we had previously received a batch containing a send_message op,
- // handle it now. Note that we need to re-enter the call combiner
- // for this, since we can't send two batches down while holding the
- // call combiner, since the connected_channel filter (at the bottom of
- // the call stack) will release the call combiner for each batch it sees.
+ // If we had previously received a batch containing a send_message op,
+ // handle it now. Note that we need to re-enter the call combiner
+ // for this, since we can't send two batches down while holding the
+ // call combiner, since the connected_channel filter (at the bottom of
+ // the call stack) will release the call combiner for each batch it sees.
if (send_message_batch_ != nullptr) {
- GRPC_CALL_COMBINER_START(
+ GRPC_CALL_COMBINER_START(
call_combiner_, &start_send_message_batch_in_call_combiner_,
GRPC_ERROR_NONE, "starting send_message after send_initial_metadata");
- }
- }
- // Handle send_message.
- if (batch->send_message) {
+ }
+ }
+ // Handle send_message.
+ if (batch->send_message) {
GPR_ASSERT(send_message_batch_ == nullptr);
send_message_batch_ = batch;
- // If we have not yet seen send_initial_metadata, then we have to
+ // If we have not yet seen send_initial_metadata, then we have to
// wait. We save the batch and then drop the call combiner, which we'll
// have to pick up again later when we get send_initial_metadata.
if (!seen_initial_metadata_) {
- GRPC_CALL_COMBINER_STOP(
+ GRPC_CALL_COMBINER_STOP(
call_combiner_, "send_message batch pending send_initial_metadata");
- return;
- }
+ return;
+ }
StartSendMessageBatch(elem, GRPC_ERROR_NONE);
- } else {
- // Pass control down the stack.
- grpc_call_next_op(elem, batch);
- }
-}
-
+ } else {
+ // Pass control down the stack.
+ grpc_call_next_op(elem, batch);
+ }
+}
+
void CompressStartTransportStreamOpBatch(
grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
CallData* calld = static_cast<CallData*>(elem->call_data);
calld->CompressStartTransportStreamOpBatch(elem, batch);
}
-/* Constructor for call_data */
+/* Constructor for call_data */
grpc_error* CompressInitCallElem(grpc_call_element* elem,
const grpc_call_element_args* args) {
new (elem->call_data) CallData(elem, *args);
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for call_data */
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for call_data */
void CompressDestroyCallElem(grpc_call_element* elem,
const grpc_call_final_info* /*final_info*/,
grpc_closure* /*ignored*/) {
CallData* calld = static_cast<CallData*>(elem->call_data);
calld->~CallData();
-}
-
+}
+
/* Constructor for ChannelData */
grpc_error* CompressInitChannelElem(grpc_channel_element* elem,
grpc_channel_element_args* args) {
new (elem->channel_data) ChannelData(args);
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel data */
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for channel data */
void CompressDestroyChannelElem(grpc_channel_element* elem) {
ChannelData* channeld = static_cast<ChannelData*>(elem->channel_data);
channeld->~ChannelData();
}
-
+
} // namespace
-const grpc_channel_filter grpc_message_compress_filter = {
+const grpc_channel_filter grpc_message_compress_filter = {
CompressStartTransportStreamOpBatch,
- grpc_channel_next_op,
+ grpc_channel_next_op,
sizeof(CallData),
CompressInitCallElem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
CompressDestroyCallElem,
sizeof(ChannelData),
CompressInitChannelElem,
CompressDestroyChannelElem,
- grpc_channel_next_get_info,
- "message_compress"};
+ grpc_channel_next_get_info,
+ "message_compress"};
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.h b/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.h
index e163e3cf98f..37b5a0b917c 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.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_CORE_EXT_FILTERS_HTTP_MESSAGE_COMPRESS_MESSAGE_COMPRESS_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_HTTP_MESSAGE_COMPRESS_MESSAGE_COMPRESS_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/compression_types.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-
-/** Compression filter for outgoing data.
- *
- * See <grpc/compression.h> for the available compression settings.
- *
- * Compression settings may come from:
- * - Channel configuration, as established at channel creation time.
- * - The metadata accompanying the outgoing data to be compressed. This is
- * taken as a request only. We may choose not to honor it. The metadata key
- * is given by \a GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY.
- *
- * Compression can be disabled for concrete messages (for instance in order to
- * prevent CRIME/BEAST type attacks) by having the GRPC_WRITE_NO_COMPRESS set in
- * the BEGIN_MESSAGE flags.
- *
- * The attempted compression mechanism is added to the resulting initial
- * metadata under the'grpc-encoding' key.
- *
- * If compression is actually performed, BEGIN_MESSAGE's flag is modified to
- * incorporate GRPC_WRITE_INTERNAL_COMPRESS. Otherwise, and regardless of the
- * aforementioned 'grpc-encoding' metadata value, data will pass through
- * uncompressed. */
-
-extern const grpc_channel_filter grpc_message_compress_filter;
-
-#endif /* GRPC_CORE_EXT_FILTERS_HTTP_MESSAGE_COMPRESS_MESSAGE_COMPRESS_FILTER_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_EXT_FILTERS_HTTP_MESSAGE_COMPRESS_MESSAGE_COMPRESS_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_HTTP_MESSAGE_COMPRESS_MESSAGE_COMPRESS_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/impl/codegen/compression_types.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+
+/** Compression filter for outgoing data.
+ *
+ * See <grpc/compression.h> for the available compression settings.
+ *
+ * Compression settings may come from:
+ * - Channel configuration, as established at channel creation time.
+ * - The metadata accompanying the outgoing data to be compressed. This is
+ * taken as a request only. We may choose not to honor it. The metadata key
+ * is given by \a GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY.
+ *
+ * Compression can be disabled for concrete messages (for instance in order to
+ * prevent CRIME/BEAST type attacks) by having the GRPC_WRITE_NO_COMPRESS set in
+ * the BEGIN_MESSAGE flags.
+ *
+ * The attempted compression mechanism is added to the resulting initial
+ * metadata under the'grpc-encoding' key.
+ *
+ * If compression is actually performed, BEGIN_MESSAGE's flag is modified to
+ * incorporate GRPC_WRITE_INTERNAL_COMPRESS. Otherwise, and regardless of the
+ * aforementioned 'grpc-encoding' metadata value, data will pass through
+ * uncompressed. */
+
+extern const grpc_channel_filter grpc_message_compress_filter;
+
+#endif /* GRPC_CORE_EXT_FILTERS_HTTP_MESSAGE_COMPRESS_MESSAGE_COMPRESS_FILTER_H \
+ */
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 62dc76fb6cc..e8bd86e8b57 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/http/server/http_server_filter.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.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/http/server/http_server_filter.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <string.h>
#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/slice/b64.h"
-#include "src/core/lib/slice/percent_encoding.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-#define EXPECTED_CONTENT_TYPE "application/grpc"
-#define EXPECTED_CONTENT_TYPE_LENGTH sizeof(EXPECTED_CONTENT_TYPE) - 1
-
+#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/slice/b64.h"
+#include "src/core/lib/slice/percent_encoding.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+#define EXPECTED_CONTENT_TYPE "application/grpc"
+#define EXPECTED_CONTENT_TYPE_LENGTH sizeof(EXPECTED_CONTENT_TYPE) - 1
+
static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err);
static void hs_recv_trailing_metadata_ready(void* user_data, grpc_error* err);
static void hs_recv_message_ready(void* user_data, grpc_error* err);
-namespace {
+namespace {
-struct call_data {
+struct call_data {
call_data(grpc_call_element* elem, const grpc_call_element_args& args)
: call_combiner(args.call_combiner) {
GRPC_CLOSURE_INIT(&recv_initial_metadata_ready,
@@ -62,24 +62,24 @@ struct call_data {
}
grpc_core::CallCombiner* call_combiner;
-
+
// Outgoing headers to add to send_initial_metadata.
- grpc_linked_mdelem status;
- grpc_linked_mdelem content_type;
-
+ grpc_linked_mdelem status;
+ grpc_linked_mdelem content_type;
+
// If we see the recv_message contents in the GET query string, we
// store it here.
grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> read_stream;
bool have_read_stream = false;
-
+
// State for intercepting recv_initial_metadata.
grpc_closure recv_initial_metadata_ready;
grpc_error* recv_initial_metadata_ready_error = GRPC_ERROR_NONE;
grpc_closure* original_recv_initial_metadata_ready;
grpc_metadata_batch* recv_initial_metadata = nullptr;
- uint32_t* recv_initial_metadata_flags;
+ uint32_t* recv_initial_metadata_flags;
bool seen_recv_initial_metadata_ready = false;
-
+
// State for intercepting recv_message.
grpc_closure* original_recv_message_ready;
grpc_closure recv_message_ready;
@@ -91,38 +91,38 @@ struct call_data {
grpc_closure* original_recv_trailing_metadata_ready;
grpc_error* recv_trailing_metadata_ready_error;
bool seen_recv_trailing_metadata_ready = false;
-};
-
-struct channel_data {
+};
+
+struct channel_data {
bool surface_user_agent;
-};
-
-} // namespace
+};
+} // namespace
+
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),
- grpc_compatible_percent_encoding_unreserved_bytes);
- if (grpc_slice_is_equivalent(pct_encoded_msg,
- GRPC_MDVALUE(b->idx.named.grpc_message->md))) {
- grpc_slice_unref_internal(pct_encoded_msg);
- } else {
- grpc_metadata_batch_set_value(b->idx.named.grpc_message, pct_encoded_msg);
- }
- }
- return GRPC_ERROR_NONE;
-}
-
+ if (b->idx.named.grpc_message != nullptr) {
+ grpc_slice pct_encoded_msg = grpc_percent_encode_slice(
+ GRPC_MDVALUE(b->idx.named.grpc_message->md),
+ grpc_compatible_percent_encoding_unreserved_bytes);
+ if (grpc_slice_is_equivalent(pct_encoded_msg,
+ GRPC_MDVALUE(b->idx.named.grpc_message->md))) {
+ grpc_slice_unref_internal(pct_encoded_msg);
+ } else {
+ grpc_metadata_batch_set_value(b->idx.named.grpc_message, pct_encoded_msg);
+ }
+ }
+ return GRPC_ERROR_NONE;
+}
+
static void hs_add_error(const char* error_name, grpc_error** cumulative,
grpc_error* new_err) {
- if (new_err == GRPC_ERROR_NONE) return;
- if (*cumulative == GRPC_ERROR_NONE) {
- *cumulative = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_name);
- }
- *cumulative = grpc_error_add_child(*cumulative, new_err);
-}
-
+ if (new_err == GRPC_ERROR_NONE) return;
+ if (*cumulative == GRPC_ERROR_NONE) {
+ *cumulative = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_name);
+ }
+ *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
@@ -151,59 +151,59 @@ static bool md_strict_equal(grpc_mdelem a, grpc_mdelem 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);
- grpc_error* error = GRPC_ERROR_NONE;
- static const char* error_name = "Failed processing incoming headers";
-
- if (b->idx.named.method != nullptr) {
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_error* error = GRPC_ERROR_NONE;
+ 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)) {
- *calld->recv_initial_metadata_flags &=
- ~(GRPC_INITIAL_METADATA_CACHEABLE_REQUEST |
- GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST);
+ *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)) {
- *calld->recv_initial_metadata_flags &=
- ~GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
- *calld->recv_initial_metadata_flags |=
- GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
+ *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)) {
- *calld->recv_initial_metadata_flags |=
- GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
- *calld->recv_initial_metadata_flags &=
- ~GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
- } else {
+ *calld->recv_initial_metadata_flags |=
+ GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
+ *calld->recv_initial_metadata_flags &=
+ ~GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
+ } else {
hs_add_error(error_name, &error,
grpc_attach_md_to_error(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"),
b->idx.named.method->md));
- }
+ }
grpc_metadata_batch_remove(b, GRPC_BATCH_METHOD);
- } else {
+ } else {
hs_add_error(
- error_name, &error,
- grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
- GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":method")));
- }
-
- if (b->idx.named.te != nullptr) {
+ error_name, &error,
+ grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
+ GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":method")));
+ }
+
+ if (b->idx.named.te != nullptr) {
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);
- } else {
+ } else {
hs_add_error(error_name, &error,
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
GRPC_ERROR_STR_KEY, grpc_slice_from_static_string("te")));
- }
-
- if (b->idx.named.scheme != nullptr) {
+ }
+
+ 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,
@@ -212,98 +212,98 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
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);
- } else {
+ } else {
hs_add_error(
- error_name, &error,
- grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
- GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":scheme")));
- }
-
- if (b->idx.named.content_type != nullptr) {
+ error_name, &error,
+ grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
+ GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":scheme")));
+ }
+
+ 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_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md),
- EXPECTED_CONTENT_TYPE,
- EXPECTED_CONTENT_TYPE_LENGTH) &&
- (GRPC_SLICE_START_PTR(GRPC_MDVALUE(
- b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
- '+' ||
- GRPC_SLICE_START_PTR(GRPC_MDVALUE(
- b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
- ';')) {
- /* Although the C implementation doesn't (currently) generate them,
- any custom +-suffix is explicitly valid. */
- /* TODO(klempner): We should consider preallocating common values such
- as +proto or +json, or at least stashing them if we see them. */
- /* TODO(klempner): Should we be surfacing this to application code? */
- } else {
- /* TODO(klempner): We're currently allowing this, but we shouldn't
- see it without a proxy so log for now. */
- char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md),
- GPR_DUMP_ASCII);
- gpr_log(GPR_INFO, "Unexpected content-type '%s'", val);
- gpr_free(val);
- }
- }
+ if (grpc_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md),
+ EXPECTED_CONTENT_TYPE,
+ EXPECTED_CONTENT_TYPE_LENGTH) &&
+ (GRPC_SLICE_START_PTR(GRPC_MDVALUE(
+ b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
+ '+' ||
+ GRPC_SLICE_START_PTR(GRPC_MDVALUE(
+ b->idx.named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
+ ';')) {
+ /* Although the C implementation doesn't (currently) generate them,
+ any custom +-suffix is explicitly valid. */
+ /* TODO(klempner): We should consider preallocating common values such
+ as +proto or +json, or at least stashing them if we see them. */
+ /* TODO(klempner): Should we be surfacing this to application code? */
+ } else {
+ /* TODO(klempner): We're currently allowing this, but we shouldn't
+ see it without a proxy so log for now. */
+ char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md),
+ GPR_DUMP_ASCII);
+ gpr_log(GPR_INFO, "Unexpected content-type '%s'", val);
+ gpr_free(val);
+ }
+ }
grpc_metadata_batch_remove(b, GRPC_BATCH_CONTENT_TYPE);
- }
-
- if (b->idx.named.path == nullptr) {
+ }
+
+ if (b->idx.named.path == nullptr) {
hs_add_error(
error_name, &error,
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":path")));
- } else if (*calld->recv_initial_metadata_flags &
- GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) {
- /* We have a cacheable request made with GET verb. The path contains the
- * query parameter which is base64 encoded request payload. */
- const char k_query_separator = '?';
- grpc_slice path_slice = GRPC_MDVALUE(b->idx.named.path->md);
- uint8_t* path_ptr = GRPC_SLICE_START_PTR(path_slice);
- size_t path_length = GRPC_SLICE_LENGTH(path_slice);
- /* offset of the character '?' */
- size_t offset = 0;
- for (offset = 0; offset < path_length && *path_ptr != k_query_separator;
- path_ptr++, offset++)
- ;
- if (offset < path_length) {
- grpc_slice query_slice =
- grpc_slice_sub(path_slice, offset + 1, path_length);
-
- /* substitute path metadata with just the path (not query) */
- grpc_mdelem mdelem_path_without_query = grpc_mdelem_from_slices(
- GRPC_MDSTR_PATH, grpc_slice_sub(path_slice, 0, offset));
-
- grpc_metadata_batch_substitute(b, b->idx.named.path,
- mdelem_path_without_query);
-
- /* decode payload from query and add to the slice buffer to be returned */
- const int k_url_safe = 1;
- grpc_slice_buffer read_slice_buffer;
- grpc_slice_buffer_init(&read_slice_buffer);
- grpc_slice_buffer_add(
- &read_slice_buffer,
- grpc_base64_decode_with_len(
- reinterpret_cast<const char*> GRPC_SLICE_START_PTR(query_slice),
- GRPC_SLICE_LENGTH(query_slice), k_url_safe));
- calld->read_stream.Init(&read_slice_buffer, 0);
- grpc_slice_buffer_destroy_internal(&read_slice_buffer);
+ } else if (*calld->recv_initial_metadata_flags &
+ GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) {
+ /* We have a cacheable request made with GET verb. The path contains the
+ * query parameter which is base64 encoded request payload. */
+ const char k_query_separator = '?';
+ grpc_slice path_slice = GRPC_MDVALUE(b->idx.named.path->md);
+ uint8_t* path_ptr = GRPC_SLICE_START_PTR(path_slice);
+ size_t path_length = GRPC_SLICE_LENGTH(path_slice);
+ /* offset of the character '?' */
+ size_t offset = 0;
+ for (offset = 0; offset < path_length && *path_ptr != k_query_separator;
+ path_ptr++, offset++)
+ ;
+ if (offset < path_length) {
+ grpc_slice query_slice =
+ grpc_slice_sub(path_slice, offset + 1, path_length);
+
+ /* substitute path metadata with just the path (not query) */
+ grpc_mdelem mdelem_path_without_query = grpc_mdelem_from_slices(
+ GRPC_MDSTR_PATH, grpc_slice_sub(path_slice, 0, offset));
+
+ grpc_metadata_batch_substitute(b, b->idx.named.path,
+ mdelem_path_without_query);
+
+ /* decode payload from query and add to the slice buffer to be returned */
+ const int k_url_safe = 1;
+ grpc_slice_buffer read_slice_buffer;
+ grpc_slice_buffer_init(&read_slice_buffer);
+ grpc_slice_buffer_add(
+ &read_slice_buffer,
+ grpc_base64_decode_with_len(
+ reinterpret_cast<const char*> GRPC_SLICE_START_PTR(query_slice),
+ GRPC_SLICE_LENGTH(query_slice), k_url_safe));
+ calld->read_stream.Init(&read_slice_buffer, 0);
+ grpc_slice_buffer_destroy_internal(&read_slice_buffer);
calld->have_read_stream = true;
- grpc_slice_unref_internal(query_slice);
- } else {
- gpr_log(GPR_ERROR, "GET request without QUERY");
- }
- }
-
- if (b->idx.named.host != nullptr && b->idx.named.authority == nullptr) {
- grpc_linked_mdelem* el = b->idx.named.host;
- grpc_mdelem md = GRPC_MDELEM_REF(el->md);
- grpc_metadata_batch_remove(b, el);
+ grpc_slice_unref_internal(query_slice);
+ } else {
+ gpr_log(GPR_ERROR, "GET request without QUERY");
+ }
+ }
+
+ if (b->idx.named.host != nullptr && b->idx.named.authority == nullptr) {
+ 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(
@@ -311,30 +311,30 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem,
grpc_mdelem_from_slices(GRPC_MDSTR_AUTHORITY,
grpc_slice_ref_internal(GRPC_MDVALUE(md))),
GRPC_BATCH_AUTHORITY));
- GRPC_MDELEM_UNREF(md);
- }
-
- if (b->idx.named.authority == nullptr) {
+ GRPC_MDELEM_UNREF(md);
+ }
+
+ if (b->idx.named.authority == nullptr) {
hs_add_error(
- error_name, &error,
- grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
- GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":authority")));
- }
-
+ error_name, &error,
+ grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
+ GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":authority")));
+ }
+
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);
}
- return error;
-}
-
+ return error;
+}
+
static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
- call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
calld->seen_recv_initial_metadata_ready = true;
- if (err == GRPC_ERROR_NONE) {
+ if (err == GRPC_ERROR_NONE) {
err = hs_filter_incoming_metadata(elem, calld->recv_initial_metadata);
calld->recv_initial_metadata_ready_error = GRPC_ERROR_REF(err);
if (calld->seen_recv_message_ready) {
@@ -353,9 +353,9 @@ static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err) {
GRPC_ERROR_REF(err),
"resuming recv_message_ready from recv_initial_metadata_ready");
}
- } else {
- GRPC_ERROR_REF(err);
- }
+ } else {
+ GRPC_ERROR_REF(err);
+ }
if (calld->seen_recv_trailing_metadata_ready) {
GRPC_CALL_COMBINER_START(calld->call_combiner,
&calld->recv_trailing_metadata_ready,
@@ -365,11 +365,11 @@ static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* 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) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
- call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
calld->seen_recv_message_ready = true;
if (calld->seen_recv_initial_metadata_ready) {
// We've already seen the recv_initial_metadata callback, so
@@ -389,35 +389,35 @@ static void hs_recv_message_ready(void* user_data, grpc_error* err) {
GRPC_CALL_COMBINER_STOP(
calld->call_combiner,
"pausing recv_message_ready until recv_initial_metadata_ready");
- }
-}
-
+ }
+}
+
static void hs_recv_trailing_metadata_ready(void* user_data, grpc_error* err) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
- call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
if (!calld->seen_recv_initial_metadata_ready) {
calld->recv_trailing_metadata_ready_error = GRPC_ERROR_REF(err);
calld->seen_recv_trailing_metadata_ready = true;
- GRPC_CALL_COMBINER_STOP(calld->call_combiner,
+ GRPC_CALL_COMBINER_STOP(calld->call_combiner,
"deferring hs_recv_trailing_metadata_ready until "
"ater hs_recv_initial_metadata_ready");
return;
- }
+ }
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);
-}
-
-static grpc_error* hs_mutate_op(grpc_call_element* elem,
- grpc_transport_stream_op_batch* op) {
- /* grab pointers to our data from the call element */
- call_data* calld = static_cast<call_data*>(elem->call_data);
-
- if (op->send_initial_metadata) {
- grpc_error* error = GRPC_ERROR_NONE;
- static const char* error_name = "Failed sending initial metadata";
+}
+
+static grpc_error* hs_mutate_op(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* op) {
+ /* grab pointers to our data from the call element */
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+
+ 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(
@@ -432,29 +432,29 @@ static grpc_error* hs_mutate_op(grpc_call_element* elem,
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;
- }
-
- if (op->recv_initial_metadata) {
- /* substitute our callback for the higher callback */
- GPR_ASSERT(op->payload->recv_initial_metadata.recv_flags != nullptr);
- calld->recv_initial_metadata =
- op->payload->recv_initial_metadata.recv_initial_metadata;
- calld->recv_initial_metadata_flags =
- op->payload->recv_initial_metadata.recv_flags;
+ if (error != GRPC_ERROR_NONE) return error;
+ }
+
+ if (op->recv_initial_metadata) {
+ /* substitute our callback for the higher callback */
+ GPR_ASSERT(op->payload->recv_initial_metadata.recv_flags != nullptr);
+ calld->recv_initial_metadata =
+ op->payload->recv_initial_metadata.recv_initial_metadata;
+ calld->recv_initial_metadata_flags =
+ op->payload->recv_initial_metadata.recv_flags;
calld->original_recv_initial_metadata_ready =
- op->payload->recv_initial_metadata.recv_initial_metadata_ready;
- op->payload->recv_initial_metadata.recv_initial_metadata_ready =
+ op->payload->recv_initial_metadata.recv_initial_metadata_ready;
+ op->payload->recv_initial_metadata.recv_initial_metadata_ready =
&calld->recv_initial_metadata_ready;
- }
-
- if (op->recv_message) {
+ }
+
+ if (op->recv_message) {
calld->recv_message = op->payload->recv_message.recv_message;
calld->original_recv_message_ready =
op->payload->recv_message.recv_message_ready;
op->payload->recv_message.recv_message_ready = &calld->recv_message_ready;
- }
-
+ }
+
if (op->recv_trailing_metadata) {
calld->original_recv_trailing_metadata_ready =
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready;
@@ -462,67 +462,67 @@ static grpc_error* hs_mutate_op(grpc_call_element* elem,
&calld->recv_trailing_metadata_ready;
}
- if (op->send_trailing_metadata) {
+ if (op->send_trailing_metadata) {
grpc_error* error = hs_filter_outgoing_metadata(
op->payload->send_trailing_metadata.send_trailing_metadata);
- if (error != GRPC_ERROR_NONE) return error;
- }
-
- return GRPC_ERROR_NONE;
-}
-
-static void hs_start_transport_stream_op_batch(
- grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
- GPR_TIMER_SCOPE("hs_start_transport_stream_op_batch", 0);
- call_data* calld = static_cast<call_data*>(elem->call_data);
- grpc_error* error = hs_mutate_op(elem, op);
- if (error != GRPC_ERROR_NONE) {
- grpc_transport_stream_op_batch_finish_with_failure(op, error,
- calld->call_combiner);
- } else {
- grpc_call_next_op(elem, op);
- }
-}
-
-/* Constructor for call_data */
+ if (error != GRPC_ERROR_NONE) return error;
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+static void hs_start_transport_stream_op_batch(
+ grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
+ GPR_TIMER_SCOPE("hs_start_transport_stream_op_batch", 0);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_error* error = hs_mutate_op(elem, op);
+ if (error != GRPC_ERROR_NONE) {
+ grpc_transport_stream_op_batch_finish_with_failure(op, error,
+ calld->call_combiner);
+ } else {
+ grpc_call_next_op(elem, op);
+ }
+}
+
+/* Constructor for call_data */
static grpc_error* hs_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 */
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for call_data */
static void hs_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);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
calld->~call_data();
-}
-
-/* Constructor for channel_data */
+}
+
+/* Constructor for channel_data */
static grpc_error* hs_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->is_last);
chand->surface_user_agent = grpc_channel_arg_get_bool(
grpc_channel_args_find(args->channel_args,
const_cast<char*>(GRPC_ARG_SURFACE_USER_AGENT)),
true);
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel data */
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for channel data */
static void hs_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
-
-const grpc_channel_filter grpc_http_server_filter = {
- hs_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(call_data),
+
+const grpc_channel_filter grpc_http_server_filter = {
+ hs_start_transport_stream_op_batch,
+ grpc_channel_next_op,
+ sizeof(call_data),
hs_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
hs_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
hs_init_channel_elem,
hs_destroy_channel_elem,
- grpc_channel_next_get_info,
- "http-server"};
+ grpc_channel_next_get_info,
+ "http-server"};
diff --git a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h
index e4e0546f6db..cce62c3022e 100644
--- a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h
@@ -1,29 +1,29 @@
-/*
- *
- * 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_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.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_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+
/* Processes metadata on the server side for HTTP2 transports */
-extern const grpc_channel_filter grpc_http_server_filter;
-
-#endif /* GRPC_CORE_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H */
+extern const grpc_channel_filter grpc_http_server_filter;
+
+#endif /* GRPC_CORE_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H */
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 c57efd6d1ca..ad3635de098 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
@@ -1,221 +1,221 @@
-/*
- *
- * 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/ext/filters/max_age/max_age_filter.h"
-
-#include <limits.h>
-#include <string.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/channel_stack_builder.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/transport/http2_errors.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/max_age/max_age_filter.h"
+
+#include <limits.h>
+#include <string.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/channel_stack_builder.h"
+#include "src/core/lib/iomgr/timer.h"
+#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.
*/
-#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
-#define MAX_CONNECTION_AGE_JITTER 0.1
-
-#define MAX_CONNECTION_AGE_INTEGER_OPTIONS \
- { DEFAULT_MAX_CONNECTION_AGE_MS, 1, INT_MAX }
-#define MAX_CONNECTION_IDLE_INTEGER_OPTIONS \
- { DEFAULT_MAX_CONNECTION_IDLE_MS, 1, INT_MAX }
-
-/* States for idle_state in channel_data */
-#define MAX_IDLE_STATE_INIT ((gpr_atm)0)
-#define MAX_IDLE_STATE_SEEN_EXIT_IDLE ((gpr_atm)1)
-#define MAX_IDLE_STATE_SEEN_ENTER_IDLE ((gpr_atm)2)
-#define MAX_IDLE_STATE_TIMER_SET ((gpr_atm)3)
-
-namespace {
-struct channel_data {
+#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
+#define MAX_CONNECTION_AGE_JITTER 0.1
+
+#define MAX_CONNECTION_AGE_INTEGER_OPTIONS \
+ { DEFAULT_MAX_CONNECTION_AGE_MS, 1, INT_MAX }
+#define MAX_CONNECTION_IDLE_INTEGER_OPTIONS \
+ { DEFAULT_MAX_CONNECTION_IDLE_MS, 1, INT_MAX }
+
+/* States for idle_state in channel_data */
+#define MAX_IDLE_STATE_INIT ((gpr_atm)0)
+#define MAX_IDLE_STATE_SEEN_EXIT_IDLE ((gpr_atm)1)
+#define MAX_IDLE_STATE_SEEN_ENTER_IDLE ((gpr_atm)2)
+#define MAX_IDLE_STATE_TIMER_SET ((gpr_atm)3)
+
+namespace {
+struct channel_data {
/* 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 */
- gpr_mu max_age_timer_mu;
- /* True if the max_age timer callback is currently pending */
- bool max_age_timer_pending;
- /* True if the max_age_grace timer callback is currently pending */
- bool max_age_grace_timer_pending;
- /* The timer for checking if the channel has reached its max age */
- grpc_timer max_age_timer;
- /* The timer for checking if the max-aged channel has uesed up the grace
- period */
- grpc_timer max_age_grace_timer;
- /* The timer for checking if the channel's idle duration reaches
- max_connection_idle */
- grpc_timer max_idle_timer;
- /* Allowed max time a channel may have no outstanding rpcs */
- grpc_millis max_connection_idle;
- /* Allowed max time a channel may exist */
- grpc_millis max_connection_age;
- /* Allowed grace period after the channel reaches its max age */
- grpc_millis max_connection_age_grace;
- /* Closure to run when the channel's idle duration reaches max_connection_idle
- and should be closed gracefully */
- grpc_closure max_idle_timer_cb;
- /* Closure to run when the channel reaches its max age and should be closed
- gracefully */
- grpc_closure close_max_age_channel;
- /* Closure to run the channel uses up its max age grace time and should be
- closed forcibly */
- grpc_closure force_close_max_age_channel;
- /* Closure to run when the init fo channel stack is done and the max_idle
- timer should be started */
- grpc_closure start_max_idle_timer_after_init;
- /* Closure to run when the init fo channel stack is done and the max_age timer
- should be started */
- grpc_closure start_max_age_timer_after_init;
- /* Closure to run when the goaway op is finished and the max_age_timer */
- grpc_closure start_max_age_grace_timer_after_goaway_op;
- /* Number of active calls */
- gpr_atm call_count;
- /* TODO(zyc): C++lize this state machine */
- /* 'idle_state' holds the states of max_idle_timer and channel idleness.
- It can contain one of the following values:
- +--------------------------------+----------------+---------+
- | idle_state | max_idle_timer | channel |
- +--------------------------------+----------------+---------+
- | MAX_IDLE_STATE_INIT | unset | busy |
- | MAX_IDLE_STATE_TIMER_SET | set, valid | idle |
- | MAX_IDLE_STATE_SEEN_EXIT_IDLE | set, invalid | busy |
- | MAX_IDLE_STATE_SEEN_ENTER_IDLE | set, invalid | idle |
- +--------------------------------+----------------+---------+
-
- MAX_IDLE_STATE_INIT: The initial and final state of 'idle_state'. The
+ 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 */
+ gpr_mu max_age_timer_mu;
+ /* True if the max_age timer callback is currently pending */
+ bool max_age_timer_pending;
+ /* True if the max_age_grace timer callback is currently pending */
+ bool max_age_grace_timer_pending;
+ /* The timer for checking if the channel has reached its max age */
+ grpc_timer max_age_timer;
+ /* The timer for checking if the max-aged channel has uesed up the grace
+ period */
+ grpc_timer max_age_grace_timer;
+ /* The timer for checking if the channel's idle duration reaches
+ max_connection_idle */
+ grpc_timer max_idle_timer;
+ /* Allowed max time a channel may have no outstanding rpcs */
+ grpc_millis max_connection_idle;
+ /* Allowed max time a channel may exist */
+ grpc_millis max_connection_age;
+ /* Allowed grace period after the channel reaches its max age */
+ grpc_millis max_connection_age_grace;
+ /* Closure to run when the channel's idle duration reaches max_connection_idle
+ and should be closed gracefully */
+ grpc_closure max_idle_timer_cb;
+ /* Closure to run when the channel reaches its max age and should be closed
+ gracefully */
+ grpc_closure close_max_age_channel;
+ /* Closure to run the channel uses up its max age grace time and should be
+ closed forcibly */
+ grpc_closure force_close_max_age_channel;
+ /* Closure to run when the init fo channel stack is done and the max_idle
+ timer should be started */
+ grpc_closure start_max_idle_timer_after_init;
+ /* Closure to run when the init fo channel stack is done and the max_age timer
+ should be started */
+ grpc_closure start_max_age_timer_after_init;
+ /* Closure to run when the goaway op is finished and the max_age_timer */
+ grpc_closure start_max_age_grace_timer_after_goaway_op;
+ /* Number of active calls */
+ gpr_atm call_count;
+ /* TODO(zyc): C++lize this state machine */
+ /* 'idle_state' holds the states of max_idle_timer and channel idleness.
+ It can contain one of the following values:
+ +--------------------------------+----------------+---------+
+ | idle_state | max_idle_timer | channel |
+ +--------------------------------+----------------+---------+
+ | MAX_IDLE_STATE_INIT | unset | busy |
+ | MAX_IDLE_STATE_TIMER_SET | set, valid | idle |
+ | MAX_IDLE_STATE_SEEN_EXIT_IDLE | set, invalid | busy |
+ | MAX_IDLE_STATE_SEEN_ENTER_IDLE | set, invalid | idle |
+ +--------------------------------+----------------+---------+
+
+ MAX_IDLE_STATE_INIT: The initial and final state of 'idle_state'. The
channel has 1 or 1+ active calls, and the timer is not set. Note that
- we may put a virtual call to hold this state at channel initialization or
- shutdown, so that the channel won't enter other states.
-
- MAX_IDLE_STATE_TIMER_SET: 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, we will close the channel
- due to idleness.
-
- MAX_IDLE_STATE_SEEN_EXIT_IDLE: 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 reschudle it.
-
- 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
+ we may put a virtual call to hold this state at channel initialization or
+ shutdown, so that the channel won't enter other states.
+
+ MAX_IDLE_STATE_TIMER_SET: 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, we will close the channel
+ due to idleness.
+
+ MAX_IDLE_STATE_SEEN_EXIT_IDLE: 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 reschudle it.
+
+ 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.
-
- 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.
- idle_state is MAX_IDLE_STATE_TIMER_SET), the channel will be closed due to
- idleness, otherwise the channel won't be changed.
-
- State transitions:
- MAX_IDLE_STATE_INIT <-------3------ MAX_IDLE_STATE_SEEN_EXIT_IDLE
- ^ | ^ ^ |
- | | | | |
- 1 2 +-----------4------------+ 6 7
- | | | | |
- | v | | v
- MAX_IDLE_STATE_TIMER_SET <----5------ MAX_IDLE_STATE_SEEN_ENTER_IDLE
-
- For 1, 3, 5 : See max_idle_timer_cb() function
- For 2, 7 : See decrease_call_count() function
- For 4, 6 : See increase_call_count() function */
- gpr_atm idle_state;
- /* Time when the channel finished its last outstanding call, in grpc_millis */
- gpr_atm last_enter_idle_time_millis;
-};
-} // namespace
-
-/* Increase the nubmer of active calls. Before the increasement, if there are no
- calls, the max_idle_timer should be cancelled. */
-static void increase_call_count(channel_data* chand) {
- /* Exit idle */
- if (gpr_atm_full_fetch_add(&chand->call_count, 1) == 0) {
- while (true) {
- gpr_atm idle_state = gpr_atm_acq_load(&chand->idle_state);
- switch (idle_state) {
- case MAX_IDLE_STATE_TIMER_SET:
- /* max_idle_timer_cb may have already set idle_state to
- MAX_IDLE_STATE_INIT, in this case, we don't need to set it to
- MAX_IDLE_STATE_SEEN_EXIT_IDLE */
- gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_TIMER_SET,
- MAX_IDLE_STATE_SEEN_EXIT_IDLE);
- return;
- case MAX_IDLE_STATE_SEEN_ENTER_IDLE:
- gpr_atm_rel_store(&chand->idle_state, MAX_IDLE_STATE_SEEN_EXIT_IDLE);
- return;
- default:
- /* try again */
- break;
- }
- }
- }
-}
-
-/* Decrease the nubmer of active calls. After the decrement, if there are no
- calls, the max_idle_timer should be started. */
-static void decrease_call_count(channel_data* chand) {
- /* Enter idle */
- if (gpr_atm_full_fetch_add(&chand->call_count, -1) == 1) {
- gpr_atm_no_barrier_store(&chand->last_enter_idle_time_millis,
- (gpr_atm)grpc_core::ExecCtx::Get()->Now());
- while (true) {
- gpr_atm idle_state = gpr_atm_acq_load(&chand->idle_state);
- switch (idle_state) {
- case MAX_IDLE_STATE_INIT:
- GRPC_CHANNEL_STACK_REF(chand->channel_stack,
- "max_age max_idle_timer");
- grpc_timer_init(
- &chand->max_idle_timer,
- grpc_core::ExecCtx::Get()->Now() + chand->max_connection_idle,
- &chand->max_idle_timer_cb);
- gpr_atm_rel_store(&chand->idle_state, MAX_IDLE_STATE_TIMER_SET);
- return;
- case MAX_IDLE_STATE_SEEN_EXIT_IDLE:
- if (gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_SEEN_EXIT_IDLE,
- MAX_IDLE_STATE_SEEN_ENTER_IDLE)) {
- return;
- }
- break;
- default:
- /* try again */
- break;
- }
- }
- }
-}
-
+
+ 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.
+ idle_state is MAX_IDLE_STATE_TIMER_SET), the channel will be closed due to
+ idleness, otherwise the channel won't be changed.
+
+ State transitions:
+ MAX_IDLE_STATE_INIT <-------3------ MAX_IDLE_STATE_SEEN_EXIT_IDLE
+ ^ | ^ ^ |
+ | | | | |
+ 1 2 +-----------4------------+ 6 7
+ | | | | |
+ | v | | v
+ MAX_IDLE_STATE_TIMER_SET <----5------ MAX_IDLE_STATE_SEEN_ENTER_IDLE
+
+ For 1, 3, 5 : See max_idle_timer_cb() function
+ For 2, 7 : See decrease_call_count() function
+ For 4, 6 : See increase_call_count() function */
+ gpr_atm idle_state;
+ /* Time when the channel finished its last outstanding call, in grpc_millis */
+ gpr_atm last_enter_idle_time_millis;
+};
+} // namespace
+
+/* Increase the nubmer of active calls. Before the increasement, if there are no
+ calls, the max_idle_timer should be cancelled. */
+static void increase_call_count(channel_data* chand) {
+ /* Exit idle */
+ if (gpr_atm_full_fetch_add(&chand->call_count, 1) == 0) {
+ while (true) {
+ gpr_atm idle_state = gpr_atm_acq_load(&chand->idle_state);
+ switch (idle_state) {
+ case MAX_IDLE_STATE_TIMER_SET:
+ /* max_idle_timer_cb may have already set idle_state to
+ MAX_IDLE_STATE_INIT, in this case, we don't need to set it to
+ MAX_IDLE_STATE_SEEN_EXIT_IDLE */
+ gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_TIMER_SET,
+ MAX_IDLE_STATE_SEEN_EXIT_IDLE);
+ return;
+ case MAX_IDLE_STATE_SEEN_ENTER_IDLE:
+ gpr_atm_rel_store(&chand->idle_state, MAX_IDLE_STATE_SEEN_EXIT_IDLE);
+ return;
+ default:
+ /* try again */
+ break;
+ }
+ }
+ }
+}
+
+/* Decrease the nubmer of active calls. After the decrement, if there are no
+ calls, the max_idle_timer should be started. */
+static void decrease_call_count(channel_data* chand) {
+ /* Enter idle */
+ if (gpr_atm_full_fetch_add(&chand->call_count, -1) == 1) {
+ gpr_atm_no_barrier_store(&chand->last_enter_idle_time_millis,
+ (gpr_atm)grpc_core::ExecCtx::Get()->Now());
+ while (true) {
+ gpr_atm idle_state = gpr_atm_acq_load(&chand->idle_state);
+ switch (idle_state) {
+ case MAX_IDLE_STATE_INIT:
+ GRPC_CHANNEL_STACK_REF(chand->channel_stack,
+ "max_age max_idle_timer");
+ grpc_timer_init(
+ &chand->max_idle_timer,
+ grpc_core::ExecCtx::Get()->Now() + chand->max_connection_idle,
+ &chand->max_idle_timer_cb);
+ gpr_atm_rel_store(&chand->idle_state, MAX_IDLE_STATE_TIMER_SET);
+ return;
+ case MAX_IDLE_STATE_SEEN_EXIT_IDLE:
+ if (gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_SEEN_EXIT_IDLE,
+ MAX_IDLE_STATE_SEEN_ENTER_IDLE)) {
+ return;
+ }
+ break;
+ default:
+ /* try again */
+ break;
+ }
+ }
+ }
+}
+
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,
- max_idle_timer will start after all the active calls end. */
- decrease_call_count(chand);
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack,
- "max_age start_max_idle_timer_after_init");
-}
-
+ 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,
+ max_idle_timer will start after all the active calls end. */
+ decrease_call_count(chand);
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack,
+ "max_age start_max_idle_timer_after_init");
+}
+
namespace grpc_core {
class ConnectivityWatcher : public AsyncConnectivityStateWatcherInterface {
@@ -259,299 +259,299 @@ class ConnectivityWatcher : public AsyncConnectivityStateWatcherInterface {
} // 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;
- GRPC_CHANNEL_STACK_REF(chand->channel_stack, "max_age max_age_timer");
- grpc_timer_init(&chand->max_age_timer,
- grpc_core::ExecCtx::Get()->Now() + chand->max_connection_age,
- &chand->close_max_age_channel);
- gpr_mu_unlock(&chand->max_age_timer_mu);
- grpc_transport_op* op = grpc_make_transport_op(nullptr);
+ channel_data* chand = static_cast<channel_data*>(arg);
+ gpr_mu_lock(&chand->max_age_timer_mu);
+ chand->max_age_timer_pending = true;
+ GRPC_CHANNEL_STACK_REF(chand->channel_stack, "max_age max_age_timer");
+ grpc_timer_init(&chand->max_age_timer,
+ grpc_core::ExecCtx::Get()->Now() + chand->max_connection_age,
+ &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;
- 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_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*/) {
- channel_data* chand = static_cast<channel_data*>(arg);
- gpr_mu_lock(&chand->max_age_timer_mu);
- chand->max_age_grace_timer_pending = true;
- GRPC_CHANNEL_STACK_REF(chand->channel_stack, "max_age max_age_grace_timer");
- grpc_timer_init(
- &chand->max_age_grace_timer,
- chand->max_connection_age_grace == GRPC_MILLIS_INF_FUTURE
- ? GRPC_MILLIS_INF_FUTURE
- : grpc_core::ExecCtx::Get()->Now() + chand->max_connection_age_grace,
- &chand->force_close_max_age_channel);
- gpr_mu_unlock(&chand->max_age_timer_mu);
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack,
- "max_age start_max_age_grace_timer_after_goaway_op");
-}
-
-static void close_max_idle_channel(channel_data* chand) {
- /* Prevent the max idle timer from being set again */
- gpr_atm_no_barrier_fetch_add(&chand->call_count, 1);
- grpc_transport_op* op = grpc_make_transport_op(nullptr);
- op->goaway_error =
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("max_idle"),
- GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_NO_ERROR);
- grpc_channel_element* elem =
- grpc_channel_stack_element(chand->channel_stack, 0);
- elem->filter->start_transport_op(elem, op);
-}
-
-static void max_idle_timer_cb(void* arg, grpc_error* error) {
- channel_data* chand = static_cast<channel_data*>(arg);
- if (error == GRPC_ERROR_NONE) {
- bool try_again = true;
- while (try_again) {
- gpr_atm idle_state = gpr_atm_acq_load(&chand->idle_state);
- switch (idle_state) {
- case MAX_IDLE_STATE_TIMER_SET:
- close_max_idle_channel(chand);
- /* This MAX_IDLE_STATE_INIT is a final state, we don't have to check
- * if idle_state has been changed */
- gpr_atm_rel_store(&chand->idle_state, MAX_IDLE_STATE_INIT);
- try_again = false;
- break;
- case MAX_IDLE_STATE_SEEN_EXIT_IDLE:
- if (gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_SEEN_EXIT_IDLE,
- MAX_IDLE_STATE_INIT)) {
- try_again = false;
- }
- break;
- case MAX_IDLE_STATE_SEEN_ENTER_IDLE:
- GRPC_CHANNEL_STACK_REF(chand->channel_stack,
- "max_age max_idle_timer");
- grpc_timer_init(&chand->max_idle_timer,
- static_cast<grpc_millis>(gpr_atm_no_barrier_load(
- &chand->last_enter_idle_time_millis)) +
- chand->max_connection_idle,
- &chand->max_idle_timer_cb);
- /* idle_state may have already been set to
- MAX_IDLE_STATE_SEEN_EXIT_IDLE by increase_call_count(), in this
- case, we don't need to set it to MAX_IDLE_STATE_TIMER_SET */
- gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_SEEN_ENTER_IDLE,
- MAX_IDLE_STATE_TIMER_SET);
- try_again = false;
- break;
- default:
- /* try again */
- break;
- }
- }
- }
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack, "max_age max_idle_timer");
-}
-
-static void close_max_age_channel(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 = false;
- gpr_mu_unlock(&chand->max_age_timer_mu);
- if (error == GRPC_ERROR_NONE) {
- GRPC_CHANNEL_STACK_REF(chand->channel_stack,
- "max_age start_max_age_grace_timer_after_goaway_op");
- grpc_transport_op* op = grpc_make_transport_op(
- &chand->start_max_age_grace_timer_after_goaway_op);
- op->goaway_error =
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("max_age"),
- GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_NO_ERROR);
- grpc_channel_element* elem =
- grpc_channel_stack_element(chand->channel_stack, 0);
- elem->filter->start_transport_op(elem, op);
- } else if (error != GRPC_ERROR_CANCELLED) {
- GRPC_LOG_IF_ERROR("close_max_age_channel", error);
- }
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack, "max_age max_age_timer");
-}
-
-static void force_close_max_age_channel(void* arg, 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 = false;
- gpr_mu_unlock(&chand->max_age_timer_mu);
- if (error == GRPC_ERROR_NONE) {
- grpc_transport_op* op = grpc_make_transport_op(nullptr);
- op->disconnect_with_error =
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel reaches max age");
- grpc_channel_element* elem =
- grpc_channel_stack_element(chand->channel_stack, 0);
- elem->filter->start_transport_op(elem, op);
- } else if (error != GRPC_ERROR_CANCELLED) {
- GRPC_LOG_IF_ERROR("force_close_max_age_channel", error);
- }
- GRPC_CHANNEL_STACK_UNREF(chand->channel_stack, "max_age max_age_grace_timer");
-}
-
-/* A random jitter of +/-10% will be added to MAX_CONNECTION_AGE to spread out
- connection storms. Note that the MAX_CONNECTION_AGE option without jitter
- would not create connection storms by itself, but if there happened to be a
- connection storm it could cause it to repeat at a fixed period. */
-static grpc_millis
-add_random_max_connection_age_jitter_and_convert_to_grpc_millis(int value) {
- /* generate a random number between 1 - MAX_CONNECTION_AGE_JITTER and
- 1 + MAX_CONNECTION_AGE_JITTER */
- double multiplier = rand() * MAX_CONNECTION_AGE_JITTER * 2.0 / RAND_MAX +
- 1.0 - MAX_CONNECTION_AGE_JITTER;
- double result = multiplier * value;
- /* INT_MAX - 0.5 converts the value to float, so that result will not be
- cast to int implicitly before the comparison. */
- return result > (static_cast<double>(GRPC_MILLIS_INF_FUTURE)) - 0.5
- ? GRPC_MILLIS_INF_FUTURE
- : static_cast<grpc_millis>(result);
-}
-
-/* Constructor for call_data. */
+ channel_data* chand = static_cast<channel_data*>(arg);
+ gpr_mu_lock(&chand->max_age_timer_mu);
+ chand->max_age_grace_timer_pending = true;
+ GRPC_CHANNEL_STACK_REF(chand->channel_stack, "max_age max_age_grace_timer");
+ grpc_timer_init(
+ &chand->max_age_grace_timer,
+ chand->max_connection_age_grace == GRPC_MILLIS_INF_FUTURE
+ ? GRPC_MILLIS_INF_FUTURE
+ : grpc_core::ExecCtx::Get()->Now() + chand->max_connection_age_grace,
+ &chand->force_close_max_age_channel);
+ gpr_mu_unlock(&chand->max_age_timer_mu);
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack,
+ "max_age start_max_age_grace_timer_after_goaway_op");
+}
+
+static void close_max_idle_channel(channel_data* chand) {
+ /* Prevent the max idle timer from being set again */
+ gpr_atm_no_barrier_fetch_add(&chand->call_count, 1);
+ grpc_transport_op* op = grpc_make_transport_op(nullptr);
+ op->goaway_error =
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("max_idle"),
+ GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_NO_ERROR);
+ grpc_channel_element* elem =
+ grpc_channel_stack_element(chand->channel_stack, 0);
+ elem->filter->start_transport_op(elem, op);
+}
+
+static void max_idle_timer_cb(void* arg, grpc_error* error) {
+ channel_data* chand = static_cast<channel_data*>(arg);
+ if (error == GRPC_ERROR_NONE) {
+ bool try_again = true;
+ while (try_again) {
+ gpr_atm idle_state = gpr_atm_acq_load(&chand->idle_state);
+ switch (idle_state) {
+ case MAX_IDLE_STATE_TIMER_SET:
+ close_max_idle_channel(chand);
+ /* This MAX_IDLE_STATE_INIT is a final state, we don't have to check
+ * if idle_state has been changed */
+ gpr_atm_rel_store(&chand->idle_state, MAX_IDLE_STATE_INIT);
+ try_again = false;
+ break;
+ case MAX_IDLE_STATE_SEEN_EXIT_IDLE:
+ if (gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_SEEN_EXIT_IDLE,
+ MAX_IDLE_STATE_INIT)) {
+ try_again = false;
+ }
+ break;
+ case MAX_IDLE_STATE_SEEN_ENTER_IDLE:
+ GRPC_CHANNEL_STACK_REF(chand->channel_stack,
+ "max_age max_idle_timer");
+ grpc_timer_init(&chand->max_idle_timer,
+ static_cast<grpc_millis>(gpr_atm_no_barrier_load(
+ &chand->last_enter_idle_time_millis)) +
+ chand->max_connection_idle,
+ &chand->max_idle_timer_cb);
+ /* idle_state may have already been set to
+ MAX_IDLE_STATE_SEEN_EXIT_IDLE by increase_call_count(), in this
+ case, we don't need to set it to MAX_IDLE_STATE_TIMER_SET */
+ gpr_atm_rel_cas(&chand->idle_state, MAX_IDLE_STATE_SEEN_ENTER_IDLE,
+ MAX_IDLE_STATE_TIMER_SET);
+ try_again = false;
+ break;
+ default:
+ /* try again */
+ break;
+ }
+ }
+ }
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack, "max_age max_idle_timer");
+}
+
+static void close_max_age_channel(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 = false;
+ gpr_mu_unlock(&chand->max_age_timer_mu);
+ if (error == GRPC_ERROR_NONE) {
+ GRPC_CHANNEL_STACK_REF(chand->channel_stack,
+ "max_age start_max_age_grace_timer_after_goaway_op");
+ grpc_transport_op* op = grpc_make_transport_op(
+ &chand->start_max_age_grace_timer_after_goaway_op);
+ op->goaway_error =
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("max_age"),
+ GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_NO_ERROR);
+ grpc_channel_element* elem =
+ grpc_channel_stack_element(chand->channel_stack, 0);
+ elem->filter->start_transport_op(elem, op);
+ } else if (error != GRPC_ERROR_CANCELLED) {
+ GRPC_LOG_IF_ERROR("close_max_age_channel", error);
+ }
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack, "max_age max_age_timer");
+}
+
+static void force_close_max_age_channel(void* arg, 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 = false;
+ gpr_mu_unlock(&chand->max_age_timer_mu);
+ if (error == GRPC_ERROR_NONE) {
+ grpc_transport_op* op = grpc_make_transport_op(nullptr);
+ op->disconnect_with_error =
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel reaches max age");
+ grpc_channel_element* elem =
+ grpc_channel_stack_element(chand->channel_stack, 0);
+ elem->filter->start_transport_op(elem, op);
+ } else if (error != GRPC_ERROR_CANCELLED) {
+ GRPC_LOG_IF_ERROR("force_close_max_age_channel", error);
+ }
+ GRPC_CHANNEL_STACK_UNREF(chand->channel_stack, "max_age max_age_grace_timer");
+}
+
+/* A random jitter of +/-10% will be added to MAX_CONNECTION_AGE to spread out
+ connection storms. Note that the MAX_CONNECTION_AGE option without jitter
+ would not create connection storms by itself, but if there happened to be a
+ connection storm it could cause it to repeat at a fixed period. */
+static grpc_millis
+add_random_max_connection_age_jitter_and_convert_to_grpc_millis(int value) {
+ /* generate a random number between 1 - MAX_CONNECTION_AGE_JITTER and
+ 1 + MAX_CONNECTION_AGE_JITTER */
+ double multiplier = rand() * MAX_CONNECTION_AGE_JITTER * 2.0 / RAND_MAX +
+ 1.0 - MAX_CONNECTION_AGE_JITTER;
+ double result = multiplier * value;
+ /* INT_MAX - 0.5 converts the value to float, so that result will not be
+ cast to int implicitly before the comparison. */
+ return result > (static_cast<double>(GRPC_MILLIS_INF_FUTURE)) - 0.5
+ ? GRPC_MILLIS_INF_FUTURE
+ : static_cast<grpc_millis>(result);
+}
+
+/* Constructor for call_data. */
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. */
+ 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*/) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- decrease_call_count(chand);
-}
-
-/* Constructor for channel_data. */
+ 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) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- gpr_mu_init(&chand->max_age_timer_mu);
- chand->max_age_timer_pending = false;
- chand->max_age_grace_timer_pending = false;
- chand->channel_stack = args->channel_stack;
- chand->max_connection_age =
- add_random_max_connection_age_jitter_and_convert_to_grpc_millis(
- DEFAULT_MAX_CONNECTION_AGE_MS);
- chand->max_connection_age_grace =
- DEFAULT_MAX_CONNECTION_AGE_GRACE_MS == INT_MAX
- ? GRPC_MILLIS_INF_FUTURE
- : DEFAULT_MAX_CONNECTION_AGE_GRACE_MS;
- chand->max_connection_idle = DEFAULT_MAX_CONNECTION_IDLE_MS == INT_MAX
- ? GRPC_MILLIS_INF_FUTURE
- : DEFAULT_MAX_CONNECTION_IDLE_MS;
- chand->idle_state = MAX_IDLE_STATE_INIT;
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ gpr_mu_init(&chand->max_age_timer_mu);
+ chand->max_age_timer_pending = false;
+ chand->max_age_grace_timer_pending = false;
+ chand->channel_stack = args->channel_stack;
+ chand->max_connection_age =
+ add_random_max_connection_age_jitter_and_convert_to_grpc_millis(
+ DEFAULT_MAX_CONNECTION_AGE_MS);
+ chand->max_connection_age_grace =
+ DEFAULT_MAX_CONNECTION_AGE_GRACE_MS == INT_MAX
+ ? GRPC_MILLIS_INF_FUTURE
+ : DEFAULT_MAX_CONNECTION_AGE_GRACE_MS;
+ chand->max_connection_idle = DEFAULT_MAX_CONNECTION_IDLE_MS == INT_MAX
+ ? GRPC_MILLIS_INF_FUTURE
+ : DEFAULT_MAX_CONNECTION_IDLE_MS;
+ chand->idle_state = MAX_IDLE_STATE_INIT;
gpr_atm_no_barrier_store(&chand->last_enter_idle_time_millis, GPR_ATM_MIN);
- for (size_t i = 0; i < args->channel_args->num_args; ++i) {
- if (0 == strcmp(args->channel_args->args[i].key,
- GRPC_ARG_MAX_CONNECTION_AGE_MS)) {
- const int value = grpc_channel_arg_get_integer(
- &args->channel_args->args[i], MAX_CONNECTION_AGE_INTEGER_OPTIONS);
- chand->max_connection_age =
- add_random_max_connection_age_jitter_and_convert_to_grpc_millis(
- value);
- } else if (0 == strcmp(args->channel_args->args[i].key,
- GRPC_ARG_MAX_CONNECTION_AGE_GRACE_MS)) {
- const int value = grpc_channel_arg_get_integer(
- &args->channel_args->args[i],
- {DEFAULT_MAX_CONNECTION_AGE_GRACE_MS, 0, INT_MAX});
- chand->max_connection_age_grace =
- value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value;
- } else if (0 == strcmp(args->channel_args->args[i].key,
- GRPC_ARG_MAX_CONNECTION_IDLE_MS)) {
- const int value = grpc_channel_arg_get_integer(
- &args->channel_args->args[i], MAX_CONNECTION_IDLE_INTEGER_OPTIONS);
- chand->max_connection_idle =
- value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value;
- }
- }
- GRPC_CLOSURE_INIT(&chand->max_idle_timer_cb, max_idle_timer_cb, chand,
- grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&chand->close_max_age_channel, close_max_age_channel, chand,
- grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&chand->force_close_max_age_channel,
- force_close_max_age_channel, chand,
- grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&chand->start_max_idle_timer_after_init,
- start_max_idle_timer_after_init, chand,
- grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&chand->start_max_age_timer_after_init,
- start_max_age_timer_after_init, chand,
- grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&chand->start_max_age_grace_timer_after_goaway_op,
- start_max_age_grace_timer_after_goaway_op, chand,
- grpc_schedule_on_exec_ctx);
-
- if (chand->max_connection_age != GRPC_MILLIS_INF_FUTURE) {
- /* When the channel reaches its max age, we send down an op with
- goaway_error set. However, we can't send down any ops until after the
- channel stack is fully initialized. If we start the timer here, we have
- no guarantee that the timer won't pop before channel stack initialization
- is finished. To avoid that problem, we create a closure to start the
- timer, and we schedule that closure to be run after call stack
- initialization is done. */
- GRPC_CHANNEL_STACK_REF(chand->channel_stack,
- "max_age start_max_age_timer_after_init");
+ for (size_t i = 0; i < args->channel_args->num_args; ++i) {
+ if (0 == strcmp(args->channel_args->args[i].key,
+ GRPC_ARG_MAX_CONNECTION_AGE_MS)) {
+ const int value = grpc_channel_arg_get_integer(
+ &args->channel_args->args[i], MAX_CONNECTION_AGE_INTEGER_OPTIONS);
+ chand->max_connection_age =
+ add_random_max_connection_age_jitter_and_convert_to_grpc_millis(
+ value);
+ } else if (0 == strcmp(args->channel_args->args[i].key,
+ GRPC_ARG_MAX_CONNECTION_AGE_GRACE_MS)) {
+ const int value = grpc_channel_arg_get_integer(
+ &args->channel_args->args[i],
+ {DEFAULT_MAX_CONNECTION_AGE_GRACE_MS, 0, INT_MAX});
+ chand->max_connection_age_grace =
+ value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value;
+ } else if (0 == strcmp(args->channel_args->args[i].key,
+ GRPC_ARG_MAX_CONNECTION_IDLE_MS)) {
+ const int value = grpc_channel_arg_get_integer(
+ &args->channel_args->args[i], MAX_CONNECTION_IDLE_INTEGER_OPTIONS);
+ chand->max_connection_idle =
+ value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value;
+ }
+ }
+ GRPC_CLOSURE_INIT(&chand->max_idle_timer_cb, max_idle_timer_cb, chand,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&chand->close_max_age_channel, close_max_age_channel, chand,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&chand->force_close_max_age_channel,
+ force_close_max_age_channel, chand,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&chand->start_max_idle_timer_after_init,
+ start_max_idle_timer_after_init, chand,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&chand->start_max_age_timer_after_init,
+ start_max_age_timer_after_init, chand,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&chand->start_max_age_grace_timer_after_goaway_op,
+ start_max_age_grace_timer_after_goaway_op, chand,
+ grpc_schedule_on_exec_ctx);
+
+ if (chand->max_connection_age != GRPC_MILLIS_INF_FUTURE) {
+ /* When the channel reaches its max age, we send down an op with
+ goaway_error set. However, we can't send down any ops until after the
+ channel stack is fully initialized. If we start the timer here, we have
+ no guarantee that the timer won't pop before channel stack initialization
+ is finished. To avoid that problem, we create a closure to start the
+ timer, and we schedule that closure to be run after call stack
+ 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);
- }
-
- /* Initialize the number of calls as 1, so that the max_idle_timer will not
- start until start_max_idle_timer_after_init is invoked. */
- gpr_atm_rel_store(&chand->call_count, 1);
- if (chand->max_connection_idle != GRPC_MILLIS_INF_FUTURE) {
- GRPC_CHANNEL_STACK_REF(chand->channel_stack,
- "max_age start_max_idle_timer_after_init");
+ }
+
+ /* Initialize the number of calls as 1, so that the max_idle_timer will not
+ start until start_max_idle_timer_after_init is invoked. */
+ gpr_atm_rel_store(&chand->call_count, 1);
+ 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);
- }
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel_data. */
+ }
+ 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);
}
-
-const grpc_channel_filter grpc_max_age_filter = {
- grpc_call_next_op,
- grpc_channel_next_op,
- 0, /* sizeof_call_data */
+
+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,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
max_age_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
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,
+ grpc_channel_next_get_info,
+ "max_age"};
+
+static bool maybe_add_max_age_filter(grpc_channel_stack_builder* builder,
void* /*arg*/) {
- const grpc_channel_args* channel_args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- bool enable =
- grpc_channel_arg_get_integer(
- grpc_channel_args_find(channel_args, GRPC_ARG_MAX_CONNECTION_AGE_MS),
- MAX_CONNECTION_AGE_INTEGER_OPTIONS) != INT_MAX ||
- grpc_channel_arg_get_integer(
- grpc_channel_args_find(channel_args, GRPC_ARG_MAX_CONNECTION_IDLE_MS),
- MAX_CONNECTION_IDLE_INTEGER_OPTIONS) != INT_MAX;
- if (enable) {
- return grpc_channel_stack_builder_prepend_filter(
- builder, &grpc_max_age_filter, nullptr, nullptr);
- } else {
- return true;
- }
-}
-
-void grpc_max_age_filter_init(void) {
- grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
- GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- maybe_add_max_age_filter, nullptr);
-}
-
-void grpc_max_age_filter_shutdown(void) {}
+ const grpc_channel_args* channel_args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ bool enable =
+ grpc_channel_arg_get_integer(
+ grpc_channel_args_find(channel_args, GRPC_ARG_MAX_CONNECTION_AGE_MS),
+ MAX_CONNECTION_AGE_INTEGER_OPTIONS) != INT_MAX ||
+ grpc_channel_arg_get_integer(
+ grpc_channel_args_find(channel_args, GRPC_ARG_MAX_CONNECTION_IDLE_MS),
+ MAX_CONNECTION_IDLE_INTEGER_OPTIONS) != INT_MAX;
+ if (enable) {
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, &grpc_max_age_filter, nullptr, nullptr);
+ } else {
+ return true;
+ }
+}
+
+void grpc_max_age_filter_init(void) {
+ grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
+ GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ maybe_add_max_age_filter, nullptr);
+}
+
+void grpc_max_age_filter_shutdown(void) {}
diff --git a/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.h b/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.h
index 989322244f7..37138f8236b 100644
--- a/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.h
@@ -1,26 +1,26 @@
-//
-// 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_EXT_FILTERS_MAX_AGE_MAX_AGE_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_MAX_AGE_MAX_AGE_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-
-extern const grpc_channel_filter grpc_max_age_filter;
-
-#endif /* GRPC_CORE_EXT_FILTERS_MAX_AGE_MAX_AGE_FILTER_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.
+//
+
+#ifndef GRPC_CORE_EXT_FILTERS_MAX_AGE_MAX_AGE_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_MAX_AGE_MAX_AGE_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+
+extern const grpc_channel_filter grpc_max_age_filter;
+
+#endif /* GRPC_CORE_EXT_FILTERS_MAX_AGE_MAX_AGE_FILTER_H */
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 944479ac3b2..c42b21b4b3d 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
@@ -1,51 +1,51 @@
-//
-// 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/ext/filters/message_size/message_size_filter.h"
-
-#include <limits.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.
+//
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/filters/message_size/message_size_filter.h"
+
+#include <limits.h>
+#include <string.h>
+
#include "y_absl/strings/str_format.h"
-#include <grpc/impl/codegen/grpc_types.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
+#include <grpc/impl/codegen/grpc_types.h>
+#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_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/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/channel_init.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);
+
+namespace grpc_core {
-namespace grpc_core {
-
-namespace {
+namespace {
size_t g_message_size_parser_index;
} // namespace
-
+
//
// MessageSizeParsedConfig
//
@@ -71,7 +71,7 @@ MessageSizeParser::ParsePerMethodParams(const grpc_channel_args* /*args*/,
GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
std::vector<grpc_error*> error_list;
// Max request size.
- int max_request_message_bytes = -1;
+ int max_request_message_bytes = -1;
auto it = json.object_value().find("maxRequestMessageBytes");
if (it != json.object_value().end()) {
if (it->second.type() != Json::Type::STRING &&
@@ -84,7 +84,7 @@ MessageSizeParser::ParsePerMethodParams(const grpc_channel_args* /*args*/,
if (max_request_message_bytes == -1) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:maxRequestMessageBytes error:should be non-negative"));
- }
+ }
}
}
// Max response size.
@@ -101,17 +101,17 @@ MessageSizeParser::ParsePerMethodParams(const grpc_channel_args* /*args*/,
if (max_response_message_bytes == -1) {
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;
}
return y_absl::make_unique<MessageSizeParsedConfig>(max_request_message_bytes,
max_response_message_bytes);
-}
-
+}
+
void MessageSizeParser::Register() {
g_message_size_parser_index = ServiceConfigParser::RegisterParser(
y_absl::make_unique<MessageSizeParser>());
@@ -133,14 +133,14 @@ int GetMaxSendSizeFromChannelArgs(const grpc_channel_args* args) {
{GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH, -1, INT_MAX});
}
-} // namespace grpc_core
-
-namespace {
+} // namespace grpc_core
+
+namespace {
struct channel_data {
grpc_core::MessageSizeParsedConfig::message_size_limits limits;
};
-struct call_data {
+struct call_data {
call_data(grpc_call_element* elem, const channel_data& chand,
const grpc_call_element_args& args)
: call_combiner(args.call_combiner), limits(chand.limits) {
@@ -173,47 +173,47 @@ struct call_data {
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.
- grpc_closure recv_message_ready;
+ // 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.
+ grpc_closure recv_message_ready;
grpc_closure recv_trailing_metadata_ready;
// The error caused by a message that is too large, or GRPC_ERROR_NONE
grpc_error* error = GRPC_ERROR_NONE;
- // Used by recv_message_ready.
+ // Used by recv_message_ready.
grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message = nullptr;
- // Original recv_message_ready callback, invoked after our own.
+ // Original recv_message_ready callback, invoked after our own.
grpc_closure* next_recv_message_ready = nullptr;
// Original recv_trailing_metadata callback, invoked after our own.
grpc_closure* original_recv_trailing_metadata_ready;
bool seen_recv_trailing_metadata = false;
grpc_error* recv_trailing_metadata_error;
-};
-
-} // namespace
-
-// Callback invoked when we receive a message. Here we check the max
-// receive message size.
-static void recv_message_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 (*calld->recv_message != nullptr && calld->limits.max_recv_size >= 0 &&
- (*calld->recv_message)->length() >
- static_cast<size_t>(calld->limits.max_recv_size)) {
- grpc_error* new_error = grpc_error_set_int(
+};
+
+} // namespace
+
+// Callback invoked when we receive a message. Here we check the max
+// receive message size.
+static void recv_message_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 (*calld->recv_message != nullptr && calld->limits.max_recv_size >= 0 &&
+ (*calld->recv_message)->length() >
+ static_cast<size_t>(calld->limits.max_recv_size)) {
+ grpc_error* new_error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("Received message larger than max (%u vs. %d)",
(*calld->recv_message)->length(),
calld->limits.max_recv_size)
.c_str()),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_RESOURCE_EXHAUSTED);
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_RESOURCE_EXHAUSTED);
error = grpc_error_add_child(GRPC_ERROR_REF(error), new_error);
GRPC_ERROR_UNREF(calld->error);
calld->error = GRPC_ERROR_REF(error);
- } else {
- GRPC_ERROR_REF(error);
- }
- // Invoke the next callback.
+ } else {
+ GRPC_ERROR_REF(error);
+ }
+ // Invoke the next callback.
grpc_closure* closure = calld->next_recv_message_ready;
calld->next_recv_message_ready = nullptr;
if (calld->seen_recv_trailing_metadata) {
@@ -229,8 +229,8 @@ static void recv_message_ready(void* user_data, grpc_error* error) {
"continue recv_trailing_metadata_ready");
}
grpc_core::Closure::Run(DEBUG_LOCATION, closure, error);
-}
-
+}
+
// Callback invoked on completion of recv_trailing_metadata
// Notifies the recv_trailing_metadata batch of any message size failures
static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) {
@@ -251,16 +251,16 @@ static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) {
calld->original_recv_trailing_metadata_ready, error);
}
-// Start transport stream op.
+// Start transport stream op.
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.
- if (op->send_message && calld->limits.max_send_size >= 0 &&
- op->payload->send_message.send_message->length() >
- static_cast<size_t>(calld->limits.max_send_size)) {
- grpc_transport_stream_op_batch_finish_with_failure(
- op,
+ 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.
+ if (op->send_message && calld->limits.max_send_size >= 0 &&
+ op->payload->send_message.send_message->length() >
+ static_cast<size_t>(calld->limits.max_send_size)) {
+ grpc_transport_stream_op_batch_finish_with_failure(
+ op,
grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat(
@@ -269,16 +269,16 @@ static void message_size_start_transport_stream_op_batch(
calld->limits.max_send_size)
.c_str()),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_RESOURCE_EXHAUSTED),
- calld->call_combiner);
- return;
- }
- // Inject callback for receiving a message.
- if (op->recv_message) {
- calld->next_recv_message_ready =
- op->payload->recv_message.recv_message_ready;
- calld->recv_message = op->payload->recv_message.recv_message;
- op->payload->recv_message.recv_message_ready = &calld->recv_message_ready;
- }
+ calld->call_combiner);
+ return;
+ }
+ // Inject callback for receiving a message.
+ if (op->recv_message) {
+ calld->next_recv_message_ready =
+ op->payload->recv_message.recv_message_ready;
+ calld->recv_message = op->payload->recv_message.recv_message;
+ op->payload->recv_message.recv_message_ready = &calld->recv_message_ready;
+ }
// Inject callback for receiving trailing metadata.
if (op->recv_trailing_metadata) {
calld->original_recv_trailing_metadata_ready =
@@ -286,63 +286,63 @@ static void message_size_start_transport_stream_op_batch(
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&calld->recv_trailing_metadata_ready;
}
- // Chain to the next filter.
- grpc_call_next_op(elem, op);
-}
-
-// Constructor for call_data.
+ // Chain to the next filter.
+ grpc_call_next_op(elem, op);
+}
+
+// Constructor for call_data.
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);
+ 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.
+ 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*/) {
call_data* calld = (call_data*)elem->call_data;
calld->~call_data();
}
-
+
grpc_core::MessageSizeParsedConfig::message_size_limits get_message_size_limits(
- const grpc_channel_args* channel_args) {
+ const grpc_channel_args* channel_args) {
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.
+ return lim;
+}
+
+// Constructor for channel_data.
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);
+ GPR_ASSERT(!args->is_last);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
new (chand) channel_data();
- chand->limits = get_message_size_limits(args->channel_args);
- return GRPC_ERROR_NONE;
-}
-
-// Destructor for 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) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
chand->~channel_data();
-}
-
-const grpc_channel_filter grpc_message_size_filter = {
+}
+
+const grpc_channel_filter grpc_message_size_filter = {
message_size_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(call_data),
+ grpc_channel_next_op,
+ sizeof(call_data),
message_size_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
message_size_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
message_size_init_channel_elem,
message_size_destroy_channel_elem,
- grpc_channel_next_get_info,
- "message_size"};
-
+ 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*/) {
@@ -357,44 +357,44 @@ static bool maybe_add_message_size_filter_subchannel(
// 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,
+static bool maybe_add_message_size_filter(grpc_channel_stack_builder* builder,
void* /*arg*/) {
- const grpc_channel_args* channel_args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
+ 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;
+ bool enable = false;
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);
+ 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) {
- enable = true;
- }
- if (enable) {
- return grpc_channel_stack_builder_prepend_filter(
- builder, &grpc_message_size_filter, nullptr, nullptr);
- } else {
- return true;
- }
-}
-
-void grpc_message_size_filter_init(void) {
+ enable = true;
+ }
+ if (enable) {
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, &grpc_message_size_filter, nullptr, nullptr);
+ } else {
+ return true;
+ }
+}
+
+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_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_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();
-}
-
-void grpc_message_size_filter_shutdown(void) {}
+}
+
+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 0583a789267..62bcddcf555 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
@@ -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 GRPC_CORE_EXT_FILTERS_MESSAGE_SIZE_MESSAGE_SIZE_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_MESSAGE_SIZE_MESSAGE_SIZE_FILTER_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_MESSAGE_SIZE_MESSAGE_SIZE_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_MESSAGE_SIZE_MESSAGE_SIZE_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
#include "src/core/ext/filters/client_channel/service_config_parser.h"
-#include "src/core/lib/channel/channel_stack.h"
-
-extern const grpc_channel_filter grpc_message_size_filter;
-
+#include "src/core/lib/channel/channel_stack.h"
+
+extern const grpc_channel_filter grpc_message_size_filter;
+
namespace grpc_core {
class MessageSizeParsedConfig : public ServiceConfigParser::ParsedConfig {
@@ -63,4 +63,4 @@ int GetMaxSendSizeFromChannelArgs(const grpc_channel_args* args);
} // namespace grpc_core
-#endif /* GRPC_CORE_EXT_FILTERS_MESSAGE_SIZE_MESSAGE_SIZE_FILTER_H */
+#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 7f9a4fcaf82..11fb578bb13 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
@@ -1,210 +1,210 @@
-//
-// 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/ext/filters/workarounds/workaround_cronet_compression_filter.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-#include "src/core/ext/filters/workarounds/workaround_utils.h"
-#include "src/core/lib/channel/channel_stack_builder.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/transport/metadata.h"
-
-namespace {
-struct call_data {
- // Receive closures are chained: we inject this closure as the
- // recv_initial_metadata_ready up-call on transport_stream_op, and remember to
- // call our next_recv_initial_metadata_ready member after handling it.
- grpc_closure recv_initial_metadata_ready;
- // Used by recv_initial_metadata_ready.
- grpc_metadata_batch* recv_initial_metadata;
- // Original recv_initial_metadata_ready callback, invoked after our own.
- grpc_closure* next_recv_initial_metadata_ready;
-
- // Marks whether the workaround is active
- bool workaround_active;
-};
-} // namespace
-
-// Find the user agent metadata element in the batch
-static bool get_user_agent_mdelem(const grpc_metadata_batch* batch,
- grpc_mdelem* md) {
- if (batch->idx.named.user_agent != nullptr) {
- *md = batch->idx.named.user_agent->md;
- return true;
- }
- return false;
-}
-
-// Callback invoked when we receive an initial metadata.
-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 (GRPC_ERROR_NONE == error) {
- grpc_mdelem md;
- if (get_user_agent_mdelem(calld->recv_initial_metadata, &md)) {
- grpc_workaround_user_agent_md* user_agent_md = grpc_parse_user_agent(md);
- if (user_agent_md
- ->workaround_active[GRPC_WORKAROUND_ID_CRONET_COMPRESSION]) {
- calld->workaround_active = true;
- }
- }
- }
-
- // Invoke the next callback.
+//
+// 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/ext/filters/workarounds/workaround_cronet_compression_filter.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+#include "src/core/ext/filters/workarounds/workaround_utils.h"
+#include "src/core/lib/channel/channel_stack_builder.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/transport/metadata.h"
+
+namespace {
+struct call_data {
+ // Receive closures are chained: we inject this closure as the
+ // recv_initial_metadata_ready up-call on transport_stream_op, and remember to
+ // call our next_recv_initial_metadata_ready member after handling it.
+ grpc_closure recv_initial_metadata_ready;
+ // Used by recv_initial_metadata_ready.
+ grpc_metadata_batch* recv_initial_metadata;
+ // Original recv_initial_metadata_ready callback, invoked after our own.
+ grpc_closure* next_recv_initial_metadata_ready;
+
+ // Marks whether the workaround is active
+ bool workaround_active;
+};
+} // namespace
+
+// Find the user agent metadata element in the batch
+static bool get_user_agent_mdelem(const grpc_metadata_batch* batch,
+ grpc_mdelem* md) {
+ if (batch->idx.named.user_agent != nullptr) {
+ *md = batch->idx.named.user_agent->md;
+ return true;
+ }
+ return false;
+}
+
+// Callback invoked when we receive an initial metadata.
+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 (GRPC_ERROR_NONE == error) {
+ grpc_mdelem md;
+ if (get_user_agent_mdelem(calld->recv_initial_metadata, &md)) {
+ grpc_workaround_user_agent_md* user_agent_md = grpc_parse_user_agent(md);
+ if (user_agent_md
+ ->workaround_active[GRPC_WORKAROUND_ID_CRONET_COMPRESSION]) {
+ calld->workaround_active = true;
+ }
+ }
+ }
+
+ // Invoke the next callback.
grpc_core::Closure::Run(DEBUG_LOCATION,
calld->next_recv_initial_metadata_ready,
GRPC_ERROR_REF(error));
-}
-
-// Start transport stream op.
+}
+
+// Start transport stream op.
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);
-
- // Inject callback for receiving initial metadata
- if (op->recv_initial_metadata) {
- calld->next_recv_initial_metadata_ready =
- op->payload->recv_initial_metadata.recv_initial_metadata_ready;
- op->payload->recv_initial_metadata.recv_initial_metadata_ready =
- &calld->recv_initial_metadata_ready;
- calld->recv_initial_metadata =
- op->payload->recv_initial_metadata.recv_initial_metadata;
- }
-
- if (op->send_message) {
- /* Send message happens after client's user-agent (initial metadata) is
- * received, so workaround_active must be set already */
- if (calld->workaround_active) {
- op->payload->send_message.send_message->set_flags(
- op->payload->send_message.send_message->flags() |
- GRPC_WRITE_NO_COMPRESS);
- }
- }
-
- // Chain to the next filter.
- grpc_call_next_op(elem, op);
-}
-
-// Constructor for call_data.
+ grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+
+ // Inject callback for receiving initial metadata
+ if (op->recv_initial_metadata) {
+ calld->next_recv_initial_metadata_ready =
+ op->payload->recv_initial_metadata.recv_initial_metadata_ready;
+ op->payload->recv_initial_metadata.recv_initial_metadata_ready =
+ &calld->recv_initial_metadata_ready;
+ calld->recv_initial_metadata =
+ op->payload->recv_initial_metadata.recv_initial_metadata;
+ }
+
+ if (op->send_message) {
+ /* Send message happens after client's user-agent (initial metadata) is
+ * received, so workaround_active must be set already */
+ if (calld->workaround_active) {
+ op->payload->send_message.send_message->set_flags(
+ op->payload->send_message.send_message->flags() |
+ GRPC_WRITE_NO_COMPRESS);
+ }
+ }
+
+ // Chain to the next filter.
+ grpc_call_next_op(elem, op);
+}
+
+// Constructor for call_data.
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;
- GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready,
- recv_initial_metadata_ready, elem,
- grpc_schedule_on_exec_ctx);
- return GRPC_ERROR_NONE;
-}
-
-// Destructor for call_data.
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ calld->next_recv_initial_metadata_ready = nullptr;
+ calld->workaround_active = false;
+ GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready,
+ recv_initial_metadata_ready, elem,
+ grpc_schedule_on_exec_ctx);
+ return GRPC_ERROR_NONE;
+}
+
+// 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*/) {}
-
-// Constructor for channel_data.
+
+// Constructor for channel_data.
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.
+ return GRPC_ERROR_NONE;
+}
+
+// Destructor for channel_data.
static void cronet_compression_destroy_channel_elem(
grpc_channel_element* /*elem*/) {}
-
-// Parse the user agent
-static bool parse_user_agent(grpc_mdelem md) {
- const char grpc_objc_specifier[] = "grpc-objc/";
- const size_t grpc_objc_specifier_len = sizeof(grpc_objc_specifier) - 1;
- const char cronet_specifier[] = "cronet_http";
- const size_t cronet_specifier_len = sizeof(cronet_specifier) - 1;
-
- char* user_agent_str = grpc_slice_to_c_string(GRPC_MDVALUE(md));
- bool grpc_objc_specifier_seen = false;
- bool cronet_specifier_seen = false;
- char *major_version_str = user_agent_str, *minor_version_str;
- long major_version = 0, minor_version = 0;
-
- char* head = strtok(user_agent_str, " ");
- while (head != nullptr) {
- if (!grpc_objc_specifier_seen &&
- 0 == strncmp(head, grpc_objc_specifier, grpc_objc_specifier_len)) {
- major_version_str = head + grpc_objc_specifier_len;
- grpc_objc_specifier_seen = true;
- } else if (grpc_objc_specifier_seen &&
- 0 == strncmp(head, cronet_specifier, cronet_specifier_len)) {
- cronet_specifier_seen = true;
- break;
- }
-
- head = strtok(nullptr, " ");
- }
- if (grpc_objc_specifier_seen) {
- major_version_str = strtok(major_version_str, ".");
- minor_version_str = strtok(nullptr, ".");
- major_version = atol(major_version_str);
- minor_version = atol(minor_version_str);
- }
-
- gpr_free(user_agent_str);
- return (grpc_objc_specifier_seen && cronet_specifier_seen &&
- (major_version < 1 || (major_version == 1 && minor_version <= 3)));
-}
-
-const grpc_channel_filter grpc_workaround_cronet_compression_filter = {
+
+// Parse the user agent
+static bool parse_user_agent(grpc_mdelem md) {
+ const char grpc_objc_specifier[] = "grpc-objc/";
+ const size_t grpc_objc_specifier_len = sizeof(grpc_objc_specifier) - 1;
+ const char cronet_specifier[] = "cronet_http";
+ const size_t cronet_specifier_len = sizeof(cronet_specifier) - 1;
+
+ char* user_agent_str = grpc_slice_to_c_string(GRPC_MDVALUE(md));
+ bool grpc_objc_specifier_seen = false;
+ bool cronet_specifier_seen = false;
+ char *major_version_str = user_agent_str, *minor_version_str;
+ long major_version = 0, minor_version = 0;
+
+ char* head = strtok(user_agent_str, " ");
+ while (head != nullptr) {
+ if (!grpc_objc_specifier_seen &&
+ 0 == strncmp(head, grpc_objc_specifier, grpc_objc_specifier_len)) {
+ major_version_str = head + grpc_objc_specifier_len;
+ grpc_objc_specifier_seen = true;
+ } else if (grpc_objc_specifier_seen &&
+ 0 == strncmp(head, cronet_specifier, cronet_specifier_len)) {
+ cronet_specifier_seen = true;
+ break;
+ }
+
+ head = strtok(nullptr, " ");
+ }
+ if (grpc_objc_specifier_seen) {
+ major_version_str = strtok(major_version_str, ".");
+ minor_version_str = strtok(nullptr, ".");
+ major_version = atol(major_version_str);
+ minor_version = atol(minor_version_str);
+ }
+
+ gpr_free(user_agent_str);
+ return (grpc_objc_specifier_seen && cronet_specifier_seen &&
+ (major_version < 1 || (major_version == 1 && minor_version <= 3)));
+}
+
+const grpc_channel_filter grpc_workaround_cronet_compression_filter = {
cronet_compression_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(call_data),
+ grpc_channel_next_op,
+ sizeof(call_data),
cronet_compression_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
cronet_compression_destroy_call_elem,
- 0,
+ 0,
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_next_get_info,
+ "workaround_cronet_compression"};
+
+static bool register_workaround_cronet_compression(
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(
- channel_args, GRPC_ARG_WORKAROUND_CRONET_COMPRESSION);
- if (a == nullptr) {
- return true;
- }
- if (grpc_channel_arg_get_bool(a, false) == false) {
- return true;
- }
- return grpc_channel_stack_builder_prepend_filter(
- builder, &grpc_workaround_cronet_compression_filter, nullptr, nullptr);
-}
-
-void grpc_workaround_cronet_compression_filter_init(void) {
- grpc_channel_init_register_stage(
- GRPC_SERVER_CHANNEL, GRPC_WORKAROUND_PRIORITY_HIGH,
- register_workaround_cronet_compression, nullptr);
- grpc_register_workaround(GRPC_WORKAROUND_ID_CRONET_COMPRESSION,
- parse_user_agent);
-}
-
-void grpc_workaround_cronet_compression_filter_shutdown(void) {}
+ const grpc_channel_args* channel_args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ const grpc_arg* a = grpc_channel_args_find(
+ channel_args, GRPC_ARG_WORKAROUND_CRONET_COMPRESSION);
+ if (a == nullptr) {
+ return true;
+ }
+ if (grpc_channel_arg_get_bool(a, false) == false) {
+ return true;
+ }
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, &grpc_workaround_cronet_compression_filter, nullptr, nullptr);
+}
+
+void grpc_workaround_cronet_compression_filter_init(void) {
+ grpc_channel_init_register_stage(
+ GRPC_SERVER_CHANNEL, GRPC_WORKAROUND_PRIORITY_HIGH,
+ register_workaround_cronet_compression, nullptr);
+ grpc_register_workaround(GRPC_WORKAROUND_ID_CRONET_COMPRESSION,
+ parse_user_agent);
+}
+
+void grpc_workaround_cronet_compression_filter_shutdown(void) {}
diff --git a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h
index 94d20f0c4ac..768c7008511 100644
--- a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h
+++ b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h
@@ -1,27 +1,27 @@
-//
-// 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_EXT_FILTERS_WORKAROUNDS_WORKAROUND_CRONET_COMPRESSION_FILTER_H
-#define GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_CRONET_COMPRESSION_FILTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-
-extern const grpc_channel_filter grpc_workaround_cronet_compression_filter;
-
-#endif /* GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_CRONET_COMPRESSION_FILTER_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.
+//
+
+#ifndef GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_CRONET_COMPRESSION_FILTER_H
+#define GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_CRONET_COMPRESSION_FILTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+
+extern const grpc_channel_filter grpc_workaround_cronet_compression_filter;
+
+#endif /* GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_CRONET_COMPRESSION_FILTER_H \
+ */
diff --git a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.cc b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.cc
index 4dabe896d3b..68b18bb9b2b 100644
--- a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.cc
+++ b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.cc
@@ -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.
-//
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/filters/workarounds/workaround_utils.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-user_agent_parser ua_parser[GRPC_MAX_WORKAROUND_ID];
-
-static void destroy_user_agent_md(void* user_agent_md) {
- gpr_free(user_agent_md);
-}
-
-grpc_workaround_user_agent_md* grpc_parse_user_agent(grpc_mdelem md) {
- grpc_workaround_user_agent_md* user_agent_md =
- static_cast<grpc_workaround_user_agent_md*>(
- grpc_mdelem_get_user_data(md, destroy_user_agent_md));
-
- if (nullptr != user_agent_md) {
- return user_agent_md;
- }
- user_agent_md = static_cast<grpc_workaround_user_agent_md*>(
- gpr_malloc(sizeof(grpc_workaround_user_agent_md)));
- for (int i = 0; i < GRPC_MAX_WORKAROUND_ID; i++) {
- if (ua_parser[i]) {
- user_agent_md->workaround_active[i] = ua_parser[i](md);
- }
- }
- grpc_mdelem_set_user_data(md, destroy_user_agent_md, (void*)user_agent_md);
-
- return user_agent_md;
-}
-
-void grpc_register_workaround(uint32_t id, user_agent_parser parser) {
- GPR_ASSERT(id < GRPC_MAX_WORKAROUND_ID);
- ua_parser[id] = parser;
-}
+//
+// 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/ext/filters/workarounds/workaround_utils.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+user_agent_parser ua_parser[GRPC_MAX_WORKAROUND_ID];
+
+static void destroy_user_agent_md(void* user_agent_md) {
+ gpr_free(user_agent_md);
+}
+
+grpc_workaround_user_agent_md* grpc_parse_user_agent(grpc_mdelem md) {
+ grpc_workaround_user_agent_md* user_agent_md =
+ static_cast<grpc_workaround_user_agent_md*>(
+ grpc_mdelem_get_user_data(md, destroy_user_agent_md));
+
+ if (nullptr != user_agent_md) {
+ return user_agent_md;
+ }
+ user_agent_md = static_cast<grpc_workaround_user_agent_md*>(
+ gpr_malloc(sizeof(grpc_workaround_user_agent_md)));
+ for (int i = 0; i < GRPC_MAX_WORKAROUND_ID; i++) {
+ if (ua_parser[i]) {
+ user_agent_md->workaround_active[i] = ua_parser[i](md);
+ }
+ }
+ grpc_mdelem_set_user_data(md, destroy_user_agent_md, (void*)user_agent_md);
+
+ return user_agent_md;
+}
+
+void grpc_register_workaround(uint32_t id, user_agent_parser parser) {
+ GPR_ASSERT(id < GRPC_MAX_WORKAROUND_ID);
+ ua_parser[id] = parser;
+}
diff --git a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.h b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.h
index f172ccc0788..dbe0cf9a43d 100644
--- a/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.h
+++ b/contrib/libs/grpc/src/core/ext/filters/workarounds/workaround_utils.h
@@ -1,39 +1,39 @@
-//
-// 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_EXT_FILTERS_WORKAROUNDS_WORKAROUND_UTILS_H
-#define GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_UTILS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/workaround_list.h>
-
-#include "src/core/lib/transport/metadata.h"
-
-#define GRPC_WORKAROUND_PRIORITY_HIGH 10001
-#define GRPC_WORKAROUND_PROIRITY_LOW 9999
-
-typedef struct grpc_workaround_user_agent_md {
- bool workaround_active[GRPC_MAX_WORKAROUND_ID];
-} grpc_workaround_user_agent_md;
-
-grpc_workaround_user_agent_md* grpc_parse_user_agent(grpc_mdelem md);
-
-typedef bool (*user_agent_parser)(grpc_mdelem);
-
-void grpc_register_workaround(uint32_t id, user_agent_parser parser);
-
-#endif /* GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_UTILS_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.
+//
+
+#ifndef GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_UTILS_H
+#define GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_UTILS_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/workaround_list.h>
+
+#include "src/core/lib/transport/metadata.h"
+
+#define GRPC_WORKAROUND_PRIORITY_HIGH 10001
+#define GRPC_WORKAROUND_PROIRITY_LOW 9999
+
+typedef struct grpc_workaround_user_agent_md {
+ bool workaround_active[GRPC_MAX_WORKAROUND_ID];
+} grpc_workaround_user_agent_md;
+
+grpc_workaround_user_agent_md* grpc_parse_user_agent(grpc_mdelem md);
+
+typedef bool (*user_agent_parser)(grpc_mdelem);
+
+void grpc_register_workaround(uint32_t id, user_agent_parser parser);
+
+#endif /* GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_UTILS_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.cc
index 1fdab76dbf0..14aad42b1cc 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/alpn/alpn.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/log.h>
-#include "src/core/ext/transport/chttp2/alpn/alpn.h"
-
-#include "src/core/lib/gpr/useful.h"
-
-/* in order of preference */
-static const char* const supported_versions[] = {"grpc-exp", "h2"};
-
-int grpc_chttp2_is_alpn_version_supported(const char* version, size_t size) {
- size_t i;
- for (i = 0; i < GPR_ARRAY_SIZE(supported_versions); i++) {
- if (!strncmp(version, supported_versions[i], size)) return 1;
- }
- return 0;
-}
-
-size_t grpc_chttp2_num_alpn_versions(void) {
- return GPR_ARRAY_SIZE(supported_versions);
-}
-
-const char* grpc_chttp2_get_alpn_version_index(size_t i) {
- GPR_ASSERT(i < GPR_ARRAY_SIZE(supported_versions));
- return supported_versions[i];
-}
+/*
+ *
+ * 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 <grpc/support/log.h>
+#include "src/core/ext/transport/chttp2/alpn/alpn.h"
+
+#include "src/core/lib/gpr/useful.h"
+
+/* in order of preference */
+static const char* const supported_versions[] = {"grpc-exp", "h2"};
+
+int grpc_chttp2_is_alpn_version_supported(const char* version, size_t size) {
+ size_t i;
+ for (i = 0; i < GPR_ARRAY_SIZE(supported_versions); i++) {
+ if (!strncmp(version, supported_versions[i], size)) return 1;
+ }
+ return 0;
+}
+
+size_t grpc_chttp2_num_alpn_versions(void) {
+ return GPR_ARRAY_SIZE(supported_versions);
+}
+
+const char* grpc_chttp2_get_alpn_version_index(size_t i) {
+ GPR_ASSERT(i < GPR_ARRAY_SIZE(supported_versions));
+ return supported_versions[i];
+}
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 e2ffe4e405e..31ffaaabe8a 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
@@ -1,36 +1,36 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_ALPN_ALPN_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_ALPN_ALPN_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <string.h>
/* Returns 1 if the version is supported, 0 otherwise. */
-int grpc_chttp2_is_alpn_version_supported(const char* version, size_t size);
+int grpc_chttp2_is_alpn_version_supported(const char* version, size_t size);
/* Returns the number of protocol versions to advertise */
size_t grpc_chttp2_num_alpn_versions(void);
/* Returns the protocol version at index i (0 <= i <
* grpc_chttp2_num_alpn_versions()) */
-const char* grpc_chttp2_get_alpn_version_index(size_t i);
+const char* grpc_chttp2_get_alpn_version_index(size_t i);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_ALPN_ALPN_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.cc
index bad3153b013..7da844816c2 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.cc
@@ -1,42 +1,42 @@
-/*
- *
- * 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/ext/transport/chttp2/client/authority.h"
-
-grpc_channel_args* grpc_default_authority_add_if_not_present(
- const grpc_channel_args* args) {
- const bool has_default_authority =
- grpc_channel_args_find(args, GRPC_ARG_DEFAULT_AUTHORITY) != nullptr;
- grpc_arg new_args[1];
- size_t num_new_args = 0;
- grpc_core::UniquePtr<char> default_authority;
- if (!has_default_authority) {
- const grpc_arg* server_uri_arg =
- grpc_channel_args_find(args, GRPC_ARG_SERVER_URI);
- const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg);
- GPR_ASSERT(server_uri_str != nullptr);
- default_authority =
- grpc_core::ResolverRegistry::GetDefaultAuthority(server_uri_str);
- GPR_ASSERT(default_authority != nullptr);
- new_args[num_new_args++] = grpc_channel_arg_string_create(
- const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY), default_authority.get());
- }
- return grpc_channel_args_copy_and_add(args, new_args, num_new_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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/transport/chttp2/client/authority.h"
+
+grpc_channel_args* grpc_default_authority_add_if_not_present(
+ const grpc_channel_args* args) {
+ const bool has_default_authority =
+ grpc_channel_args_find(args, GRPC_ARG_DEFAULT_AUTHORITY) != nullptr;
+ grpc_arg new_args[1];
+ size_t num_new_args = 0;
+ grpc_core::UniquePtr<char> default_authority;
+ if (!has_default_authority) {
+ const grpc_arg* server_uri_arg =
+ grpc_channel_args_find(args, GRPC_ARG_SERVER_URI);
+ const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg);
+ GPR_ASSERT(server_uri_str != nullptr);
+ default_authority =
+ grpc_core::ResolverRegistry::GetDefaultAuthority(server_uri_str);
+ GPR_ASSERT(default_authority != nullptr);
+ new_args[num_new_args++] = grpc_channel_arg_string_create(
+ const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY), default_authority.get());
+ }
+ return grpc_channel_args_copy_and_add(args, new_args, num_new_args);
+}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.h
index 642584ef566..51a776e2df5 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/authority.h
@@ -1,36 +1,36 @@
-/*
- *
- * 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_TRANSPORT_CHTTP2_CLIENT_AUTHORITY_H
-#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_AUTHORITY_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
-#include "src/core/ext/filters/client_channel/resolver_registry.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gprpp/memory.h"
-
-/// Returns a copy of \a args with the default authority channel arg set if it
-/// wasn't already present.
-grpc_channel_args* grpc_default_authority_add_if_not_present(
- const grpc_channel_args* args);
-
-#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_AUTHORITY_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_TRANSPORT_CHTTP2_CLIENT_AUTHORITY_H
+#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_AUTHORITY_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
+#include "src/core/ext/filters/client_channel/resolver_registry.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gprpp/memory.h"
+
+/// Returns a copy of \a args with the default authority channel arg set if it
+/// wasn't already present.
+grpc_channel_args* grpc_default_authority_add_if_not_present(
+ const grpc_channel_args* args);
+
+#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_AUTHORITY_H */
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 3408ed92675..5e9f2412096 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/transport/chttp2/client/chttp2_connector.h"
-
-#include <grpc/grpc.h>
-
-#include <string.h>
-
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/connector.h"
-#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
-#include "src/core/ext/filters/client_channel/subchannel.h"
-#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/handshaker.h"
-#include "src/core/lib/channel/handshaker_registry.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/slice/slice_internal.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/transport/chttp2/client/chttp2_connector.h"
+
+#include <grpc/grpc.h>
+
+#include <string.h>
+
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/connector.h"
+#include "src/core/ext/filters/client_channel/http_connect_handshaker.h"
+#include "src/core/ext/filters/client_channel/subchannel.h"
+#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/handshaker.h"
+#include "src/core/lib/channel/handshaker_registry.h"
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/slice/slice_internal.h"
+
namespace grpc_core {
-
+
Chttp2Connector::Chttp2Connector() {
GRPC_CLOSURE_INIT(&connected_, Connected, this, grpc_schedule_on_exec_ctx);
}
-
+
Chttp2Connector::~Chttp2Connector() {
if (endpoint_ != nullptr) grpc_endpoint_destroy(endpoint_);
-}
-
+}
+
void Chttp2Connector::Connect(const Args& args, Result* result,
grpc_closure* notify) {
grpc_resolved_address addr;
@@ -63,7 +63,7 @@ void Chttp2Connector::Connect(const Args& args, Result* result,
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
@@ -73,22 +73,22 @@ void Chttp2Connector::Connect(const Args& args, Result* result,
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));
- }
- // If handshaking is not yet in progress, shutdown the endpoint.
- // Otherwise, the handshaker will do this for us.
+ }
+ // 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));
- }
+ }
GRPC_ERROR_UNREF(error);
-}
-
+}
+
void Chttp2Connector::Connected(void* arg, grpc_error* error) {
Chttp2Connector* self = static_cast<Chttp2Connector*>(arg);
bool unref = false;
@@ -110,14 +110,14 @@ void Chttp2Connector::Connected(void* arg, grpc_error* error) {
self->notify_ = nullptr;
ExecCtx::Run(DEBUG_LOCATION, notify, error);
unref = true;
- } else {
+ } else {
GPR_ASSERT(self->endpoint_ != nullptr);
self->StartHandshakeLocked();
- }
- }
+ }
+ }
if (unref) self->Unref();
-}
-
+}
+
void Chttp2Connector::StartHandshakeLocked() {
handshake_mgr_ = MakeRefCounted<HandshakeManager>();
HandshakerRegistry::AddHandshakers(HANDSHAKER_CLIENT, args_.channel_args,
@@ -127,8 +127,8 @@ void Chttp2Connector::StartHandshakeLocked() {
handshake_mgr_->DoHandshake(endpoint_, args_.channel_args, args_.deadline,
nullptr /* acceptor */, OnHandshakeDone, this);
endpoint_ = nullptr; // Endpoint handed off to handshake manager.
-}
-
+}
+
namespace {
void NullThenSchedClosure(const DebugLocation& location, grpc_closure** closure,
grpc_error* error) {
@@ -182,18 +182,18 @@ void Chttp2Connector::OnHandshakeDone(void* arg, grpc_error* error) {
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 {
+ } 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);
NullThenSchedClosure(DEBUG_LOCATION, &self->notify_, error);
- }
+ }
self->handshake_mgr_.reset();
- }
+ }
self->Unref();
-}
-
+}
+
void Chttp2Connector::OnReceiveSettings(void* arg, grpc_error* error) {
Chttp2Connector* self = static_cast<Chttp2Connector*>(arg);
{
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 322cbc2eba4..c084d0821ea 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
@@ -1,30 +1,30 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_CLIENT_CHTTP2_CONNECTOR_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_CHTTP2_CONNECTOR_H
-#include <grpc/support/port_platform.h>
+#include <grpc/support/port_platform.h>
-#include "src/core/ext/filters/client_channel/connector.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"
-
+
namespace grpc_core {
class Chttp2Connector : public SubchannelConnector {
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 189ed7d1ce5..dd68157eeeb 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
-#include "src/core/ext/filters/client_channel/resolver_registry.h"
-#include "src/core/ext/transport/chttp2/client/authority.h"
-#include "src/core/ext/transport/chttp2/client/chttp2_connector.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/channel.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 <grpc/grpc.h>
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
+#include "src/core/ext/filters/client_channel/resolver_registry.h"
+#include "src/core/ext/transport/chttp2/client/authority.h"
+#include "src/core/ext/transport/chttp2/client/chttp2_connector.h"
+#include "src/core/lib/channel/channel_args.h"
+#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 {
@@ -46,32 +46,32 @@ class Chttp2InsecureClientChannelFactory : public ClientChannelFactory {
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 =
+ 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());
- 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);
- grpc_channel* channel =
- grpc_channel_create(target, new_args, GRPC_CLIENT_CHANNEL, nullptr);
- grpc_channel_args_destroy(new_args);
- return channel;
-}
-
+ 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);
+ grpc_channel* channel =
+ grpc_channel_create(target, new_args, GRPC_CLIENT_CHANNEL, nullptr);
+ grpc_channel_args_destroy(new_args);
+ return channel;
+}
+
} // namespace
-
+
} // namespace grpc_core
-
+
namespace {
grpc_core::Chttp2InsecureClientChannelFactory* g_factory;
@@ -83,30 +83,30 @@ void FactoryInit() {
} // namespace
-/* Create a client channel:
- Asynchronously: - resolve target
- - connect to it (trying alternatives as presented)
- - perform handshakes */
-grpc_channel* grpc_insecure_channel_create(const char* target,
- const grpc_channel_args* args,
- void* reserved) {
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE(
- "grpc_insecure_channel_create(target=%s, args=%p, reserved=%p)", 3,
- (target, args, reserved));
- GPR_ASSERT(reserved == nullptr);
- // Add channel arg containing the client channel factory.
+/* Create a client channel:
+ Asynchronously: - resolve target
+ - connect to it (trying alternatives as presented)
+ - perform handshakes */
+grpc_channel* grpc_insecure_channel_create(const char* target,
+ const grpc_channel_args* args,
+ void* reserved) {
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE(
+ "grpc_insecure_channel_create(target=%s, args=%p, reserved=%p)", 3,
+ (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);
- // Create channel.
+ // Create channel.
grpc_channel* channel = grpc_core::CreateChannel(target, new_args);
- // Clean up.
- grpc_channel_args_destroy(new_args);
- return channel != nullptr ? channel
- : grpc_lame_client_channel_create(
- target, GRPC_STATUS_INTERNAL,
- "Failed to create client channel");
-}
+ // Clean up.
+ grpc_channel_args_destroy(new_args);
+ return channel != nullptr ? channel
+ : grpc_lame_client_channel_create(
+ target, GRPC_STATUS_INTERNAL,
+ "Failed to create client channel");
+}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc
index 5bdcb387c9b..0cf8d0b2351 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc
@@ -1,79 +1,79 @@
-/*
- *
- * 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 <grpc/grpc.h>
-#include <grpc/grpc_posix.h>
-#include <grpc/support/log.h>
-
-#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
-
-#include <fcntl.h>
-
-#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/iomgr/endpoint.h"
-#include "src/core/lib/iomgr/tcp_client_posix.h"
-#include "src/core/lib/iomgr/tcp_posix.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/channel.h"
-#include "src/core/lib/transport/transport.h"
-
-grpc_channel* grpc_insecure_channel_create_from_fd(
- const char* target, int fd, const grpc_channel_args* args) {
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE("grpc_insecure_channel_create(target=%p, fd=%d, args=%p)", 3,
- (target, fd, args));
-
- grpc_arg default_authority_arg = grpc_channel_arg_string_create(
- (char*)GRPC_ARG_DEFAULT_AUTHORITY, (char*)"test.authority");
- grpc_channel_args* final_args =
- grpc_channel_args_copy_and_add(args, &default_authority_arg, 1);
-
- int flags = fcntl(fd, F_GETFL, 0);
- GPR_ASSERT(fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0);
-
- grpc_endpoint* client = grpc_tcp_client_create_from_fd(
+/*
+ *
+ * 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 <grpc/grpc.h>
+#include <grpc/grpc_posix.h>
+#include <grpc/support/log.h>
+
+#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
+
+#include <fcntl.h>
+
+#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/tcp_client_posix.h"
+#include "src/core/lib/iomgr/tcp_posix.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/transport/transport.h"
+
+grpc_channel* grpc_insecure_channel_create_from_fd(
+ const char* target, int fd, const grpc_channel_args* args) {
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE("grpc_insecure_channel_create(target=%p, fd=%d, args=%p)", 3,
+ (target, fd, args));
+
+ grpc_arg default_authority_arg = grpc_channel_arg_string_create(
+ (char*)GRPC_ARG_DEFAULT_AUTHORITY, (char*)"test.authority");
+ grpc_channel_args* final_args =
+ grpc_channel_args_copy_and_add(args, &default_authority_arg, 1);
+
+ int flags = fcntl(fd, F_GETFL, 0);
+ GPR_ASSERT(fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0);
+
+ grpc_endpoint* client = grpc_tcp_client_create_from_fd(
grpc_fd_create(fd, "client", true), args, "fd-client");
-
- grpc_transport* transport =
- grpc_create_chttp2_transport(final_args, client, true);
- GPR_ASSERT(transport);
- grpc_channel* channel = grpc_channel_create(
- target, final_args, GRPC_CLIENT_DIRECT_CHANNEL, transport);
- grpc_channel_args_destroy(final_args);
- grpc_chttp2_transport_start_reading(transport, nullptr, nullptr);
-
- grpc_core::ExecCtx::Get()->Flush();
-
- return channel != nullptr ? channel
- : grpc_lame_client_channel_create(
- target, GRPC_STATUS_INTERNAL,
- "Failed to create client channel");
-}
-
-#else // !GPR_SUPPORT_CHANNELS_FROM_FD
-
-grpc_channel* grpc_insecure_channel_create_from_fd(
- const char* target, int fd, const grpc_channel_args* args) {
- GPR_ASSERT(0);
- return nullptr;
-}
-
-#endif // GPR_SUPPORT_CHANNELS_FROM_FD
+
+ grpc_transport* transport =
+ grpc_create_chttp2_transport(final_args, client, true);
+ GPR_ASSERT(transport);
+ grpc_channel* channel = grpc_channel_create(
+ target, final_args, GRPC_CLIENT_DIRECT_CHANNEL, transport);
+ grpc_channel_args_destroy(final_args);
+ grpc_chttp2_transport_start_reading(transport, nullptr, nullptr);
+
+ grpc_core::ExecCtx::Get()->Flush();
+
+ return channel != nullptr ? channel
+ : grpc_lame_client_channel_create(
+ target, GRPC_STATUS_INTERNAL,
+ "Failed to create client channel");
+}
+
+#else // !GPR_SUPPORT_CHANNELS_FROM_FD
+
+grpc_channel* grpc_insecure_channel_create_from_fd(
+ const char* target, int fd, const grpc_channel_args* args) {
+ GPR_ASSERT(0);
+ return nullptr;
+}
+
+#endif // GPR_SUPPORT_CHANNELS_FROM_FD
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 93dadf36456..55e4c281ecd 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
@@ -1,46 +1,46 @@
-/*
- *
- * 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 <grpc/grpc.h>
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/filters/client_channel/client_channel.h"
-#include "src/core/ext/filters/client_channel/resolver_registry.h"
-#include "src/core/ext/transport/chttp2/client/chttp2_connector.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/security/credentials/credentials.h"
-#include "src/core/lib/security/security_connector/security_connector.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/channel.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 <grpc/grpc.h>
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/filters/client_channel/client_channel.h"
+#include "src/core/ext/filters/client_channel/resolver_registry.h"
+#include "src/core/ext/transport/chttp2/client/chttp2_connector.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/security/credentials/credentials.h"
+#include "src/core/lib/security/security_connector/security_connector.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/channel.h"
#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 {
@@ -55,7 +55,7 @@ class Chttp2SecureClientChannelFactory : public ClientChannelFactory {
grpc_channel_args_destroy(new_args);
return s;
}
-
+
private:
static grpc_channel_args* GetSecureNamingChannelArgs(
const grpc_channel_args* args) {
@@ -66,7 +66,7 @@ class Chttp2SecureClientChannelFactory : public ClientChannelFactory {
"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,
@@ -120,36 +120,36 @@ class Chttp2SecureClientChannelFactory : public ClientChannelFactory {
if (new_args_from_connector != nullptr) {
grpc_channel_args_destroy(new_args_from_connector);
}
- grpc_channel_args_destroy(args_with_authority);
+ grpc_channel_args_destroy(args_with_authority);
return new_args;
- }
+ }
};
-
+
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 =
+ 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());
- 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);
- grpc_channel* channel =
- grpc_channel_create(target, new_args, GRPC_CLIENT_CHANNEL, nullptr);
- grpc_channel_args_destroy(new_args);
- return channel;
-}
-
+ 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);
+ grpc_channel* channel =
+ grpc_channel_create(target, new_args, GRPC_CLIENT_CHANNEL, nullptr);
+ grpc_channel_args_destroy(new_args);
+ return channel;
+}
+
} // namespace
-
+
} // namespace grpc_core
-
+
namespace {
grpc_core::Chttp2SecureClientChannelFactory* g_factory;
@@ -161,24 +161,24 @@ void FactoryInit() {
} // namespace
-// Create a secure client channel:
-// Asynchronously: - resolve target
-// - connect to it (trying alternatives as presented)
-// - perform handshakes
-grpc_channel* grpc_secure_channel_create(grpc_channel_credentials* creds,
- const char* target,
- const grpc_channel_args* args,
- void* reserved) {
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE(
- "grpc_secure_channel_create(creds=%p, target=%s, args=%p, "
- "reserved=%p)",
- 4, ((void*)creds, target, (void*)args, (void*)reserved));
- GPR_ASSERT(reserved == nullptr);
- grpc_channel* channel = nullptr;
- if (creds != nullptr) {
- // Add channel args containing the client channel factory and channel
- // credentials.
+// Create a secure client channel:
+// Asynchronously: - resolve target
+// - connect to it (trying alternatives as presented)
+// - perform handshakes
+grpc_channel* grpc_secure_channel_create(grpc_channel_credentials* creds,
+ const char* target,
+ const grpc_channel_args* args,
+ void* reserved) {
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE(
+ "grpc_secure_channel_create(creds=%p, target=%s, args=%p, "
+ "reserved=%p)",
+ 4, ((void*)creds, target, (void*)args, (void*)reserved));
+ GPR_ASSERT(reserved == nullptr);
+ grpc_channel* channel = nullptr;
+ 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);
@@ -188,13 +188,13 @@ grpc_channel* grpc_secure_channel_create(grpc_channel_credentials* creds,
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.
+ // Create channel.
channel = grpc_core::CreateChannel(target, new_args);
- // Clean up.
- grpc_channel_args_destroy(new_args);
- }
- return channel != nullptr ? channel
- : grpc_lame_client_channel_create(
- target, GRPC_STATUS_INTERNAL,
- "Failed to create secure client channel");
-}
+ // Clean up.
+ grpc_channel_args_destroy(new_args);
+ }
+ return channel != nullptr ? channel
+ : grpc_lame_client_channel_create(
+ target, GRPC_STATUS_INTERNAL,
+ "Failed to create secure client channel");
+}
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 94cf61310bc..95945579848 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
@@ -1,58 +1,58 @@
-/*
- *
- * 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/transport/chttp2/server/chttp2_server.h"
-
-#include <inttypes.h>
-#include <limits.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/transport/chttp2/server/chttp2_server.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <string.h>
#include <vector>
-
+
#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/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/ext/filters/http/server/http_server_filter.h"
-#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/handshaker.h"
-#include "src/core/lib/channel/handshaker_registry.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/ext/filters/http/server/http_server_filter.h"
+#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/handshaker.h"
+#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/endpoint.h"
-#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/iomgr/resource_quota.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/server.h"
-
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/server.h"
+
namespace grpc_core {
namespace {
-
+
class Chttp2ServerListener : public Server::ListenerInterface {
public:
static grpc_error* Create(Server* server, const char* addr,
@@ -126,7 +126,7 @@ class Chttp2ServerListener : public Server::ListenerInterface {
HandshakeManager* pending_handshake_mgrs_ = nullptr;
RefCountedPtr<channelz::ListenSocketNode> channelz_listen_socket_;
};
-
+
//
// Chttp2ServerListener::ConnectionState
//
@@ -159,34 +159,34 @@ Chttp2ServerListener::ConnectionState::ConnectionState(
Chttp2ServerListener::ConnectionState::~ConnectionState() {
if (transport_ != nullptr) {
GRPC_CHTTP2_UNREF_TRANSPORT(transport_, "receive settings timeout");
- }
+ }
grpc_pollset_set_del_pollset(interested_parties_, accepting_pollset_);
grpc_pollset_set_destroy(interested_parties_);
-}
-
+}
+
void Chttp2ServerListener::ConnectionState::OnTimeout(void* arg,
grpc_error* error) {
ConnectionState* self = static_cast<ConnectionState*>(arg);
- // Note that we may be called with GRPC_ERROR_NONE when the timer fires
- // or with an error indicating that the timer system is being shut down.
- if (error != GRPC_ERROR_CANCELLED) {
- grpc_transport_op* op = grpc_make_transport_op(nullptr);
- op->disconnect_with_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Did not receive HTTP/2 settings before handshake timeout");
+ // Note that we may be called with GRPC_ERROR_NONE when the timer fires
+ // or with an error indicating that the timer system is being shut down.
+ if (error != GRPC_ERROR_CANCELLED) {
+ grpc_transport_op* op = grpc_make_transport_op(nullptr);
+ op->disconnect_with_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Did not receive HTTP/2 settings before handshake timeout");
grpc_transport_perform_op(&self->transport_->base, op);
- }
+ }
self->Unref();
-}
-
+}
+
void Chttp2ServerListener::ConnectionState::OnReceiveSettings(
void* arg, grpc_error* error) {
ConnectionState* self = static_cast<ConnectionState*>(arg);
- if (error == GRPC_ERROR_NONE) {
+ if (error == GRPC_ERROR_NONE) {
grpc_timer_cancel(&self->timer_);
- }
+ }
self->Unref();
-}
-
+}
+
void Chttp2ServerListener::ConnectionState::OnHandshakeDone(void* arg,
grpc_error* error) {
auto* args = static_cast<HandshakerArgs*>(arg);
@@ -253,16 +253,16 @@ void Chttp2ServerListener::ConnectionState::OnHandshakeDone(void* arg,
GRPC_RESOURCE_QUOTA_CHANNEL_SIZE);
}
}
- }
+ }
self->handshake_mgr_->RemoveFromPendingMgrList(
&self->listener_->pending_handshake_mgrs_);
- }
+ }
self->handshake_mgr_.reset();
gpr_free(self->acceptor_);
grpc_tcp_server_unref(self->listener_->tcp_server_);
self->Unref();
-}
-
+}
+
//
// Chttp2ServerListener
//
@@ -329,7 +329,7 @@ grpc_error* Chttp2ServerListener::Create(Server* server, const char* addr,
}();
if (resolved != nullptr) {
grpc_resolved_addresses_destroy(resolved);
- }
+ }
if (error != GRPC_ERROR_NONE) {
if (listener != nullptr) {
if (listener->tcp_server_ != nullptr) {
@@ -424,12 +424,12 @@ void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp,
// Deletes itself when done.
new ConnectionState(self, accepting_pollset, acceptor,
std::move(handshake_mgr), self->args_, tcp);
-}
-
+}
+
void Chttp2ServerListener::TcpServerShutdownComplete(void* arg,
grpc_error* error) {
Chttp2ServerListener* self = static_cast<Chttp2ServerListener*>(arg);
- /* ensure all threads have unlocked */
+ /* ensure all threads have unlocked */
grpc_closure* destroy_done = nullptr;
{
MutexLock lock(&self->mu_);
@@ -440,18 +440,18 @@ void Chttp2ServerListener::TcpServerShutdownComplete(void* arg,
}
self->channelz_listen_socket_.reset();
}
- // Flush queued work before destroying handshaker factory, since that
- // may do a synchronous unref.
+ // Flush queued work before destroying handshaker factory, since that
+ // may do a synchronous unref.
ExecCtx::Get()->Flush();
- if (destroy_done != nullptr) {
+ if (destroy_done != nullptr) {
ExecCtx::Run(DEBUG_LOCATION, destroy_done, GRPC_ERROR_REF(error));
ExecCtx::Get()->Flush();
- }
+ }
delete self;
-}
-
-/* Server callback: destroy the tcp listener (so we don't generate further
- callbacks) */
+}
+
+/* Server callback: destroy the tcp listener (so we don't generate further
+ callbacks) */
void Chttp2ServerListener::Orphan() {
grpc_tcp_server* tcp_server;
{
@@ -459,10 +459,10 @@ void Chttp2ServerListener::Orphan() {
shutdown_ = true;
tcp_server = tcp_server_;
}
- grpc_tcp_server_shutdown_listeners(tcp_server);
- grpc_tcp_server_unref(tcp_server);
-}
-
+ grpc_tcp_server_shutdown_listeners(tcp_server);
+ grpc_tcp_server_unref(tcp_server);
+}
+
} // namespace
//
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.h
index 095cc5e4c04..204ea02b745 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.h
@@ -1,29 +1,29 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/grpc_types.h>
-#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/surface/server.h"
namespace grpc_core {
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc
index eebae9efaa9..4d6f02225c5 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2.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 <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/ext/transport/chttp2/server/chttp2_server.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/server.h"
-
-int grpc_server_add_insecure_http2_port(grpc_server* server, const char* addr) {
- grpc_core::ExecCtx exec_ctx;
- int port_num = 0;
- GRPC_API_TRACE("grpc_server_add_insecure_http2_port(server=%p, addr=%s)", 2,
- (server, addr));
+/*
+ *
+ * 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 <grpc/grpc.h>
+
+#include <grpc/support/log.h>
+
+#include "src/core/ext/transport/chttp2/server/chttp2_server.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/server.h"
+
+int grpc_server_add_insecure_http2_port(grpc_server* server, const char* addr) {
+ grpc_core::ExecCtx exec_ctx;
+ int port_num = 0;
+ GRPC_API_TRACE("grpc_server_add_insecure_http2_port(server=%p, addr=%s)", 2,
+ (server, addr));
grpc_error* err = grpc_core::Chttp2ServerAddPort(
server->core_server.get(), addr,
grpc_channel_args_copy(server->core_server->channel_args()), &port_num);
- if (err != GRPC_ERROR_NONE) {
- const char* msg = grpc_error_string(err);
- gpr_log(GPR_ERROR, "%s", msg);
-
- GRPC_ERROR_UNREF(err);
- }
- return port_num;
-}
+ if (err != GRPC_ERROR_NONE) {
+ const char* msg = grpc_error_string(err);
+ gpr_log(GPR_ERROR, "%s", msg);
+
+ GRPC_ERROR_UNREF(err);
+ }
+ return port_num;
+}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc
index 33086bd6020..502712b17f7 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc
@@ -1,69 +1,69 @@
-/*
- *
- * 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 <grpc/grpc.h>
-#include <grpc/grpc_posix.h>
-#include <grpc/support/log.h>
-
-#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
-
+/*
+ *
+ * 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 <grpc/grpc.h>
+#include <grpc/grpc_posix.h>
+#include <grpc/support/log.h>
+
+#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-
-#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/iomgr/endpoint.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/tcp_posix.h"
-#include "src/core/lib/surface/completion_queue.h"
-#include "src/core/lib/surface/server.h"
-
-void grpc_server_add_insecure_channel_from_fd(grpc_server* server,
- void* reserved, int fd) {
- GPR_ASSERT(reserved == nullptr);
-
- grpc_core::ExecCtx exec_ctx;
+#include <grpc/support/alloc.h>
+
+#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/tcp_posix.h"
+#include "src/core/lib/surface/completion_queue.h"
+#include "src/core/lib/surface/server.h"
+
+void grpc_server_add_insecure_channel_from_fd(grpc_server* server,
+ void* reserved, int fd) {
+ GPR_ASSERT(reserved == nullptr);
+
+ grpc_core::ExecCtx exec_ctx;
grpc_core::Server* core_server = server->core_server.get();
-
+
const grpc_channel_args* server_args = core_server->channel_args();
TString name = y_absl::StrCat("fd:", fd);
grpc_endpoint* server_endpoint = grpc_tcp_create(
grpc_fd_create(fd, name.c_str(), true), server_args, name.c_str());
-
- grpc_transport* transport = grpc_create_chttp2_transport(
- server_args, server_endpoint, false /* is_client */);
-
+
+ grpc_transport* transport = grpc_create_chttp2_transport(
+ server_args, server_endpoint, false /* is_client */);
+
for (grpc_pollset* pollset : core_server->pollsets()) {
grpc_endpoint_add_to_pollset(server_endpoint, pollset);
- }
-
+ }
+
core_server->SetupTransport(transport, nullptr, server_args, nullptr);
- grpc_chttp2_transport_start_reading(transport, nullptr, nullptr);
-}
-
-#else // !GPR_SUPPORT_CHANNELS_FROM_FD
-
-void grpc_server_add_insecure_channel_from_fd(grpc_server* server,
- void* reserved, int fd) {
- GPR_ASSERT(0);
-}
-
-#endif // GPR_SUPPORT_CHANNELS_FROM_FD
+ grpc_chttp2_transport_start_reading(transport, nullptr, nullptr);
+}
+
+#else // !GPR_SUPPORT_CHANNELS_FROM_FD
+
+void grpc_server_add_insecure_channel_from_fd(grpc_server* server,
+ void* reserved, int fd) {
+ GPR_ASSERT(0);
+}
+
+#endif // GPR_SUPPORT_CHANNELS_FROM_FD
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc
index c49e1511a57..11b6062a149 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc
@@ -1,86 +1,86 @@
-/*
- *
- * 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 <grpc/grpc.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 <grpc/grpc.h>
+
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/ext/transport/chttp2/server/chttp2_server.h"
-
-#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/handshaker.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/ext/transport/chttp2/server/chttp2_server.h"
+
+#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/handshaker.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"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/server.h"
-
-int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr,
- grpc_server_credentials* creds) {
- grpc_core::ExecCtx exec_ctx;
- grpc_error* err = GRPC_ERROR_NONE;
+#include "src/core/lib/security/context/security_context.h"
+#include "src/core/lib/security/credentials/credentials.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/server.h"
+
+int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr,
+ grpc_server_credentials* creds) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_error* err = GRPC_ERROR_NONE;
grpc_core::RefCountedPtr<grpc_server_security_connector> sc;
- int port_num = 0;
- grpc_channel_args* args = nullptr;
- GRPC_API_TRACE(
- "grpc_server_add_secure_http2_port("
- "server=%p, addr=%s, creds=%p)",
- 3, (server, addr, creds));
- // Create security context.
- if (creds == nullptr) {
- err = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "No credentials specified for secure server port (creds==NULL)");
- goto done;
- }
+ int port_num = 0;
+ grpc_channel_args* args = nullptr;
+ GRPC_API_TRACE(
+ "grpc_server_add_secure_http2_port("
+ "server=%p, addr=%s, creds=%p)",
+ 3, (server, addr, creds));
+ // Create security context.
+ if (creds == nullptr) {
+ err = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "No credentials specified for secure server port (creds==NULL)");
+ goto done;
+ }
sc = creds->create_security_connector();
if (sc == nullptr) {
err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Unable to create secure server with credentials of type ",
creds->type())
.c_str());
- goto done;
- }
- // Create channel args.
- grpc_arg args_to_add[2];
- args_to_add[0] = grpc_server_credentials_to_arg(creds);
+ goto done;
+ }
+ // Create channel args.
+ grpc_arg args_to_add[2];
+ args_to_add[0] = grpc_server_credentials_to_arg(creds);
args_to_add[1] = grpc_security_connector_to_arg(sc.get());
- args =
+ args =
grpc_channel_args_copy_and_add(server->core_server->channel_args(),
- args_to_add, GPR_ARRAY_SIZE(args_to_add));
- // Add server port.
+ args_to_add, GPR_ARRAY_SIZE(args_to_add));
+ // Add server port.
err = grpc_core::Chttp2ServerAddPort(server->core_server.get(), addr, args,
&port_num);
-done:
+done:
sc.reset(DEBUG_LOCATION, "server");
-
- if (err != GRPC_ERROR_NONE) {
- const char* msg = grpc_error_string(err);
- gpr_log(GPR_ERROR, "%s", msg);
-
- GRPC_ERROR_UNREF(err);
- }
- return port_num;
-}
+
+ if (err != GRPC_ERROR_NONE) {
+ const char* msg = grpc_error_string(err);
+ gpr_log(GPR_ERROR, "%s", msg);
+
+ GRPC_ERROR_UNREF(err);
+ }
+ return port_num;
+}
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 249035d7e89..c2853b3d8a9 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
@@ -1,250 +1,250 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include "src/core/ext/transport/chttp2/transport/bin_decoder.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-
-static uint8_t decode_table[] = {
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 62, 0x40, 0x40, 0x40, 63,
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0, 1, 2, 3, 4, 5, 6,
- 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
- 19, 20, 21, 22, 23, 24, 25, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
- 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
- 49, 50, 51, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
- 0x40, 0x40, 0x40, 0x40};
-
-static const uint8_t tail_xtra[4] = {0, 0, 1, 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include "src/core/ext/transport/chttp2/transport/bin_decoder.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+
+static uint8_t decode_table[] = {
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 62, 0x40, 0x40, 0x40, 63,
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0, 1, 2, 3, 4, 5, 6,
+ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
+ 19, 20, 21, 22, 23, 24, 25, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
+ 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
+ 49, 50, 51, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
+ 0x40, 0x40, 0x40, 0x40};
+
+static const uint8_t tail_xtra[4] = {0, 0, 1, 2};
+
static bool input_is_valid(const uint8_t* input_ptr, size_t length) {
- size_t i;
-
- for (i = 0; i < length; ++i) {
+ size_t i;
+
+ for (i = 0; i < length; ++i) {
if (GPR_UNLIKELY((decode_table[input_ptr[i]] & 0xC0) != 0)) {
- gpr_log(GPR_ERROR,
- "Base64 decoding failed, invalid character '%c' in base64 "
- "input.\n",
- static_cast<char>(*input_ptr));
- return false;
- }
- }
- return true;
-}
-
-#define COMPOSE_OUTPUT_BYTE_0(input_ptr) \
- (uint8_t)((decode_table[input_ptr[0]] << 2) | \
- (decode_table[input_ptr[1]] >> 4))
-
-#define COMPOSE_OUTPUT_BYTE_1(input_ptr) \
- (uint8_t)((decode_table[input_ptr[1]] << 4) | \
- (decode_table[input_ptr[2]] >> 2))
-
-#define COMPOSE_OUTPUT_BYTE_2(input_ptr) \
- (uint8_t)((decode_table[input_ptr[2]] << 6) | decode_table[input_ptr[3]])
-
-// By RFC 4648, if the length of the encoded string without padding is 4n+r,
-// the length of decoded string is: 1) 3n if r = 0, 2) 3n + 1 if r = 2, 3, or
-// 3) invalid if r = 1.
-size_t grpc_chttp2_base64_infer_length_after_decode(const grpc_slice& slice) {
- size_t len = GRPC_SLICE_LENGTH(slice);
- const uint8_t* bytes = GRPC_SLICE_START_PTR(slice);
- while (len > 0 && bytes[len - 1] == '=') {
- len--;
- }
+ gpr_log(GPR_ERROR,
+ "Base64 decoding failed, invalid character '%c' in base64 "
+ "input.\n",
+ static_cast<char>(*input_ptr));
+ return false;
+ }
+ }
+ return true;
+}
+
+#define COMPOSE_OUTPUT_BYTE_0(input_ptr) \
+ (uint8_t)((decode_table[input_ptr[0]] << 2) | \
+ (decode_table[input_ptr[1]] >> 4))
+
+#define COMPOSE_OUTPUT_BYTE_1(input_ptr) \
+ (uint8_t)((decode_table[input_ptr[1]] << 4) | \
+ (decode_table[input_ptr[2]] >> 2))
+
+#define COMPOSE_OUTPUT_BYTE_2(input_ptr) \
+ (uint8_t)((decode_table[input_ptr[2]] << 6) | decode_table[input_ptr[3]])
+
+// By RFC 4648, if the length of the encoded string without padding is 4n+r,
+// the length of decoded string is: 1) 3n if r = 0, 2) 3n + 1 if r = 2, 3, or
+// 3) invalid if r = 1.
+size_t grpc_chttp2_base64_infer_length_after_decode(const grpc_slice& slice) {
+ size_t len = GRPC_SLICE_LENGTH(slice);
+ const uint8_t* bytes = GRPC_SLICE_START_PTR(slice);
+ while (len > 0 && bytes[len - 1] == '=') {
+ len--;
+ }
if (GPR_UNLIKELY(GRPC_SLICE_LENGTH(slice) - len > 2)) {
- gpr_log(GPR_ERROR,
- "Base64 decoding failed. Input has more than 2 paddings.");
- return 0;
- }
- size_t tuples = len / 4;
- size_t tail_case = len % 4;
+ gpr_log(GPR_ERROR,
+ "Base64 decoding failed. Input has more than 2 paddings.");
+ return 0;
+ }
+ size_t tuples = len / 4;
+ size_t tail_case = len % 4;
if (GPR_UNLIKELY(tail_case == 1)) {
- gpr_log(GPR_ERROR,
- "Base64 decoding failed. Input has a length of %zu (without"
- " padding), which is invalid.\n",
- len);
- return 0;
- }
- return tuples * 3 + tail_xtra[tail_case];
-}
-
-bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx) {
- size_t input_tail;
-
- if (ctx->input_cur > ctx->input_end || ctx->output_cur > ctx->output_end) {
- return false;
- }
-
- // Process a block of 4 input characters and 3 output bytes
- while (ctx->input_end >= ctx->input_cur + 4 &&
- ctx->output_end >= ctx->output_cur + 3) {
- if (!input_is_valid(ctx->input_cur, 4)) return false;
- ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
- ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur);
- ctx->output_cur[2] = COMPOSE_OUTPUT_BYTE_2(ctx->input_cur);
- ctx->output_cur += 3;
- ctx->input_cur += 4;
- }
-
- // Process the tail of input data
- input_tail = static_cast<size_t>(ctx->input_end - ctx->input_cur);
- if (input_tail == 4) {
- // Process the input data with pad chars
- if (ctx->input_cur[3] == '=') {
- if (ctx->input_cur[2] == '=' && ctx->output_end >= ctx->output_cur + 1) {
- if (!input_is_valid(ctx->input_cur, 2)) return false;
- *(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
- ctx->input_cur += 4;
- } else if (ctx->output_end >= ctx->output_cur + 2) {
- if (!input_is_valid(ctx->input_cur, 3)) return false;
- *(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
- *(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur);
- ;
- ctx->input_cur += 4;
- }
- }
-
- } else if (ctx->contains_tail && input_tail > 1) {
- // Process the input data without pad chars, but constains_tail is set
- if (ctx->output_end >= ctx->output_cur + tail_xtra[input_tail]) {
- if (!input_is_valid(ctx->input_cur, input_tail)) return false;
- switch (input_tail) {
- case 3:
- ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur);
- /* fallthrough */
- case 2:
- ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
- }
- ctx->output_cur += tail_xtra[input_tail];
- ctx->input_cur += input_tail;
- }
- }
-
- return true;
-}
-
+ gpr_log(GPR_ERROR,
+ "Base64 decoding failed. Input has a length of %zu (without"
+ " padding), which is invalid.\n",
+ len);
+ return 0;
+ }
+ return tuples * 3 + tail_xtra[tail_case];
+}
+
+bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx) {
+ size_t input_tail;
+
+ if (ctx->input_cur > ctx->input_end || ctx->output_cur > ctx->output_end) {
+ return false;
+ }
+
+ // Process a block of 4 input characters and 3 output bytes
+ while (ctx->input_end >= ctx->input_cur + 4 &&
+ ctx->output_end >= ctx->output_cur + 3) {
+ if (!input_is_valid(ctx->input_cur, 4)) return false;
+ ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
+ ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur);
+ ctx->output_cur[2] = COMPOSE_OUTPUT_BYTE_2(ctx->input_cur);
+ ctx->output_cur += 3;
+ ctx->input_cur += 4;
+ }
+
+ // Process the tail of input data
+ input_tail = static_cast<size_t>(ctx->input_end - ctx->input_cur);
+ if (input_tail == 4) {
+ // Process the input data with pad chars
+ if (ctx->input_cur[3] == '=') {
+ if (ctx->input_cur[2] == '=' && ctx->output_end >= ctx->output_cur + 1) {
+ if (!input_is_valid(ctx->input_cur, 2)) return false;
+ *(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
+ ctx->input_cur += 4;
+ } else if (ctx->output_end >= ctx->output_cur + 2) {
+ if (!input_is_valid(ctx->input_cur, 3)) return false;
+ *(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
+ *(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur);
+ ;
+ ctx->input_cur += 4;
+ }
+ }
+
+ } else if (ctx->contains_tail && input_tail > 1) {
+ // Process the input data without pad chars, but constains_tail is set
+ if (ctx->output_end >= ctx->output_cur + tail_xtra[input_tail]) {
+ if (!input_is_valid(ctx->input_cur, input_tail)) return false;
+ switch (input_tail) {
+ case 3:
+ ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur);
+ /* fallthrough */
+ case 2:
+ ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur);
+ }
+ ctx->output_cur += tail_xtra[input_tail];
+ ctx->input_cur += input_tail;
+ }
+ }
+
+ return true;
+}
+
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;
- grpc_slice output;
-
+ size_t input_length = GRPC_SLICE_LENGTH(input);
+ size_t output_length = input_length / 4 * 3;
+ struct grpc_base64_decode_context ctx;
+ grpc_slice output;
+
if (GPR_UNLIKELY(input_length % 4 != 0)) {
- gpr_log(GPR_ERROR,
- "Base64 decoding failed, input of "
- "grpc_chttp2_base64_decode has a length of %d, which is not a "
- "multiple of 4.\n",
- static_cast<int>(input_length));
- return grpc_empty_slice();
- }
-
- if (input_length > 0) {
+ gpr_log(GPR_ERROR,
+ "Base64 decoding failed, input of "
+ "grpc_chttp2_base64_decode has a length of %d, which is not a "
+ "multiple of 4.\n",
+ static_cast<int>(input_length));
+ return grpc_empty_slice();
+ }
+
+ if (input_length > 0) {
const uint8_t* input_end = GRPC_SLICE_END_PTR(input);
- if (*(--input_end) == '=') {
- output_length--;
- if (*(--input_end) == '=') {
- output_length--;
- }
- }
- }
- output = GRPC_SLICE_MALLOC(output_length);
-
- ctx.input_cur = GRPC_SLICE_START_PTR(input);
- ctx.input_end = GRPC_SLICE_END_PTR(input);
- ctx.output_cur = GRPC_SLICE_START_PTR(output);
- ctx.output_end = GRPC_SLICE_END_PTR(output);
- ctx.contains_tail = false;
-
+ if (*(--input_end) == '=') {
+ output_length--;
+ if (*(--input_end) == '=') {
+ output_length--;
+ }
+ }
+ }
+ output = GRPC_SLICE_MALLOC(output_length);
+
+ ctx.input_cur = GRPC_SLICE_START_PTR(input);
+ ctx.input_end = GRPC_SLICE_END_PTR(input);
+ ctx.output_cur = GRPC_SLICE_START_PTR(output);
+ ctx.output_end = GRPC_SLICE_END_PTR(output);
+ ctx.contains_tail = false;
+
if (GPR_UNLIKELY(!grpc_base64_decode_partial(&ctx))) {
- char* s = grpc_slice_to_c_string(input);
- gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s);
- gpr_free(s);
- grpc_slice_unref_internal(output);
- return grpc_empty_slice();
- }
- GPR_ASSERT(ctx.output_cur == GRPC_SLICE_END_PTR(output));
- GPR_ASSERT(ctx.input_cur == GRPC_SLICE_END_PTR(input));
- return output;
-}
-
+ char* s = grpc_slice_to_c_string(input);
+ gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s);
+ gpr_free(s);
+ grpc_slice_unref_internal(output);
+ return grpc_empty_slice();
+ }
+ GPR_ASSERT(ctx.output_cur == GRPC_SLICE_END_PTR(output));
+ GPR_ASSERT(ctx.input_cur == GRPC_SLICE_END_PTR(input));
+ return output;
+}
+
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);
- struct grpc_base64_decode_context ctx;
-
- // The length of a base64 string cannot be 4 * n + 1
+ size_t output_length) {
+ size_t input_length = GRPC_SLICE_LENGTH(input);
+ grpc_slice output = GRPC_SLICE_MALLOC(output_length);
+ struct grpc_base64_decode_context ctx;
+
+ // The length of a base64 string cannot be 4 * n + 1
if (GPR_UNLIKELY(input_length % 4 == 1)) {
- gpr_log(GPR_ERROR,
- "Base64 decoding failed, input of "
- "grpc_chttp2_base64_decode_with_length has a length of %d, which "
- "has a tail of 1 byte.\n",
- static_cast<int>(input_length));
- grpc_slice_unref_internal(output);
- return grpc_empty_slice();
- }
-
+ gpr_log(GPR_ERROR,
+ "Base64 decoding failed, input of "
+ "grpc_chttp2_base64_decode_with_length has a length of %d, which "
+ "has a tail of 1 byte.\n",
+ static_cast<int>(input_length));
+ grpc_slice_unref_internal(output);
+ return grpc_empty_slice();
+ }
+
if (GPR_UNLIKELY(output_length >
input_length / 4 * 3 + tail_xtra[input_length % 4])) {
- gpr_log(
- GPR_ERROR,
- "Base64 decoding failed, output_length %d is longer "
- "than the max possible output length %d.\n",
- static_cast<int>(output_length),
- static_cast<int>(input_length / 4 * 3 + tail_xtra[input_length % 4]));
- grpc_slice_unref_internal(output);
- return grpc_empty_slice();
- }
-
- ctx.input_cur = GRPC_SLICE_START_PTR(input);
- ctx.input_end = GRPC_SLICE_END_PTR(input);
- ctx.output_cur = GRPC_SLICE_START_PTR(output);
- ctx.output_end = GRPC_SLICE_END_PTR(output);
- ctx.contains_tail = true;
-
+ gpr_log(
+ GPR_ERROR,
+ "Base64 decoding failed, output_length %d is longer "
+ "than the max possible output length %d.\n",
+ static_cast<int>(output_length),
+ static_cast<int>(input_length / 4 * 3 + tail_xtra[input_length % 4]));
+ grpc_slice_unref_internal(output);
+ return grpc_empty_slice();
+ }
+
+ ctx.input_cur = GRPC_SLICE_START_PTR(input);
+ ctx.input_end = GRPC_SLICE_END_PTR(input);
+ ctx.output_cur = GRPC_SLICE_START_PTR(output);
+ ctx.output_end = GRPC_SLICE_END_PTR(output);
+ ctx.contains_tail = true;
+
if (GPR_UNLIKELY(!grpc_base64_decode_partial(&ctx))) {
- char* s = grpc_slice_to_c_string(input);
- gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s);
- gpr_free(s);
- grpc_slice_unref_internal(output);
- return grpc_empty_slice();
- }
- GPR_ASSERT(ctx.output_cur == GRPC_SLICE_END_PTR(output));
- GPR_ASSERT(ctx.input_cur <= GRPC_SLICE_END_PTR(input));
- return output;
-}
+ char* s = grpc_slice_to_c_string(input);
+ gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s);
+ gpr_free(s);
+ grpc_slice_unref_internal(output);
+ return grpc_empty_slice();
+ }
+ GPR_ASSERT(ctx.output_cur == GRPC_SLICE_END_PTR(output));
+ GPR_ASSERT(ctx.input_cur <= GRPC_SLICE_END_PTR(input));
+ return output;
+}
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 1cbca033a1f..904928c7265 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_BIN_DECODER_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_DECODER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include <stdbool.h>
@@ -28,8 +28,8 @@ struct grpc_base64_decode_context {
/* input/output: */
const uint8_t* input_cur;
const uint8_t* input_end;
- uint8_t* output_cur;
- uint8_t* output_end;
+ uint8_t* output_cur;
+ uint8_t* output_end;
/* Indicate if the decoder should handle the tail of input data*/
bool contains_tail;
};
@@ -38,7 +38,7 @@ struct grpc_base64_decode_context {
or output_end is reached. When input_end is reached, (input_end - input_cur)
is less than 4. When output_end is reached, (output_end - output_cur) is less
than 3. Returns false if decoding is failed. */
-bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx);
+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. */
@@ -50,7 +50,7 @@ grpc_slice grpc_chttp2_base64_decode(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. */
-size_t grpc_chttp2_base64_infer_length_after_decode(const grpc_slice& slice);
-
+/* Infer the length of decoded data from encoded data. */
+size_t grpc_chttp2_base64_infer_length_after_decode(const grpc_slice& slice);
+
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_DECODER_H */
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 ba39bbdbe33..401002a0ba0 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
-
-#include <string.h>
-
-#include <grpc/support/log.h>
-#include "src/core/ext/transport/chttp2/transport/huffsyms.h"
-
-static const char alphabet[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
+/*
+ *
+ * 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/transport/chttp2/transport/bin_encoder.h"
+
+#include <string.h>
+
+#include <grpc/support/log.h>
+#include "src/core/ext/transport/chttp2/transport/huffsyms.h"
+
+static const char alphabet[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
struct b64_huff_sym {
- uint16_t bits;
- uint8_t length;
+ uint16_t bits;
+ uint8_t length;
};
-static const b64_huff_sym huff_alphabet[64] = {
- {0x21, 6}, {0x5d, 7}, {0x5e, 7}, {0x5f, 7}, {0x60, 7}, {0x61, 7},
- {0x62, 7}, {0x63, 7}, {0x64, 7}, {0x65, 7}, {0x66, 7}, {0x67, 7},
- {0x68, 7}, {0x69, 7}, {0x6a, 7}, {0x6b, 7}, {0x6c, 7}, {0x6d, 7},
- {0x6e, 7}, {0x6f, 7}, {0x70, 7}, {0x71, 7}, {0x72, 7}, {0xfc, 8},
- {0x73, 7}, {0xfd, 8}, {0x3, 5}, {0x23, 6}, {0x4, 5}, {0x24, 6},
- {0x5, 5}, {0x25, 6}, {0x26, 6}, {0x27, 6}, {0x6, 5}, {0x74, 7},
- {0x75, 7}, {0x28, 6}, {0x29, 6}, {0x2a, 6}, {0x7, 5}, {0x2b, 6},
- {0x76, 7}, {0x2c, 6}, {0x8, 5}, {0x9, 5}, {0x2d, 6}, {0x77, 7},
- {0x78, 7}, {0x79, 7}, {0x7a, 7}, {0x7b, 7}, {0x0, 5}, {0x1, 5},
- {0x2, 5}, {0x19, 6}, {0x1a, 6}, {0x1b, 6}, {0x1c, 6}, {0x1d, 6},
- {0x1e, 6}, {0x1f, 6}, {0x7fb, 11}, {0x18, 6}};
-
-static const uint8_t tail_xtra[3] = {0, 2, 3};
-
+static const b64_huff_sym huff_alphabet[64] = {
+ {0x21, 6}, {0x5d, 7}, {0x5e, 7}, {0x5f, 7}, {0x60, 7}, {0x61, 7},
+ {0x62, 7}, {0x63, 7}, {0x64, 7}, {0x65, 7}, {0x66, 7}, {0x67, 7},
+ {0x68, 7}, {0x69, 7}, {0x6a, 7}, {0x6b, 7}, {0x6c, 7}, {0x6d, 7},
+ {0x6e, 7}, {0x6f, 7}, {0x70, 7}, {0x71, 7}, {0x72, 7}, {0xfc, 8},
+ {0x73, 7}, {0xfd, 8}, {0x3, 5}, {0x23, 6}, {0x4, 5}, {0x24, 6},
+ {0x5, 5}, {0x25, 6}, {0x26, 6}, {0x27, 6}, {0x6, 5}, {0x74, 7},
+ {0x75, 7}, {0x28, 6}, {0x29, 6}, {0x2a, 6}, {0x7, 5}, {0x2b, 6},
+ {0x76, 7}, {0x2c, 6}, {0x8, 5}, {0x9, 5}, {0x2d, 6}, {0x77, 7},
+ {0x78, 7}, {0x79, 7}, {0x7a, 7}, {0x7b, 7}, {0x0, 5}, {0x1, 5},
+ {0x2, 5}, {0x19, 6}, {0x1a, 6}, {0x1b, 6}, {0x1c, 6}, {0x1d, 6},
+ {0x1e, 6}, {0x1f, 6}, {0x7fb, 11}, {0x18, 6}};
+
+static const uint8_t tail_xtra[3] = {0, 2, 3};
+
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);
+ 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);
- char* out = reinterpret_cast<char*> GRPC_SLICE_START_PTR(output);
- size_t i;
-
- /* encode full triplets */
- for (i = 0; i < input_triplets; i++) {
- out[0] = alphabet[in[0] >> 2];
- out[1] = alphabet[((in[0] & 0x3) << 4) | (in[1] >> 4)];
- out[2] = alphabet[((in[1] & 0xf) << 2) | (in[2] >> 6)];
- out[3] = alphabet[in[2] & 0x3f];
- out += 4;
- in += 3;
- }
-
- /* encode the remaining bytes */
- switch (tail_case) {
- case 0:
- break;
- case 1:
- out[0] = alphabet[in[0] >> 2];
- out[1] = alphabet[(in[0] & 0x3) << 4];
- out += 2;
- in += 1;
- break;
- case 2:
- out[0] = alphabet[in[0] >> 2];
- out[1] = alphabet[((in[0] & 0x3) << 4) | (in[1] >> 4)];
- out[2] = alphabet[(in[1] & 0xf) << 2];
- out += 3;
- in += 2;
- break;
- }
-
- GPR_ASSERT(out == (char*)GRPC_SLICE_END_PTR(output));
- GPR_ASSERT(in == GRPC_SLICE_END_PTR(input));
- return output;
-}
-
+ char* out = reinterpret_cast<char*> GRPC_SLICE_START_PTR(output);
+ size_t i;
+
+ /* encode full triplets */
+ for (i = 0; i < input_triplets; i++) {
+ out[0] = alphabet[in[0] >> 2];
+ out[1] = alphabet[((in[0] & 0x3) << 4) | (in[1] >> 4)];
+ out[2] = alphabet[((in[1] & 0xf) << 2) | (in[2] >> 6)];
+ out[3] = alphabet[in[2] & 0x3f];
+ out += 4;
+ in += 3;
+ }
+
+ /* encode the remaining bytes */
+ switch (tail_case) {
+ case 0:
+ break;
+ case 1:
+ out[0] = alphabet[in[0] >> 2];
+ out[1] = alphabet[(in[0] & 0x3) << 4];
+ out += 2;
+ in += 1;
+ break;
+ case 2:
+ out[0] = alphabet[in[0] >> 2];
+ out[1] = alphabet[((in[0] & 0x3) << 4) | (in[1] >> 4)];
+ out[2] = alphabet[(in[1] & 0xf) << 2];
+ out += 3;
+ in += 2;
+ break;
+ }
+
+ GPR_ASSERT(out == (char*)GRPC_SLICE_END_PTR(output));
+ GPR_ASSERT(in == GRPC_SLICE_END_PTR(input));
+ return output;
+}
+
grpc_slice grpc_chttp2_huffman_compress(const grpc_slice& input) {
- size_t nbits;
+ size_t nbits;
const uint8_t* in;
- uint8_t* out;
- grpc_slice output;
- uint32_t temp = 0;
- uint32_t temp_length = 0;
-
- nbits = 0;
- for (in = GRPC_SLICE_START_PTR(input); in != GRPC_SLICE_END_PTR(input);
- ++in) {
- nbits += grpc_chttp2_huffsyms[*in].length;
- }
-
- output = GRPC_SLICE_MALLOC(nbits / 8 + (nbits % 8 != 0));
- out = GRPC_SLICE_START_PTR(output);
- for (in = GRPC_SLICE_START_PTR(input); in != GRPC_SLICE_END_PTR(input);
- ++in) {
- int sym = *in;
- temp <<= grpc_chttp2_huffsyms[sym].length;
- temp |= grpc_chttp2_huffsyms[sym].bits;
- temp_length += grpc_chttp2_huffsyms[sym].length;
-
- while (temp_length > 8) {
- temp_length -= 8;
- *out++ = static_cast<uint8_t>(temp >> temp_length);
- }
- }
-
- if (temp_length) {
- /* 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++ =
- static_cast<uint8_t>(static_cast<uint8_t>(temp << (8u - temp_length)) |
- static_cast<uint8_t>(0xffu >> temp_length));
- }
-
- GPR_ASSERT(out == GRPC_SLICE_END_PTR(output));
-
- return output;
-}
-
+ uint8_t* out;
+ grpc_slice output;
+ uint32_t temp = 0;
+ uint32_t temp_length = 0;
+
+ nbits = 0;
+ for (in = GRPC_SLICE_START_PTR(input); in != GRPC_SLICE_END_PTR(input);
+ ++in) {
+ nbits += grpc_chttp2_huffsyms[*in].length;
+ }
+
+ output = GRPC_SLICE_MALLOC(nbits / 8 + (nbits % 8 != 0));
+ out = GRPC_SLICE_START_PTR(output);
+ for (in = GRPC_SLICE_START_PTR(input); in != GRPC_SLICE_END_PTR(input);
+ ++in) {
+ int sym = *in;
+ temp <<= grpc_chttp2_huffsyms[sym].length;
+ temp |= grpc_chttp2_huffsyms[sym].bits;
+ temp_length += grpc_chttp2_huffsyms[sym].length;
+
+ while (temp_length > 8) {
+ temp_length -= 8;
+ *out++ = static_cast<uint8_t>(temp >> temp_length);
+ }
+ }
+
+ if (temp_length) {
+ /* 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++ =
+ static_cast<uint8_t>(static_cast<uint8_t>(temp << (8u - temp_length)) |
+ static_cast<uint8_t>(0xffu >> temp_length));
+ }
+
+ GPR_ASSERT(out == GRPC_SLICE_END_PTR(output));
+
+ return output;
+}
+
struct huff_out {
- uint32_t temp;
- uint32_t temp_length;
- uint8_t* out;
+ uint32_t temp;
+ uint32_t temp_length;
+ uint8_t* out;
};
-static void enc_flush_some(huff_out* out) {
- while (out->temp_length > 8) {
- out->temp_length -= 8;
- *out->out++ = static_cast<uint8_t>(out->temp >> out->temp_length);
- }
-}
-
-static void enc_add2(huff_out* out, uint8_t a, uint8_t b) {
- b64_huff_sym sa = huff_alphabet[a];
- b64_huff_sym sb = huff_alphabet[b];
- out->temp = (out->temp << (sa.length + sb.length)) |
- (static_cast<uint32_t>(sa.bits) << sb.length) | sb.bits;
- out->temp_length +=
- static_cast<uint32_t>(sa.length) + static_cast<uint32_t>(sb.length);
- enc_flush_some(out);
-}
-
-static void enc_add1(huff_out* out, uint8_t a) {
- b64_huff_sym sa = huff_alphabet[a];
- out->temp = (out->temp << sa.length) | sa.bits;
- out->temp_length += sa.length;
- enc_flush_some(out);
-}
-
+static void enc_flush_some(huff_out* out) {
+ while (out->temp_length > 8) {
+ out->temp_length -= 8;
+ *out->out++ = static_cast<uint8_t>(out->temp >> out->temp_length);
+ }
+}
+
+static void enc_add2(huff_out* out, uint8_t a, uint8_t b) {
+ b64_huff_sym sa = huff_alphabet[a];
+ b64_huff_sym sb = huff_alphabet[b];
+ out->temp = (out->temp << (sa.length + sb.length)) |
+ (static_cast<uint32_t>(sa.bits) << sb.length) | sb.bits;
+ out->temp_length +=
+ static_cast<uint32_t>(sa.length) + static_cast<uint32_t>(sb.length);
+ enc_flush_some(out);
+}
+
+static void enc_add1(huff_out* out, uint8_t a) {
+ b64_huff_sym sa = huff_alphabet[a];
+ out->temp = (out->temp << sa.length) | sa.bits;
+ out->temp_length += sa.length;
+ enc_flush_some(out);
+}
+
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;
- size_t output_syms = input_triplets * 4 + tail_xtra[tail_case];
- 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);
+ 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_syms = input_triplets * 4 + tail_xtra[tail_case];
+ 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);
- uint8_t* start_out = GRPC_SLICE_START_PTR(output);
- huff_out out;
- size_t i;
-
- out.temp = 0;
- out.temp_length = 0;
- out.out = start_out;
-
- /* encode full triplets */
- for (i = 0; i < input_triplets; i++) {
- const uint8_t low_to_high = static_cast<uint8_t>((in[0] & 0x3) << 4);
- const uint8_t high_to_low = in[1] >> 4;
- enc_add2(&out, in[0] >> 2, low_to_high | high_to_low);
-
- const uint8_t a = static_cast<uint8_t>((in[1] & 0xf) << 2);
- const uint8_t b = (in[2] >> 6);
- enc_add2(&out, a | b, in[2] & 0x3f);
- in += 3;
- }
-
- /* encode the remaining bytes */
- switch (tail_case) {
- case 0:
- break;
- case 1:
- enc_add2(&out, in[0] >> 2, static_cast<uint8_t>((in[0] & 0x3) << 4));
- in += 1;
- break;
- case 2: {
- const uint8_t low_to_high = static_cast<uint8_t>((in[0] & 0x3) << 4);
- const uint8_t high_to_low = in[1] >> 4;
- enc_add2(&out, in[0] >> 2, low_to_high | high_to_low);
- enc_add1(&out, static_cast<uint8_t>((in[1] & 0xf) << 2));
- in += 2;
- break;
- }
- }
-
- if (out.temp_length) {
- /* 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.out++ = static_cast<uint8_t>(
- static_cast<uint8_t>(out.temp << (8u - out.temp_length)) |
- static_cast<uint8_t>(0xffu >> out.temp_length));
- }
-
- GPR_ASSERT(out.out <= GRPC_SLICE_END_PTR(output));
- GRPC_SLICE_SET_LENGTH(output, out.out - start_out);
-
- GPR_ASSERT(in == GRPC_SLICE_END_PTR(input));
- return output;
-}
+ uint8_t* start_out = GRPC_SLICE_START_PTR(output);
+ huff_out out;
+ size_t i;
+
+ out.temp = 0;
+ out.temp_length = 0;
+ out.out = start_out;
+
+ /* encode full triplets */
+ for (i = 0; i < input_triplets; i++) {
+ const uint8_t low_to_high = static_cast<uint8_t>((in[0] & 0x3) << 4);
+ const uint8_t high_to_low = in[1] >> 4;
+ enc_add2(&out, in[0] >> 2, low_to_high | high_to_low);
+
+ const uint8_t a = static_cast<uint8_t>((in[1] & 0xf) << 2);
+ const uint8_t b = (in[2] >> 6);
+ enc_add2(&out, a | b, in[2] & 0x3f);
+ in += 3;
+ }
+
+ /* encode the remaining bytes */
+ switch (tail_case) {
+ case 0:
+ break;
+ case 1:
+ enc_add2(&out, in[0] >> 2, static_cast<uint8_t>((in[0] & 0x3) << 4));
+ in += 1;
+ break;
+ case 2: {
+ const uint8_t low_to_high = static_cast<uint8_t>((in[0] & 0x3) << 4);
+ const uint8_t high_to_low = in[1] >> 4;
+ enc_add2(&out, in[0] >> 2, low_to_high | high_to_low);
+ enc_add1(&out, static_cast<uint8_t>((in[1] & 0xf) << 2));
+ in += 2;
+ break;
+ }
+ }
+
+ if (out.temp_length) {
+ /* 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.out++ = static_cast<uint8_t>(
+ static_cast<uint8_t>(out.temp << (8u - out.temp_length)) |
+ static_cast<uint8_t>(0xffu >> out.temp_length));
+ }
+
+ GPR_ASSERT(out.out <= GRPC_SLICE_END_PTR(output));
+ GRPC_SLICE_SET_LENGTH(output, out.out - start_out);
+
+ GPR_ASSERT(in == GRPC_SLICE_END_PTR(input));
+ return output;
+}
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 4f7ee67bd31..d921b62fde5 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_BIN_ENCODER_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_ENCODER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
/* base64 encode a slice. Returns a new slice, does not take ownership of the
@@ -34,7 +34,7 @@ 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);
+ grpc_slice_unref_internal( x);
return y; */
grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(
const grpc_slice& input);
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 ac13d73d3b5..817436f16eb 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
@@ -1,37 +1,37 @@
-/*
- *
- * 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/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/lib/debug/trace.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/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/transport/metadata.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");
-void grpc_chttp2_plugin_init(void) {
+void grpc_chttp2_plugin_init(void) {
g_flow_control_enabled =
!GPR_GLOBAL_CONFIG_GET(grpc_experimental_disable_flow_control);
-}
-
-void grpc_chttp2_plugin_shutdown(void) {}
+}
+
+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 180ca625435..59450c6bf25 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
@@ -13,11 +13,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
-
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
+
#include "y_absl/strings/str_format.h"
#include <grpc/slice_buffer.h>
@@ -25,168 +25,168 @@
#include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include <grpc/support/string_util.h>
-#include <inttypes.h>
-#include <limits.h>
-#include <math.h>
-#include <stdio.h>
-#include <string.h>
-
+#include <inttypes.h>
+#include <limits.h>
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
#include "src/core/ext/transport/chttp2/transport/context_list.h"
-#include "src/core/ext/transport/chttp2/transport/frame_data.h"
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-#include "src/core/ext/transport/chttp2/transport/varint.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/compression/stream_compression.h"
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gpr/env.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/http/parser.h"
-#include "src/core/lib/iomgr/executor.h"
+#include "src/core/ext/transport/chttp2/transport/frame_data.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+#include "src/core/ext/transport/chttp2/transport/varint.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/compression/stream_compression.h"
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gpr/env.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/http/parser.h"
+#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/iomgr/timer.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/transport/error_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"
-#include "src/core/lib/transport/timeout_encoding.h"
-#include "src/core/lib/transport/transport.h"
-#include "src/core/lib/transport/transport_impl.h"
+#include "src/core/lib/iomgr/timer.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/transport/error_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"
+#include "src/core/lib/transport/timeout_encoding.h"
+#include "src/core/lib/transport/transport.h"
+#include "src/core/lib/transport/transport_impl.h"
#include "src/core/lib/uri/uri_parser.h"
-
-#define DEFAULT_CONNECTION_WINDOW_TARGET (1024 * 1024)
-#define MAX_WINDOW 0x7fffffffu
-#define MAX_WRITE_BUFFER_SIZE (64 * 1024 * 1024)
-#define DEFAULT_MAX_HEADER_LIST_SIZE (8 * 1024)
-
-#define DEFAULT_CLIENT_KEEPALIVE_TIME_MS INT_MAX
-#define DEFAULT_CLIENT_KEEPALIVE_TIMEOUT_MS 20000 /* 20 seconds */
-#define DEFAULT_SERVER_KEEPALIVE_TIME_MS 7200000 /* 2 hours */
-#define DEFAULT_SERVER_KEEPALIVE_TIMEOUT_MS 20000 /* 20 seconds */
-#define DEFAULT_KEEPALIVE_PERMIT_WITHOUT_CALLS false
-#define KEEPALIVE_TIME_BACKOFF_MULTIPLIER 2
-
-#define DEFAULT_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS 300000 /* 5 minutes */
-#define DEFAULT_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS 300000 /* 5 minutes */
-#define DEFAULT_MAX_PINGS_BETWEEN_DATA 2
-#define DEFAULT_MAX_PING_STRIKES 2
-
+
+#define DEFAULT_CONNECTION_WINDOW_TARGET (1024 * 1024)
+#define MAX_WINDOW 0x7fffffffu
+#define MAX_WRITE_BUFFER_SIZE (64 * 1024 * 1024)
+#define DEFAULT_MAX_HEADER_LIST_SIZE (8 * 1024)
+
+#define DEFAULT_CLIENT_KEEPALIVE_TIME_MS INT_MAX
+#define DEFAULT_CLIENT_KEEPALIVE_TIMEOUT_MS 20000 /* 20 seconds */
+#define DEFAULT_SERVER_KEEPALIVE_TIME_MS 7200000 /* 2 hours */
+#define DEFAULT_SERVER_KEEPALIVE_TIMEOUT_MS 20000 /* 20 seconds */
+#define DEFAULT_KEEPALIVE_PERMIT_WITHOUT_CALLS false
+#define KEEPALIVE_TIME_BACKOFF_MULTIPLIER 2
+
+#define DEFAULT_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS 300000 /* 5 minutes */
+#define DEFAULT_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS 300000 /* 5 minutes */
+#define DEFAULT_MAX_PINGS_BETWEEN_DATA 2
+#define DEFAULT_MAX_PING_STRIKES 2
+
#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 =
- DEFAULT_CLIENT_KEEPALIVE_TIMEOUT_MS;
-static int g_default_server_keepalive_time_ms =
- DEFAULT_SERVER_KEEPALIVE_TIME_MS;
-static int g_default_server_keepalive_timeout_ms =
- DEFAULT_SERVER_KEEPALIVE_TIMEOUT_MS;
-static bool g_default_client_keepalive_permit_without_calls =
- DEFAULT_KEEPALIVE_PERMIT_WITHOUT_CALLS;
-static bool g_default_server_keepalive_permit_without_calls =
- DEFAULT_KEEPALIVE_PERMIT_WITHOUT_CALLS;
-
-static int g_default_min_sent_ping_interval_without_data_ms =
- DEFAULT_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS;
-static int g_default_min_recv_ping_interval_without_data_ms =
- DEFAULT_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS;
-static int g_default_max_pings_without_data = DEFAULT_MAX_PINGS_BETWEEN_DATA;
-static int g_default_max_ping_strikes = DEFAULT_MAX_PING_STRIKES;
-
-#define MAX_CLIENT_STREAM_ID 0x7fffffffu
-grpc_core::TraceFlag grpc_http_trace(false, "http");
+static int g_default_client_keepalive_time_ms =
+ DEFAULT_CLIENT_KEEPALIVE_TIME_MS;
+static int g_default_client_keepalive_timeout_ms =
+ DEFAULT_CLIENT_KEEPALIVE_TIMEOUT_MS;
+static int g_default_server_keepalive_time_ms =
+ DEFAULT_SERVER_KEEPALIVE_TIME_MS;
+static int g_default_server_keepalive_timeout_ms =
+ DEFAULT_SERVER_KEEPALIVE_TIMEOUT_MS;
+static bool g_default_client_keepalive_permit_without_calls =
+ DEFAULT_KEEPALIVE_PERMIT_WITHOUT_CALLS;
+static bool g_default_server_keepalive_permit_without_calls =
+ DEFAULT_KEEPALIVE_PERMIT_WITHOUT_CALLS;
+
+static int g_default_min_sent_ping_interval_without_data_ms =
+ DEFAULT_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS;
+static int g_default_min_recv_ping_interval_without_data_ms =
+ DEFAULT_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS;
+static int g_default_max_pings_without_data = DEFAULT_MAX_PINGS_BETWEEN_DATA;
+static int g_default_max_ping_strikes = DEFAULT_MAX_PING_STRIKES;
+
+#define MAX_CLIENT_STREAM_ID 0x7fffffffu
+grpc_core::TraceFlag grpc_http_trace(false, "http");
grpc_core::TraceFlag grpc_keepalive_trace(false, "http_keepalive");
-grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_refcount(false,
- "chttp2_refcount");
-
+grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_refcount(false,
+ "chttp2_refcount");
+
// 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_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_locked(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_locked(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 complete_fetch(void* gs, grpc_error* error);
-static void complete_fetch_locked(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,
- grpc_chttp2_setting_id id, uint32_t value);
-
-static void close_from_api(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_error* error);
-
+static void queue_setting_update(grpc_chttp2_transport* t,
+ grpc_chttp2_setting_id id, uint32_t value);
+
+static void close_from_api(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_error* error);
+
// Start new streams that have been created if we can
-static void maybe_start_some_streams(grpc_chttp2_transport* t);
-
-static void connectivity_state_set(grpc_chttp2_transport* t,
- grpc_connectivity_state state,
+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);
-
+
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);
-
-static void post_benign_reclaimer(grpc_chttp2_transport* t);
-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 benign_reclaimer_locked(void* t, grpc_error* error);
+static void destructive_reclaimer_locked(void* t, grpc_error* error);
+
+static void post_benign_reclaimer(grpc_chttp2_transport* t);
+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_locked(void* tp, grpc_error* error);
-static void finish_bdp_ping_locked(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_locked(void* tp, grpc_error* error);
-
-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_complete);
-static void retry_initiate_ping_locked(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);
+static void send_ping_locked(grpc_chttp2_transport* t,
+ grpc_closure* on_initiate,
+ grpc_closure* on_complete);
+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_locked(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_locked(void* arg, grpc_error* error);
-static void finish_keepalive_ping_locked(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_locked(void* arg, grpc_error* error);
-
-static void reset_byte_stream(void* arg, grpc_error* error);
-
-// Flow control default enabled. Can be disabled by setting
-// GRPC_EXPERIMENTAL_DISABLE_FLOW_CONTROL
-bool g_flow_control_enabled = true;
-
+static void keepalive_watchdog_fired_locked(void* arg, grpc_error* error);
+
+static void reset_byte_stream(void* arg, grpc_error* error);
+
+// Flow control default enabled. Can be disabled by setting
+// GRPC_EXPERIMENTAL_DISABLE_FLOW_CONTROL
+bool g_flow_control_enabled = true;
+
//
// CONSTRUCTION/DESTRUCTION/REFCOUNTING
//
-
+
grpc_chttp2_transport::~grpc_chttp2_transport() {
- size_t i;
-
+ size_t i;
+
if (channelz_socket != nullptr) {
channelz_socket.reset();
}
-
+
grpc_endpoint_destroy(ep);
-
+
grpc_slice_buffer_destroy_internal(&qbuf);
-
+
grpc_slice_buffer_destroy_internal(&outbuf);
grpc_chttp2_hpack_compressor_destroy(&hpack_compressor);
-
+
grpc_error* error =
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed");
// ContextList::Execute follows semantics of a callback function and does not
@@ -199,45 +199,45 @@ grpc_chttp2_transport::~grpc_chttp2_transport() {
grpc_chttp2_hpack_parser_destroy(&hpack_parser);
grpc_chttp2_goaway_parser_destroy(&goaway_parser);
- for (i = 0; i < STREAM_LIST_COUNT; i++) {
+ for (i = 0; i < STREAM_LIST_COUNT; i++) {
GPR_ASSERT(lists[i].head == nullptr);
GPR_ASSERT(lists[i].tail == nullptr);
- }
-
+ }
+
GRPC_ERROR_UNREF(goaway_error);
-
+
GPR_ASSERT(grpc_chttp2_stream_map_size(&stream_map) == 0);
-
+
grpc_chttp2_stream_map_destroy(&stream_map);
-
+
GRPC_COMBINER_UNREF(combiner, "chttp2_transport");
-
+
cancel_pings(this,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed"));
-
+
while (write_cb_pool) {
grpc_chttp2_write_cb* next = write_cb_pool->next;
gpr_free(write_cb_pool);
write_cb_pool = next;
- }
-
+ }
+
flow_control.Destroy();
-
+
GRPC_ERROR_UNREF(closed_with_error);
gpr_free(ping_acks);
-}
-
-static const grpc_transport_vtable* get_vtable(void);
-
+}
+
+static const grpc_transport_vtable* get_vtable(void);
+
// Returns whether bdp is enabled
static bool read_channel_args(grpc_chttp2_transport* t,
const grpc_channel_args* channel_args,
bool is_client) {
bool enable_bdp = true;
bool channelz_enabled = GRPC_ENABLE_CHANNELZ_DEFAULT;
- size_t i;
- int j;
-
+ size_t i;
+ int j;
+
for (i = 0; i < channel_args->num_args; i++) {
if (0 == strcmp(channel_args->args[i].key,
GRPC_ARG_HTTP2_INITIAL_SEQUENCE_NUMBER)) {
@@ -383,29 +383,29 @@ static bool read_channel_args(grpc_chttp2_transport* t,
}
return enable_bdp;
}
-
+
static void init_transport_keepalive_settings(grpc_chttp2_transport* t) {
- if (t->is_client) {
- t->keepalive_time = g_default_client_keepalive_time_ms == INT_MAX
- ? GRPC_MILLIS_INF_FUTURE
- : g_default_client_keepalive_time_ms;
- t->keepalive_timeout = g_default_client_keepalive_timeout_ms == INT_MAX
- ? GRPC_MILLIS_INF_FUTURE
- : g_default_client_keepalive_timeout_ms;
- t->keepalive_permit_without_calls =
- g_default_client_keepalive_permit_without_calls;
- } else {
- t->keepalive_time = g_default_server_keepalive_time_ms == INT_MAX
- ? GRPC_MILLIS_INF_FUTURE
- : g_default_server_keepalive_time_ms;
- t->keepalive_timeout = g_default_server_keepalive_timeout_ms == INT_MAX
- ? GRPC_MILLIS_INF_FUTURE
- : g_default_server_keepalive_timeout_ms;
- t->keepalive_permit_without_calls =
- g_default_server_keepalive_permit_without_calls;
- }
-}
-
+ if (t->is_client) {
+ t->keepalive_time = g_default_client_keepalive_time_ms == INT_MAX
+ ? GRPC_MILLIS_INF_FUTURE
+ : g_default_client_keepalive_time_ms;
+ t->keepalive_timeout = g_default_client_keepalive_timeout_ms == INT_MAX
+ ? GRPC_MILLIS_INF_FUTURE
+ : g_default_client_keepalive_timeout_ms;
+ t->keepalive_permit_without_calls =
+ g_default_client_keepalive_permit_without_calls;
+ } else {
+ t->keepalive_time = g_default_server_keepalive_time_ms == INT_MAX
+ ? GRPC_MILLIS_INF_FUTURE
+ : g_default_server_keepalive_time_ms;
+ t->keepalive_timeout = g_default_server_keepalive_timeout_ms == INT_MAX
+ ? GRPC_MILLIS_INF_FUTURE
+ : g_default_server_keepalive_timeout_ms;
+ t->keepalive_permit_without_calls =
+ g_default_server_keepalive_permit_without_calls;
+ }
+}
+
static void configure_transport_ping_policy(grpc_chttp2_transport* t) {
t->ping_policy.max_pings_without_data = g_default_max_pings_without_data;
t->ping_policy.min_sent_ping_interval_without_data =
@@ -414,7 +414,7 @@ static void configure_transport_ping_policy(grpc_chttp2_transport* t) {
t->ping_policy.min_recv_ping_interval_without_data =
g_default_min_recv_ping_interval_without_data_ms;
}
-
+
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;
@@ -430,7 +430,7 @@ static void init_keepalive_pings_if_enabled(grpc_chttp2_transport* t) {
t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED;
}
}
-
+
grpc_chttp2_transport::grpc_chttp2_transport(
const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client,
grpc_resource_user* resource_user)
@@ -468,11 +468,11 @@ grpc_chttp2_transport::grpc_chttp2_transport(
for (i = 0; i < GRPC_CHTTP2_NUM_SETTINGS; i++) {
for (j = 0; j < GRPC_NUM_SETTING_SETS; j++) {
settings[j][i] = grpc_chttp2_settings_parameters[i].default_value;
- }
- }
+ }
+ }
grpc_chttp2_hpack_parser_init(&hpack_parser);
grpc_chttp2_goaway_parser_init(&goaway_parser);
-
+
// configure http2 the way we like it
if (is_client) {
queue_setting_update(this, GRPC_CHTTP2_SETTINGS_ENABLE_PUSH, 0);
@@ -491,126 +491,126 @@ grpc_chttp2_transport::grpc_chttp2_transport(
enable_bdp = read_channel_args(this, channel_args, is_client);
}
- if (g_flow_control_enabled) {
+ if (g_flow_control_enabled) {
flow_control.Init<grpc_core::chttp2::TransportFlowControl>(this,
enable_bdp);
- } else {
+ } else {
flow_control.Init<grpc_core::chttp2::TransportFlowControlDisabled>(this);
- enable_bdp = false;
- }
-
+ enable_bdp = false;
+ }
+
// No pings allowed before receiving a header or data frame.
ping_state.pings_before_data_required = 0;
ping_state.is_delayed_ping_timer_set = false;
ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST;
-
+
ping_recv_state.last_ping_recv_time = GRPC_MILLIS_INF_PAST;
ping_recv_state.ping_strikes = 0;
-
+
init_keepalive_pings_if_enabled(this);
-
- if (enable_bdp) {
+
+ if (enable_bdp) {
bdp_ping_blocked = true;
grpc_chttp2_act_on_flowctl_action(flow_control->PeriodicUpdate(), this,
- nullptr);
- }
-
+ nullptr);
+ }
+
grpc_chttp2_initiate_write(this, GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE);
post_benign_reclaimer(this);
-}
-
+}
+
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(
- t, grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed"),
- GRPC_ERROR_INT_OCCURRED_DURING_WRITE, t->write_state));
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+ t->destroying = 1;
+ close_transport_locked(
+ t, grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed"),
+ GRPC_ERROR_INT_OCCURRED_DURING_WRITE, t->write_state));
// Must be the last line.
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "destroy");
-}
-
-static void destroy_transport(grpc_transport* gt) {
- grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "destroy");
+}
+
+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);
-}
-
-static void close_transport_locked(grpc_chttp2_transport* t,
- grpc_error* error) {
- end_all_the_calls(t, GRPC_ERROR_REF(error));
- cancel_pings(t, GRPC_ERROR_REF(error));
- if (t->closed_with_error == GRPC_ERROR_NONE) {
- if (!grpc_error_has_clear_grpc_status(error)) {
- error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_UNAVAILABLE);
- }
- if (t->write_state != GRPC_CHTTP2_WRITE_STATE_IDLE) {
- if (t->close_transport_on_writes_finished == nullptr) {
- t->close_transport_on_writes_finished =
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Delayed close due to in-progress write");
- }
- t->close_transport_on_writes_finished =
- grpc_error_add_child(t->close_transport_on_writes_finished, error);
- return;
- }
- GPR_ASSERT(error != GRPC_ERROR_NONE);
- t->closed_with_error = GRPC_ERROR_REF(error);
+}
+
+static void close_transport_locked(grpc_chttp2_transport* t,
+ grpc_error* error) {
+ end_all_the_calls(t, GRPC_ERROR_REF(error));
+ cancel_pings(t, GRPC_ERROR_REF(error));
+ if (t->closed_with_error == GRPC_ERROR_NONE) {
+ if (!grpc_error_has_clear_grpc_status(error)) {
+ error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_UNAVAILABLE);
+ }
+ if (t->write_state != GRPC_CHTTP2_WRITE_STATE_IDLE) {
+ if (t->close_transport_on_writes_finished == nullptr) {
+ t->close_transport_on_writes_finished =
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Delayed close due to in-progress write");
+ }
+ t->close_transport_on_writes_finished =
+ grpc_error_add_child(t->close_transport_on_writes_finished, error);
+ return;
+ }
+ GPR_ASSERT(error != GRPC_ERROR_NONE);
+ t->closed_with_error = GRPC_ERROR_REF(error);
connectivity_state_set(t, GRPC_CHANNEL_SHUTDOWN, y_absl::Status(),
"close_transport");
- if (t->ping_state.is_delayed_ping_timer_set) {
- grpc_timer_cancel(&t->ping_state.delayed_ping_timer);
- }
- if (t->have_next_bdp_ping_timer) {
- grpc_timer_cancel(&t->next_bdp_ping_timer);
- }
- switch (t->keepalive_state) {
- case GRPC_CHTTP2_KEEPALIVE_STATE_WAITING:
- grpc_timer_cancel(&t->keepalive_ping_timer);
- break;
- case GRPC_CHTTP2_KEEPALIVE_STATE_PINGING:
- grpc_timer_cancel(&t->keepalive_ping_timer);
- grpc_timer_cancel(&t->keepalive_watchdog_timer);
- break;
- case GRPC_CHTTP2_KEEPALIVE_STATE_DYING:
- case GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED:
+ if (t->ping_state.is_delayed_ping_timer_set) {
+ grpc_timer_cancel(&t->ping_state.delayed_ping_timer);
+ }
+ if (t->have_next_bdp_ping_timer) {
+ grpc_timer_cancel(&t->next_bdp_ping_timer);
+ }
+ switch (t->keepalive_state) {
+ case GRPC_CHTTP2_KEEPALIVE_STATE_WAITING:
+ grpc_timer_cancel(&t->keepalive_ping_timer);
+ break;
+ case GRPC_CHTTP2_KEEPALIVE_STATE_PINGING:
+ grpc_timer_cancel(&t->keepalive_ping_timer);
+ grpc_timer_cancel(&t->keepalive_watchdog_timer);
+ break;
+ case GRPC_CHTTP2_KEEPALIVE_STATE_DYING:
+ case GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED:
// keepalive timers are not set in these two states
- break;
- }
-
+ break;
+ }
+
// flush writable stream list to avoid dangling references
- grpc_chttp2_stream* s;
- while (grpc_chttp2_list_pop_writable_stream(t, &s)) {
- GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:close");
- }
- GPR_ASSERT(t->write_state == GRPC_CHTTP2_WRITE_STATE_IDLE);
- grpc_endpoint_shutdown(t->ep, GRPC_ERROR_REF(error));
- }
- if (t->notify_on_receive_settings != nullptr) {
+ grpc_chttp2_stream* s;
+ while (grpc_chttp2_list_pop_writable_stream(t, &s)) {
+ GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:close");
+ }
+ GPR_ASSERT(t->write_state == GRPC_CHTTP2_WRITE_STATE_IDLE);
+ 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_ERROR_REF(error));
- t->notify_on_receive_settings = nullptr;
- }
- GRPC_ERROR_UNREF(error);
-}
-
-#ifndef NDEBUG
-void grpc_chttp2_stream_ref(grpc_chttp2_stream* s, const char* reason) {
- grpc_stream_ref(s->refcount, reason);
-}
-void grpc_chttp2_stream_unref(grpc_chttp2_stream* s, const char* reason) {
- grpc_stream_unref(s->refcount, reason);
-}
-#else
-void grpc_chttp2_stream_ref(grpc_chttp2_stream* s) {
- grpc_stream_ref(s->refcount);
-}
-void grpc_chttp2_stream_unref(grpc_chttp2_stream* s) {
- grpc_stream_unref(s->refcount);
-}
-#endif
-
+ t->notify_on_receive_settings = nullptr;
+ }
+ GRPC_ERROR_UNREF(error);
+}
+
+#ifndef NDEBUG
+void grpc_chttp2_stream_ref(grpc_chttp2_stream* s, const char* reason) {
+ grpc_stream_ref(s->refcount, reason);
+}
+void grpc_chttp2_stream_unref(grpc_chttp2_stream* s, const char* reason) {
+ grpc_stream_unref(s->refcount, reason);
+}
+#else
+void grpc_chttp2_stream_ref(grpc_chttp2_stream* s) {
+ grpc_stream_ref(s->refcount);
+}
+void grpc_chttp2_stream_unref(grpc_chttp2_stream* s) {
+ grpc_stream_unref(s->refcount);
+}
+#endif
+
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
@@ -618,7 +618,7 @@ grpc_chttp2_stream::Reffer::Reffer(grpc_chttp2_stream* s) {
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,
@@ -628,27 +628,27 @@ grpc_chttp2_stream::grpc_chttp2_stream(grpc_chttp2_transport* t,
reffer(this),
metadata_buffer{grpc_chttp2_incoming_metadata_buffer(arena),
grpc_chttp2_incoming_metadata_buffer(arena)} {
- if (server_data) {
+ if (server_data) {
id = static_cast<uint32_t>((uintptr_t)server_data);
*t->accepting_stream = this;
grpc_chttp2_stream_map_add(&t->stream_map, id, this);
- post_destructive_reclaimer(t);
- }
- if (t->flow_control->flow_control_enabled()) {
+ post_destructive_reclaimer(t);
+ }
+ if (t->flow_control->flow_control_enabled()) {
flow_control.Init<grpc_core::chttp2::StreamFlowControl>(
- static_cast<grpc_core::chttp2::TransportFlowControl*>(
- t->flow_control.get()),
+ static_cast<grpc_core::chttp2::TransportFlowControl*>(
+ t->flow_control.get()),
this);
- } else {
+ } else {
flow_control.Init<grpc_core::chttp2::StreamFlowControlDisabled>();
- }
-
+ }
+
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_chttp2_stream::~grpc_chttp2_stream() {
if (t->channelz_socket != nullptr) {
if ((t->is_client && eos_received) || (!t->is_client && eos_sent)) {
@@ -657,12 +657,12 @@ grpc_chttp2_stream::~grpc_chttp2_stream() {
t->channelz_socket->RecordStreamFailed();
}
}
-
+
GPR_ASSERT((write_closed && read_closed) || id == 0);
if (id != 0) {
GPR_ASSERT(grpc_chttp2_stream_map_find(&t->stream_map, id) == nullptr);
- }
-
+ }
+
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) {
@@ -672,15 +672,15 @@ grpc_chttp2_stream::~grpc_chttp2_stream() {
GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
grpc_slice_buffer_destroy_internal(&decompressed_data_buffer);
}
-
- for (int i = 0; i < STREAM_LIST_COUNT; i++) {
+
+ for (int i = 0; i < STREAM_LIST_COUNT; i++) {
if (GPR_UNLIKELY(included[i])) {
- gpr_log(GPR_ERROR, "%s stream %d still included in list %d",
+ gpr_log(GPR_ERROR, "%s stream %d still included in list %d",
t->is_client ? "client" : "server", id, i);
- abort();
- }
- }
-
+ abort();
+ }
+ }
+
GPR_ASSERT(send_initial_metadata_finished == nullptr);
GPR_ASSERT(fetching_send_message == nullptr);
GPR_ASSERT(send_trailing_metadata_finished == nullptr);
@@ -691,17 +691,17 @@ grpc_chttp2_stream::~grpc_chttp2_stream() {
GRPC_ERROR_UNREF(read_closed_error);
GRPC_ERROR_UNREF(write_closed_error);
GRPC_ERROR_UNREF(byte_stream_error);
-
+
flow_control.Destroy();
-
+
if (t->resource_user != nullptr) {
grpc_resource_user_free(t->resource_user, GRPC_RESOURCE_QUOTA_CALL_SIZE);
}
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "stream");
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "stream");
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) {
@@ -709,43 +709,43 @@ static int init_stream(grpc_transport* gt, grpc_stream* gs,
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*/) {
GPR_TIMER_SCOPE("destroy_stream", 0);
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(sp);
s->~grpc_chttp2_stream();
}
-static void destroy_stream(grpc_transport* gt, grpc_stream* gs,
- grpc_closure* then_schedule_closure) {
- 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);
+static void destroy_stream(grpc_transport* gt, grpc_stream* gs,
+ grpc_closure* then_schedule_closure) {
+ 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) {
- grpc_stream_compression_context_destroy(s->stream_compression_ctx);
- 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) {
- grpc_stream_compression_context_destroy(s->stream_decompression_ctx);
- s->stream_decompression_ctx = nullptr;
- }
-
- s->destroy_stream_arg = then_schedule_closure;
+ 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),
- GRPC_ERROR_NONE);
-}
-
-grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t,
- uint32_t id) {
+ GRPC_ERROR_NONE);
+}
+
+grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t,
+ uint32_t id) {
if (t->accept_stream_cb == nullptr) {
- return nullptr;
- }
+ return nullptr;
+ }
// Don't accept the stream if memory quota doesn't allow. Note that we should
// simply refuse the stream here instead of canceling the stream after it's
// accepted since the latter will create the call which costs much memory.
@@ -759,132 +759,132 @@ grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t,
return nullptr;
}
grpc_chttp2_stream* accepting = nullptr;
- GPR_ASSERT(t->accepting_stream == nullptr);
- t->accepting_stream = &accepting;
+ 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->accepting_stream = nullptr;
- return accepting;
-}
-
+ t->accepting_stream = nullptr;
+ return accepting;
+}
+
//
// OUTPUT PROCESSING
//
-
-static const char* write_state_name(grpc_chttp2_write_state st) {
- switch (st) {
- case GRPC_CHTTP2_WRITE_STATE_IDLE:
- return "IDLE";
- case GRPC_CHTTP2_WRITE_STATE_WRITING:
- return "WRITING";
- case GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE:
- return "WRITING+MORE";
- }
- GPR_UNREACHABLE_CODE(return "UNKNOWN");
-}
-
-static void set_write_state(grpc_chttp2_transport* t,
- grpc_chttp2_write_state st, const char* reason) {
+
+static const char* write_state_name(grpc_chttp2_write_state st) {
+ switch (st) {
+ case GRPC_CHTTP2_WRITE_STATE_IDLE:
+ return "IDLE";
+ case GRPC_CHTTP2_WRITE_STATE_WRITING:
+ return "WRITING";
+ case GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE:
+ return "WRITING+MORE";
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
+
+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,
t->is_client ? "CLIENT" : "SERVER", t->peer_string.c_str(),
write_state_name(t->write_state), write_state_name(st), reason));
- t->write_state = st;
+ 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.
//
// This is also our chance to close the transport if the transport was marked
// 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) {
+ if (st == GRPC_CHTTP2_WRITE_STATE_IDLE) {
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;
- close_transport_locked(t, err);
- }
- }
-}
-
-static void inc_initiate_write_reason(
- grpc_chttp2_initiate_write_reason reason) {
- switch (reason) {
- case GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_INITIAL_METADATA:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_TRAILING_METADATA:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING();
- break;
+ if (t->close_transport_on_writes_finished != nullptr) {
+ grpc_error* err = t->close_transport_on_writes_finished;
+ t->close_transport_on_writes_finished = nullptr;
+ close_transport_locked(t, err);
+ }
+ }
+}
+
+static void inc_initiate_write_reason(
+ grpc_chttp2_initiate_write_reason reason) {
+ switch (reason) {
+ case GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_INITIAL_METADATA:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_TRAILING_METADATA:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING();
+ break;
case GRPC_CHTTP2_INITIATE_WRITE_BDP_PING:
GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING();
break;
- case GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE();
- break;
- case GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM:
- GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM();
- break;
- }
-}
-
-void grpc_chttp2_initiate_write(grpc_chttp2_transport* t,
- grpc_chttp2_initiate_write_reason reason) {
- GPR_TIMER_SCOPE("grpc_chttp2_initiate_write", 0);
-
- switch (t->write_state) {
- case GRPC_CHTTP2_WRITE_STATE_IDLE:
- inc_initiate_write_reason(reason);
- set_write_state(t, GRPC_CHTTP2_WRITE_STATE_WRITING,
- grpc_chttp2_initiate_write_reason_string(reason));
- GRPC_CHTTP2_REF_TRANSPORT(t, "writing");
+ case GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE();
+ break;
+ case GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM:
+ GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM();
+ break;
+ }
+}
+
+void grpc_chttp2_initiate_write(grpc_chttp2_transport* t,
+ grpc_chttp2_initiate_write_reason reason) {
+ GPR_TIMER_SCOPE("grpc_chttp2_initiate_write", 0);
+
+ switch (t->write_state) {
+ case GRPC_CHTTP2_WRITE_STATE_IDLE:
+ inc_initiate_write_reason(reason);
+ set_write_state(t, GRPC_CHTTP2_WRITE_STATE_WRITING,
+ grpc_chttp2_initiate_write_reason_string(reason));
+ GRPC_CHTTP2_REF_TRANSPORT(t, "writing");
// Note that the 'write_action_begin_locked' closure is being scheduled
// on the 'finally_scheduler' of t->combiner. This means that
// 'write_action_begin_locked' is called only *after* all the other
@@ -902,49 +902,49 @@ void grpc_chttp2_initiate_write(grpc_chttp2_transport* t,
// 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(
- GRPC_CLOSURE_INIT(&t->write_action_begin_locked,
+ GRPC_CLOSURE_INIT(&t->write_action_begin_locked,
write_action_begin_locked, t, nullptr),
- GRPC_ERROR_NONE);
- break;
- case GRPC_CHTTP2_WRITE_STATE_WRITING:
- set_write_state(t, GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE,
- grpc_chttp2_initiate_write_reason_string(reason));
- break;
- case GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE:
- break;
- }
-}
-
-void grpc_chttp2_mark_stream_writable(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- if (t->closed_with_error == GRPC_ERROR_NONE &&
- grpc_chttp2_list_add_writable_stream(t, s)) {
- GRPC_CHTTP2_STREAM_REF(s, "chttp2_writing:become");
- }
-}
-
+ GRPC_ERROR_NONE);
+ break;
+ case GRPC_CHTTP2_WRITE_STATE_WRITING:
+ set_write_state(t, GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE,
+ grpc_chttp2_initiate_write_reason_string(reason));
+ break;
+ case GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE:
+ break;
+ }
+}
+
+void grpc_chttp2_mark_stream_writable(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ if (t->closed_with_error == GRPC_ERROR_NONE &&
+ grpc_chttp2_list_add_writable_stream(t, s)) {
+ GRPC_CHTTP2_STREAM_REF(s, "chttp2_writing:become");
+ }
+}
+
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*/) {
- 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);
- grpc_chttp2_begin_write_result r;
- if (t->closed_with_error != GRPC_ERROR_NONE) {
- r.writing = false;
- } else {
- r = grpc_chttp2_begin_write(t);
- }
- if (r.writing) {
- if (r.partial) {
- GRPC_STATS_INC_HTTP2_PARTIAL_WRITES();
- }
+ 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);
+ grpc_chttp2_begin_write_result r;
+ if (t->closed_with_error != GRPC_ERROR_NONE) {
+ r.writing = false;
+ } else {
+ r = grpc_chttp2_begin_write(t);
+ }
+ if (r.writing) {
+ 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,
@@ -962,26 +962,26 @@ static void write_action_begin_locked(void* gt, grpc_error* /*error_ignored*/) {
t));
t->reading_paused_on_pending_induced_frames = false;
continue_read_action_locked(t);
- }
- } else {
- GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN();
- set_write_state(t, GRPC_CHTTP2_WRITE_STATE_IDLE, "begin writing nothing");
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "writing");
- }
-}
-
+ }
+ } else {
+ GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN();
+ set_write_state(t, GRPC_CHTTP2_WRITE_STATE_IDLE, "begin writing nothing");
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "writing");
+ }
+}
+
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);
+ 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_endpoint_write(
+ t->ep, &t->outbuf,
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,
@@ -991,36 +991,36 @@ static void write_action_end(void* tp, grpc_error* 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);
-
+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;
- if (error != GRPC_ERROR_NONE) {
- close_transport_locked(t, GRPC_ERROR_REF(error));
+ if (error != GRPC_ERROR_NONE) {
+ close_transport_locked(t, GRPC_ERROR_REF(error));
closed = true;
- }
-
- if (t->sent_goaway_state == GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED) {
- t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SENT;
+ }
+
+ if (t->sent_goaway_state == GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED) {
+ t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SENT;
closed = true;
- if (grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
- close_transport_locked(
- t, GRPC_ERROR_CREATE_FROM_STATIC_STRING("goaway sent"));
- }
- }
-
- switch (t->write_state) {
- case GRPC_CHTTP2_WRITE_STATE_IDLE:
- GPR_UNREACHABLE_CODE(break);
- case GRPC_CHTTP2_WRITE_STATE_WRITING:
- GPR_TIMER_MARK("state=writing", 0);
- set_write_state(t, GRPC_CHTTP2_WRITE_STATE_IDLE, "finish writing");
- break;
- case GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE:
- 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 (grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
+ close_transport_locked(
+ t, GRPC_ERROR_CREATE_FROM_STATIC_STRING("goaway sent"));
+ }
+ }
+
+ switch (t->write_state) {
+ case GRPC_CHTTP2_WRITE_STATE_IDLE:
+ GPR_UNREACHABLE_CODE(break);
+ case GRPC_CHTTP2_WRITE_STATE_WRITING:
+ GPR_TIMER_MARK("state=writing", 0);
+ set_write_state(t, GRPC_CHTTP2_WRITE_STATE_IDLE, "finish writing");
+ break;
+ case GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE:
+ 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
@@ -1030,49 +1030,49 @@ static void write_action_end_locked(void* tp, grpc_error* error) {
grpc_core::ExecCtx::RunList(DEBUG_LOCATION, &t->run_after_write);
}
t->combiner->FinallyRun(
- GRPC_CLOSURE_INIT(&t->write_action_begin_locked,
+ GRPC_CLOSURE_INIT(&t->write_action_begin_locked,
write_action_begin_locked, t, nullptr),
- GRPC_ERROR_NONE);
- break;
- }
-
- grpc_chttp2_end_write(t, GRPC_ERROR_REF(error));
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "writing");
-}
-
-// Dirties an HTTP2 setting to be sent out next time a writing path occurs.
-// If the change needs to occur immediately, manually initiate a write.
-static void queue_setting_update(grpc_chttp2_transport* t,
- grpc_chttp2_setting_id id, uint32_t value) {
- const grpc_chttp2_setting_parameters* sp =
- &grpc_chttp2_settings_parameters[id];
- uint32_t use_value = GPR_CLAMP(value, sp->min_value, sp->max_value);
- if (use_value != value) {
- gpr_log(GPR_INFO, "Requested parameter %s clamped from %d to %d", sp->name,
- value, use_value);
- }
- if (use_value != t->settings[GRPC_LOCAL_SETTINGS][id]) {
- t->settings[GRPC_LOCAL_SETTINGS][id] = use_value;
- t->dirtied_local_settings = 1;
- }
-}
-
-void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t,
- uint32_t goaway_error,
+ GRPC_ERROR_NONE);
+ break;
+ }
+
+ grpc_chttp2_end_write(t, GRPC_ERROR_REF(error));
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "writing");
+}
+
+// Dirties an HTTP2 setting to be sent out next time a writing path occurs.
+// If the change needs to occur immediately, manually initiate a write.
+static void queue_setting_update(grpc_chttp2_transport* t,
+ grpc_chttp2_setting_id id, uint32_t value) {
+ const grpc_chttp2_setting_parameters* sp =
+ &grpc_chttp2_settings_parameters[id];
+ uint32_t use_value = GPR_CLAMP(value, sp->min_value, sp->max_value);
+ if (use_value != value) {
+ gpr_log(GPR_INFO, "Requested parameter %s clamped from %d to %d", sp->name,
+ value, use_value);
+ }
+ if (use_value != t->settings[GRPC_LOCAL_SETTINGS][id]) {
+ t->settings[GRPC_LOCAL_SETTINGS][id] = use_value;
+ t->dirtied_local_settings = 1;
+ }
+}
+
+void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t,
+ uint32_t goaway_error,
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(
+ // 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_STR_RAW_BYTES, goaway_text);
-
+ 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));
@@ -1090,28 +1090,28 @@ void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t,
if (GPR_UNLIKELY(t->is_client &&
goaway_error == GRPC_HTTP2_ENHANCE_YOUR_CALM &&
grpc_slice_str_cmp(goaway_text, "too_many_pings") == 0)) {
- gpr_log(GPR_ERROR,
- "Received a GOAWAY with error code ENHANCE_YOUR_CALM and debug "
- "data equal to \"too_many_pings\"");
- double current_keepalive_time_ms = static_cast<double>(t->keepalive_time);
+ gpr_log(GPR_ERROR,
+ "Received a GOAWAY with error code ENHANCE_YOUR_CALM and debug "
+ "data equal to \"too_many_pings\"");
+ double current_keepalive_time_ms = static_cast<double>(t->keepalive_time);
constexpr int max_keepalive_time_ms =
INT_MAX / KEEPALIVE_TIME_BACKOFF_MULTIPLIER;
- t->keepalive_time =
+ t->keepalive_time =
current_keepalive_time_ms > static_cast<double>(max_keepalive_time_ms)
- ? GRPC_MILLIS_INF_FUTURE
- : static_cast<grpc_millis>(current_keepalive_time_ms *
- KEEPALIVE_TIME_BACKOFF_MULTIPLIER);
+ ? GRPC_MILLIS_INF_FUTURE
+ : static_cast<grpc_millis>(current_keepalive_time_ms *
+ KEEPALIVE_TIME_BACKOFF_MULTIPLIER);
status.SetPayload(grpc_core::kKeepaliveThrottlingKey,
y_absl::Cord(ToString(t->keepalive_time)));
- }
+ }
// lie: use transient failure from the transport to indicate goaway has been
// received.
connectivity_state_set(t, GRPC_CHANNEL_TRANSIENT_FAILURE, status,
"got_goaway");
-}
-
-static void maybe_start_some_streams(grpc_chttp2_transport* t) {
- grpc_chttp2_stream* s;
+}
+
+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)) {
@@ -1125,33 +1125,33 @@ static void maybe_start_some_streams(grpc_chttp2_transport* t) {
}
// start streams where we have free grpc_chttp2_stream ids and free
// * concurrency
- while (t->next_stream_id <= MAX_CLIENT_STREAM_ID &&
- grpc_chttp2_stream_map_size(&t->stream_map) <
- t->settings[GRPC_PEER_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS] &&
- grpc_chttp2_list_pop_waiting_for_concurrency(t, &s)) {
+ while (t->next_stream_id <= MAX_CLIENT_STREAM_ID &&
+ grpc_chttp2_stream_map_size(&t->stream_map) <
+ t->settings[GRPC_PEER_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS] &&
+ 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(
+ 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_ASSERT(s->id == 0);
- s->id = t->next_stream_id;
- t->next_stream_id += 2;
-
- if (t->next_stream_id >= MAX_CLIENT_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,
y_absl::Status(y_absl::StatusCode::kUnavailable,
"Transport Stream IDs exhausted"),
"no_more_stream_ids");
- }
-
- grpc_chttp2_stream_map_add(&t->stream_map, s->id, s);
- post_destructive_reclaimer(t);
- grpc_chttp2_mark_stream_writable(t, s);
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM);
- }
+ }
+
+ grpc_chttp2_stream_map_add(&t->stream_map, s->id, s);
+ post_destructive_reclaimer(t);
+ grpc_chttp2_mark_stream_writable(t, s);
+ 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)) {
@@ -1161,150 +1161,150 @@ static void maybe_start_some_streams(grpc_chttp2_transport* t) {
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Stream IDs exhausted"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
}
- }
-}
-
+ }
+}
+
// Flag that this closure barrier may be covering a write in a pollset, and so
// we should not complete this closure until we can prove that the write got
// scheduled
#define CLOSURE_BARRIER_MAY_COVER_WRITE (1 << 0)
// First bit of the reference count, stored in the high order bits (with the low
// bits being used for flags defined above)
-#define CLOSURE_BARRIER_FIRST_REF_BIT (1 << 16)
-
-static grpc_closure* add_closure_barrier(grpc_closure* closure) {
- closure->next_data.scratch += CLOSURE_BARRIER_FIRST_REF_BIT;
- return closure;
-}
-
+#define CLOSURE_BARRIER_FIRST_REF_BIT (1 << 16)
+
+static grpc_closure* add_closure_barrier(grpc_closure* closure) {
+ closure->next_data.scratch += CLOSURE_BARRIER_FIRST_REF_BIT;
+ return closure;
+}
+
static void null_then_sched_closure(grpc_closure** closure) {
- grpc_closure* c = *closure;
- *closure = nullptr;
+ grpc_closure* c = *closure;
+ *closure = nullptr;
grpc_core::ExecCtx::Run(DEBUG_LOCATION, c, GRPC_ERROR_NONE);
-}
-
-void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
+}
+
+void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
grpc_chttp2_stream* /*s*/,
- grpc_closure** pclosure,
- grpc_error* error, const char* desc) {
- grpc_closure* closure = *pclosure;
- *pclosure = nullptr;
- if (closure == nullptr) {
- GRPC_ERROR_UNREF(error);
- return;
- }
- closure->next_data.scratch -= CLOSURE_BARRIER_FIRST_REF_BIT;
+ grpc_closure** pclosure,
+ grpc_error* error, const char* desc) {
+ grpc_closure* closure = *pclosure;
+ *pclosure = nullptr;
+ if (closure == nullptr) {
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
+ closure->next_data.scratch -= CLOSURE_BARRIER_FIRST_REF_BIT;
if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
- const char* errstr = grpc_error_string(error);
- gpr_log(
- GPR_INFO,
- "complete_closure_step: t=%p %p refs=%d flags=0x%04x desc=%s err=%s "
- "write_state=%s",
- t, closure,
- static_cast<int>(closure->next_data.scratch /
- CLOSURE_BARRIER_FIRST_REF_BIT),
- static_cast<int>(closure->next_data.scratch %
- CLOSURE_BARRIER_FIRST_REF_BIT),
- desc, errstr, write_state_name(t->write_state));
- }
- if (error != GRPC_ERROR_NONE) {
- if (closure->error_data.error == GRPC_ERROR_NONE) {
- closure->error_data.error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Error in HTTP transport completing operation");
- closure->error_data.error = grpc_error_set_str(
- closure->error_data.error, GRPC_ERROR_STR_TARGET_ADDRESS,
+ const char* errstr = grpc_error_string(error);
+ gpr_log(
+ GPR_INFO,
+ "complete_closure_step: t=%p %p refs=%d flags=0x%04x desc=%s err=%s "
+ "write_state=%s",
+ t, closure,
+ static_cast<int>(closure->next_data.scratch /
+ CLOSURE_BARRIER_FIRST_REF_BIT),
+ static_cast<int>(closure->next_data.scratch %
+ CLOSURE_BARRIER_FIRST_REF_BIT),
+ desc, errstr, write_state_name(t->write_state));
+ }
+ if (error != GRPC_ERROR_NONE) {
+ if (closure->error_data.error == GRPC_ERROR_NONE) {
+ closure->error_data.error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Error in HTTP transport completing operation");
+ closure->error_data.error = grpc_error_set_str(
+ closure->error_data.error, GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_copied_string(t->peer_string.c_str()));
- }
- closure->error_data.error =
- grpc_error_add_child(closure->error_data.error, error);
- }
- 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)) {
+ }
+ closure->error_data.error =
+ grpc_error_add_child(closure->error_data.error, error);
+ }
+ 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);
- } else {
- grpc_closure_list_append(&t->run_after_write, closure,
- closure->error_data.error);
- }
- }
-}
-
-static bool contains_non_ok_status(grpc_metadata_batch* batch) {
- if (batch->idx.named.grpc_status != nullptr) {
+ } else {
+ grpc_closure_list_append(&t->run_after_write, closure,
+ closure->error_data.error);
+ }
+ }
+}
+
+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 false;
-}
-
-static void maybe_become_writable_due_to_send_msg(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- if (s->id != 0 && (!s->write_buffering ||
- s->flow_controlled_buffer.length > t->write_buffer_size)) {
- grpc_chttp2_mark_stream_writable(t, s);
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE);
- }
-}
-
-static void add_fetched_slice_locked(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- s->fetched_send_message_length +=
- static_cast<uint32_t> GRPC_SLICE_LENGTH(s->fetching_slice);
- grpc_slice_buffer_add(&s->flow_controlled_buffer, s->fetching_slice);
- maybe_become_writable_due_to_send_msg(t, s);
-}
-
-static void continue_fetching_send_locked(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- for (;;) {
- if (s->fetching_send_message == nullptr) {
+ }
+ return false;
+}
+
+static void maybe_become_writable_due_to_send_msg(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ if (s->id != 0 && (!s->write_buffering ||
+ s->flow_controlled_buffer.length > t->write_buffer_size)) {
+ grpc_chttp2_mark_stream_writable(t, s);
+ grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE);
+ }
+}
+
+static void add_fetched_slice_locked(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ s->fetched_send_message_length +=
+ static_cast<uint32_t> GRPC_SLICE_LENGTH(s->fetching_slice);
+ grpc_slice_buffer_add(&s->flow_controlled_buffer, s->fetching_slice);
+ maybe_become_writable_due_to_send_msg(t, s);
+}
+
+static void continue_fetching_send_locked(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ for (;;) {
+ if (s->fetching_send_message == nullptr) {
// Stream was cancelled before message fetch completed
- abort(); /* TODO(ctiller): what cleanup here? */
- return; /* early out */
- }
- if (s->fetched_send_message_length == s->fetching_send_message->length()) {
- int64_t notify_offset = s->next_message_end_offset;
- if (notify_offset <= s->flow_controlled_bytes_written) {
- grpc_chttp2_complete_closure_step(
- t, s, &s->fetching_send_message_finished, GRPC_ERROR_NONE,
- "fetching_send_message_finished");
- } else {
- grpc_chttp2_write_cb* cb = t->write_cb_pool;
- if (cb == nullptr) {
- cb = static_cast<grpc_chttp2_write_cb*>(gpr_malloc(sizeof(*cb)));
- } else {
- t->write_cb_pool = cb->next;
- }
- cb->call_at_byte = notify_offset;
- cb->closure = s->fetching_send_message_finished;
- s->fetching_send_message_finished = nullptr;
- grpc_chttp2_write_cb** list =
- s->fetching_send_message->flags() & GRPC_WRITE_THROUGH
- ? &s->on_write_finished_cbs
- : &s->on_flow_controlled_cbs;
- cb->next = *list;
- *list = cb;
- }
- s->fetching_send_message.reset();
- return; /* early out */
+ abort(); /* TODO(ctiller): what cleanup here? */
+ return; /* early out */
+ }
+ if (s->fetched_send_message_length == s->fetching_send_message->length()) {
+ int64_t notify_offset = s->next_message_end_offset;
+ if (notify_offset <= s->flow_controlled_bytes_written) {
+ grpc_chttp2_complete_closure_step(
+ t, s, &s->fetching_send_message_finished, GRPC_ERROR_NONE,
+ "fetching_send_message_finished");
+ } else {
+ grpc_chttp2_write_cb* cb = t->write_cb_pool;
+ if (cb == nullptr) {
+ cb = static_cast<grpc_chttp2_write_cb*>(gpr_malloc(sizeof(*cb)));
+ } else {
+ t->write_cb_pool = cb->next;
+ }
+ cb->call_at_byte = notify_offset;
+ cb->closure = s->fetching_send_message_finished;
+ s->fetching_send_message_finished = nullptr;
+ grpc_chttp2_write_cb** list =
+ s->fetching_send_message->flags() & GRPC_WRITE_THROUGH
+ ? &s->on_write_finished_cbs
+ : &s->on_flow_controlled_cbs;
+ cb->next = *list;
+ *list = cb;
+ }
+ 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))) {
- grpc_error* error = s->fetching_send_message->Pull(&s->fetching_slice);
- if (error != GRPC_ERROR_NONE) {
- s->fetching_send_message.reset();
- grpc_chttp2_cancel_stream(t, s, error);
- } else {
- add_fetched_slice_locked(t, s);
- }
- }
- }
-}
-
+ grpc_error* error = s->fetching_send_message->Pull(&s->fetching_slice);
+ if (error != GRPC_ERROR_NONE) {
+ s->fetching_send_message.reset();
+ grpc_chttp2_cancel_stream(t, s, error);
+ } else {
+ add_fetched_slice_locked(t, s);
+ }
+ }
+ }
+}
+
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,
@@ -1312,107 +1312,107 @@ static void complete_fetch(void* gs, grpc_error* error) {
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;
- if (error == GRPC_ERROR_NONE) {
- error = s->fetching_send_message->Pull(&s->fetching_slice);
- if (error == GRPC_ERROR_NONE) {
- add_fetched_slice_locked(t, s);
- continue_fetching_send_locked(t, s);
- }
- }
- if (error != GRPC_ERROR_NONE) {
- s->fetching_send_message.reset();
- grpc_chttp2_cancel_stream(t, s, error);
- }
-}
-
-static void log_metadata(const grpc_metadata_batch* md_batch, uint32_t id,
- bool is_client, bool is_initial) {
- for (grpc_linked_mdelem* md = md_batch->list.head; md != nullptr;
- md = md->next) {
- char* key = grpc_slice_to_c_string(GRPC_MDKEY(md->md));
- char* value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md));
- gpr_log(GPR_INFO, "HTTP:%d:%s:%s: %s: %s", id, is_initial ? "HDR" : "TRL",
- is_client ? "CLI" : "SVR", key, value);
- gpr_free(key);
- gpr_free(value);
- }
-}
-
-static void perform_stream_op_locked(void* stream_op,
+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;
+ if (error == GRPC_ERROR_NONE) {
+ error = s->fetching_send_message->Pull(&s->fetching_slice);
+ if (error == GRPC_ERROR_NONE) {
+ add_fetched_slice_locked(t, s);
+ continue_fetching_send_locked(t, s);
+ }
+ }
+ if (error != GRPC_ERROR_NONE) {
+ s->fetching_send_message.reset();
+ grpc_chttp2_cancel_stream(t, s, error);
+ }
+}
+
+static void log_metadata(const grpc_metadata_batch* md_batch, uint32_t id,
+ bool is_client, bool is_initial) {
+ for (grpc_linked_mdelem* md = md_batch->list.head; md != nullptr;
+ md = md->next) {
+ char* key = grpc_slice_to_c_string(GRPC_MDKEY(md->md));
+ char* value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md));
+ gpr_log(GPR_INFO, "HTTP:%d:%s:%s: %s: %s", id, is_initial ? "HDR" : "TRL",
+ is_client ? "CLI" : "SVR", key, value);
+ gpr_free(key);
+ gpr_free(value);
+ }
+}
+
+static void perform_stream_op_locked(void* stream_op,
grpc_error* /*error_ignored*/) {
- GPR_TIMER_SCOPE("perform_stream_op_locked", 0);
-
- grpc_transport_stream_op_batch* op =
- static_cast<grpc_transport_stream_op_batch*>(stream_op);
- grpc_chttp2_stream* s =
- static_cast<grpc_chttp2_stream*>(op->handler_private.extra_arg);
- grpc_transport_stream_op_batch_payload* op_payload = op->payload;
- grpc_chttp2_transport* t = s->t;
-
- GRPC_STATS_INC_HTTP2_OP_BATCHES();
-
+ GPR_TIMER_SCOPE("perform_stream_op_locked", 0);
+
+ grpc_transport_stream_op_batch* op =
+ static_cast<grpc_transport_stream_op_batch*>(stream_op);
+ grpc_chttp2_stream* s =
+ static_cast<grpc_chttp2_stream*>(op->handler_private.extra_arg);
+ grpc_transport_stream_op_batch_payload* op_payload = op->payload;
+ grpc_chttp2_transport* t = s->t;
+
+ GRPC_STATS_INC_HTTP2_OP_BATCHES();
+
s->context = op->payload->context;
s->traced = op->is_traced;
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) {
- log_metadata(op_payload->send_initial_metadata.send_initial_metadata,
- s->id, t->is_client, true);
- }
- if (op->send_trailing_metadata) {
- log_metadata(op_payload->send_trailing_metadata.send_trailing_metadata,
- s->id, t->is_client, false);
- }
- }
-
- grpc_closure* on_complete = op->on_complete;
+ if (op->send_initial_metadata) {
+ log_metadata(op_payload->send_initial_metadata.send_initial_metadata,
+ s->id, t->is_client, true);
+ }
+ if (op->send_trailing_metadata) {
+ log_metadata(op_payload->send_trailing_metadata.send_trailing_metadata,
+ s->id, t->is_client, false);
+ }
+ }
+
+ 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;
- }
-
- if (op->cancel_stream) {
- GRPC_STATS_INC_HTTP2_OP_CANCEL();
- grpc_chttp2_cancel_stream(t, s, op_payload->cancel_stream.cancel_error);
- }
-
- if (op->send_initial_metadata) {
+ }
+
+ if (op->cancel_stream) {
+ GRPC_STATS_INC_HTTP2_OP_CANCEL();
+ grpc_chttp2_cancel_stream(t, s, op_payload->cancel_stream.cancel_error);
+ }
+
+ if (op->send_initial_metadata) {
if (t->is_client && t->channelz_socket != nullptr) {
t->channelz_socket->RecordStreamStartedFromLocal();
}
- GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA();
- GPR_ASSERT(s->send_initial_metadata_finished == nullptr);
- on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE;
-
+ GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA();
+ GPR_ASSERT(s->send_initial_metadata_finished == nullptr);
+ on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE;
+
// Identify stream compression
- if (op_payload->send_initial_metadata.send_initial_metadata->idx.named
- .content_encoding == nullptr ||
- grpc_stream_compression_method_parse(
- GRPC_MDVALUE(
- op_payload->send_initial_metadata.send_initial_metadata->idx
- .named.content_encoding->md),
- true, &s->stream_compression_method) == 0) {
- s->stream_compression_method = GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS;
- }
+ if (op_payload->send_initial_metadata.send_initial_metadata->idx.named
+ .content_encoding == nullptr ||
+ grpc_stream_compression_method_parse(
+ GRPC_MDVALUE(
+ op_payload->send_initial_metadata.send_initial_metadata->idx
+ .named.content_encoding->md),
+ 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);
}
- s->send_initial_metadata_finished = add_closure_barrier(on_complete);
- s->send_initial_metadata =
- op_payload->send_initial_metadata.send_initial_metadata;
- if (t->is_client) {
- s->deadline = GPR_MIN(s->deadline, s->send_initial_metadata->deadline);
- }
+ s->send_initial_metadata_finished = add_closure_barrier(on_complete);
+ s->send_initial_metadata =
+ op_payload->send_initial_metadata.send_initial_metadata;
+ if (t->is_client) {
+ s->deadline = GPR_MIN(s->deadline, s->send_initial_metadata->deadline);
+ }
if (contains_non_ok_status(s->send_initial_metadata)) {
s->seen_error = true;
}
@@ -1425,12 +1425,12 @@ static void perform_stream_op_locked(void* stream_op,
} else {
grpc_chttp2_cancel_stream(
t, s,
- grpc_error_set_int(
+ grpc_error_set_int(
GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Transport closed", &t->closed_with_error, 1),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
- }
- } else {
+ }
+ } else {
GPR_ASSERT(s->id != 0);
grpc_chttp2_mark_stream_writable(t, s);
if (!(op->send_message &&
@@ -1439,7 +1439,7 @@ static void perform_stream_op_locked(void* stream_op,
grpc_chttp2_initiate_write(
t, GRPC_CHTTP2_INITIATE_WRITE_SEND_INITIAL_METADATA);
}
- }
+ }
} else {
s->send_initial_metadata = nullptr;
grpc_chttp2_complete_closure_step(
@@ -1448,70 +1448,70 @@ static void perform_stream_op_locked(void* stream_op,
"Attempt to send initial metadata after stream was closed",
&s->write_closed_error, 1),
"send_initial_metadata_finished");
- }
- if (op_payload->send_initial_metadata.peer_string != nullptr) {
+ }
+ if (op_payload->send_initial_metadata.peer_string != nullptr) {
gpr_atm_rel_store(op_payload->send_initial_metadata.peer_string,
(gpr_atm)t->peer_string.c_str());
- }
- }
-
- if (op->send_message) {
- GRPC_STATS_INC_HTTP2_OP_SEND_MESSAGE();
+ }
+ }
+
+ if (op->send_message) {
+ GRPC_STATS_INC_HTTP2_OP_SEND_MESSAGE();
t->num_messages_in_next_write++;
- GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE(
- op->payload->send_message.send_message->length());
- 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) {
+ GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE(
+ op->payload->send_message.send_message->length());
+ 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.send_message.reset();
- grpc_chttp2_complete_closure_step(
+ op->payload->send_message.send_message.reset();
+ grpc_chttp2_complete_closure_step(
t, s, &s->fetching_send_message_finished, GRPC_ERROR_NONE,
- "fetching_send_message_finished");
- } else {
- GPR_ASSERT(s->fetching_send_message == nullptr);
- uint8_t* frame_hdr = grpc_slice_buffer_tiny_add(
- &s->flow_controlled_buffer, GRPC_HEADER_SIZE_IN_BYTES);
- uint32_t flags = op_payload->send_message.send_message->flags();
- frame_hdr[0] = (flags & GRPC_WRITE_INTERNAL_COMPRESS) != 0;
- size_t len = op_payload->send_message.send_message->length();
- frame_hdr[1] = static_cast<uint8_t>(len >> 24);
- frame_hdr[2] = static_cast<uint8_t>(len >> 16);
- frame_hdr[3] = static_cast<uint8_t>(len >> 8);
- frame_hdr[4] = static_cast<uint8_t>(len);
- s->fetching_send_message =
- std::move(op_payload->send_message.send_message);
- s->fetched_send_message_length = 0;
- s->next_message_end_offset =
- s->flow_controlled_bytes_written +
- static_cast<int64_t>(s->flow_controlled_buffer.length) +
- static_cast<int64_t>(len);
- if (flags & GRPC_WRITE_BUFFER_HINT) {
- s->next_message_end_offset -= t->write_buffer_size;
- s->write_buffering = true;
- } else {
- s->write_buffering = false;
- }
- continue_fetching_send_locked(t, s);
- maybe_become_writable_due_to_send_msg(t, s);
- }
- }
-
- if (op->send_trailing_metadata) {
- GRPC_STATS_INC_HTTP2_OP_SEND_TRAILING_METADATA();
- GPR_ASSERT(s->send_trailing_metadata_finished == nullptr);
- on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE;
- s->send_trailing_metadata_finished = add_closure_barrier(on_complete);
- s->send_trailing_metadata =
- op_payload->send_trailing_metadata.send_trailing_metadata;
+ "fetching_send_message_finished");
+ } else {
+ GPR_ASSERT(s->fetching_send_message == nullptr);
+ uint8_t* frame_hdr = grpc_slice_buffer_tiny_add(
+ &s->flow_controlled_buffer, GRPC_HEADER_SIZE_IN_BYTES);
+ uint32_t flags = op_payload->send_message.send_message->flags();
+ frame_hdr[0] = (flags & GRPC_WRITE_INTERNAL_COMPRESS) != 0;
+ size_t len = op_payload->send_message.send_message->length();
+ frame_hdr[1] = static_cast<uint8_t>(len >> 24);
+ frame_hdr[2] = static_cast<uint8_t>(len >> 16);
+ frame_hdr[3] = static_cast<uint8_t>(len >> 8);
+ frame_hdr[4] = static_cast<uint8_t>(len);
+ s->fetching_send_message =
+ std::move(op_payload->send_message.send_message);
+ s->fetched_send_message_length = 0;
+ s->next_message_end_offset =
+ s->flow_controlled_bytes_written +
+ static_cast<int64_t>(s->flow_controlled_buffer.length) +
+ static_cast<int64_t>(len);
+ if (flags & GRPC_WRITE_BUFFER_HINT) {
+ s->next_message_end_offset -= t->write_buffer_size;
+ s->write_buffering = true;
+ } else {
+ s->write_buffering = false;
+ }
+ continue_fetching_send_locked(t, s);
+ maybe_become_writable_due_to_send_msg(t, s);
+ }
+ }
+
+ if (op->send_trailing_metadata) {
+ GRPC_STATS_INC_HTTP2_OP_SEND_TRAILING_METADATA();
+ GPR_ASSERT(s->send_trailing_metadata_finished == nullptr);
+ on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE;
+ s->send_trailing_metadata_finished = add_closure_barrier(on_complete);
+ s->send_trailing_metadata =
+ op_payload->send_trailing_metadata.send_trailing_metadata;
s->sent_trailing_metadata_op = op_payload->send_trailing_metadata.sent;
- s->write_buffering = false;
+ s->write_buffering = false;
if (contains_non_ok_status(s->send_trailing_metadata)) {
s->seen_error = true;
- }
+ }
if (s->write_closed) {
s->send_trailing_metadata = nullptr;
s->sent_trailing_metadata_op = nullptr;
@@ -1531,134 +1531,134 @@ static void perform_stream_op_locked(void* stream_op,
grpc_chttp2_initiate_write(
t, GRPC_CHTTP2_INITIATE_WRITE_SEND_TRAILING_METADATA);
}
- }
-
- if (op->recv_initial_metadata) {
- GRPC_STATS_INC_HTTP2_OP_RECV_INITIAL_METADATA();
- GPR_ASSERT(s->recv_initial_metadata_ready == nullptr);
- s->recv_initial_metadata_ready =
- op_payload->recv_initial_metadata.recv_initial_metadata_ready;
- s->recv_initial_metadata =
- op_payload->recv_initial_metadata.recv_initial_metadata;
- s->trailing_metadata_available =
- op_payload->recv_initial_metadata.trailing_metadata_available;
- if (op_payload->recv_initial_metadata.peer_string != nullptr) {
+ }
+
+ if (op->recv_initial_metadata) {
+ GRPC_STATS_INC_HTTP2_OP_RECV_INITIAL_METADATA();
+ GPR_ASSERT(s->recv_initial_metadata_ready == nullptr);
+ s->recv_initial_metadata_ready =
+ op_payload->recv_initial_metadata.recv_initial_metadata_ready;
+ s->recv_initial_metadata =
+ op_payload->recv_initial_metadata.recv_initial_metadata;
+ s->trailing_metadata_available =
+ op_payload->recv_initial_metadata.trailing_metadata_available;
+ if (op_payload->recv_initial_metadata.peer_string != nullptr) {
gpr_atm_rel_store(op_payload->recv_initial_metadata.peer_string,
(gpr_atm)t->peer_string.c_str());
- }
- grpc_chttp2_maybe_complete_recv_initial_metadata(t, s);
- }
-
- if (op->recv_message) {
- GRPC_STATS_INC_HTTP2_OP_RECV_MESSAGE();
- size_t before = 0;
- GPR_ASSERT(s->recv_message_ready == nullptr);
- GPR_ASSERT(!s->pending_byte_stream);
- s->recv_message_ready = op_payload->recv_message.recv_message_ready;
- s->recv_message = op_payload->recv_message.recv_message;
- if (s->id != 0) {
- if (!s->read_closed) {
- before = s->frame_storage.length +
- s->unprocessed_incoming_frames_buffer.length;
- }
- }
- grpc_chttp2_maybe_complete_recv_message(t, s);
- if (s->id != 0) {
- if (!s->read_closed && s->frame_storage.length == 0) {
- size_t after = s->frame_storage.length +
- s->unprocessed_incoming_frames_buffer_cached_length;
- s->flow_control->IncomingByteStreamUpdate(GRPC_HEADER_SIZE_IN_BYTES,
- before - after);
- grpc_chttp2_act_on_flowctl_action(s->flow_control->MakeAction(), t, s);
- }
- }
- }
-
- if (op->recv_trailing_metadata) {
- GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA();
+ }
+ grpc_chttp2_maybe_complete_recv_initial_metadata(t, s);
+ }
+
+ if (op->recv_message) {
+ GRPC_STATS_INC_HTTP2_OP_RECV_MESSAGE();
+ size_t before = 0;
+ GPR_ASSERT(s->recv_message_ready == nullptr);
+ GPR_ASSERT(!s->pending_byte_stream);
+ s->recv_message_ready = op_payload->recv_message.recv_message_ready;
+ s->recv_message = op_payload->recv_message.recv_message;
+ if (s->id != 0) {
+ if (!s->read_closed) {
+ before = s->frame_storage.length +
+ s->unprocessed_incoming_frames_buffer.length;
+ }
+ }
+ grpc_chttp2_maybe_complete_recv_message(t, s);
+ if (s->id != 0) {
+ if (!s->read_closed && s->frame_storage.length == 0) {
+ size_t after = s->frame_storage.length +
+ s->unprocessed_incoming_frames_buffer_cached_length;
+ s->flow_control->IncomingByteStreamUpdate(GRPC_HEADER_SIZE_IN_BYTES,
+ before - after);
+ grpc_chttp2_act_on_flowctl_action(s->flow_control->MakeAction(), t, s);
+ }
+ }
+ }
+
+ if (op->recv_trailing_metadata) {
+ GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA();
GPR_ASSERT(s->collecting_stats == nullptr);
s->collecting_stats = op_payload->recv_trailing_metadata.collect_stats;
- GPR_ASSERT(s->recv_trailing_metadata_finished == nullptr);
+ GPR_ASSERT(s->recv_trailing_metadata_finished == nullptr);
s->recv_trailing_metadata_finished =
op_payload->recv_trailing_metadata.recv_trailing_metadata_ready;
- s->recv_trailing_metadata =
- op_payload->recv_trailing_metadata.recv_trailing_metadata;
- s->final_metadata_requested = true;
- grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
- }
-
+ s->recv_trailing_metadata =
+ op_payload->recv_trailing_metadata.recv_trailing_metadata;
+ s->final_metadata_requested = true;
+ 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");
}
-
- GRPC_CHTTP2_STREAM_UNREF(s, "perform_stream_op");
-}
-
-static void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
- grpc_transport_stream_op_batch* op) {
- GPR_TIMER_SCOPE("perform_stream_op", 0);
- grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
- grpc_chttp2_stream* s = reinterpret_cast<grpc_chttp2_stream*>(gs);
-
- if (!t->is_client) {
- if (op->send_initial_metadata) {
- grpc_millis deadline =
- op->payload->send_initial_metadata.send_initial_metadata->deadline;
- GPR_ASSERT(deadline == GRPC_MILLIS_INF_FUTURE);
- }
- if (op->send_trailing_metadata) {
- grpc_millis deadline =
- op->payload->send_trailing_metadata.send_trailing_metadata->deadline;
- GPR_ASSERT(deadline == GRPC_MILLIS_INF_FUTURE);
- }
- }
-
+
+ GRPC_CHTTP2_STREAM_UNREF(s, "perform_stream_op");
+}
+
+static void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
+ grpc_transport_stream_op_batch* op) {
+ GPR_TIMER_SCOPE("perform_stream_op", 0);
+ grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt);
+ grpc_chttp2_stream* s = reinterpret_cast<grpc_chttp2_stream*>(gs);
+
+ if (!t->is_client) {
+ if (op->send_initial_metadata) {
+ grpc_millis deadline =
+ op->payload->send_initial_metadata.send_initial_metadata->deadline;
+ GPR_ASSERT(deadline == GRPC_MILLIS_INF_FUTURE);
+ }
+ if (op->send_trailing_metadata) {
+ grpc_millis deadline =
+ op->payload->send_trailing_metadata.send_trailing_metadata->deadline;
+ GPR_ASSERT(deadline == GRPC_MILLIS_INF_FUTURE);
+ }
+ }
+
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;
+ 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);
-}
-
-static void cancel_pings(grpc_chttp2_transport* t, grpc_error* error) {
+}
+
+static void cancel_pings(grpc_chttp2_transport* t, grpc_error* error) {
// callback remaining pings: they're not allowed to call into the transport,
// and maybe they hold resources that need to be freed
- grpc_chttp2_ping_queue* pq = &t->ping_queue;
- 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_chttp2_ping_queue* pq = &t->ping_queue;
+ 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_ERROR_UNREF(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_ERROR_UNREF(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));
- return;
- }
- grpc_chttp2_ping_queue* pq = &t->ping_queue;
- grpc_closure_list_append(&pq->lists[GRPC_CHTTP2_PCL_INITIATE], on_initiate,
- GRPC_ERROR_NONE);
- grpc_closure_list_append(&pq->lists[GRPC_CHTTP2_PCL_NEXT], on_ack,
- GRPC_ERROR_NONE);
-}
-
+ return;
+ }
+ grpc_chttp2_ping_queue* pq = &t->ping_queue;
+ grpc_closure_list_append(&pq->lists[GRPC_CHTTP2_PCL_INITIATE], on_initiate,
+ GRPC_ERROR_NONE);
+ grpc_closure_list_append(&pq->lists[GRPC_CHTTP2_PCL_NEXT], on_ack,
+ GRPC_ERROR_NONE);
+}
+
// Specialized form of send_ping_locked for keepalive ping. If there is already
// a ping in progress, the keepalive ping would piggyback onto that ping,
// 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) {
+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),
GRPC_ERROR_REF(t->closed_with_error));
@@ -1666,10 +1666,10 @@ static void send_keepalive_ping_locked(grpc_chttp2_transport* t) {
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])) {
+ 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),
@@ -1679,8 +1679,8 @@ static void send_keepalive_ping_locked(grpc_chttp2_transport* t) {
GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked,
finish_keepalive_ping, t, grpc_schedule_on_exec_ctx),
GRPC_ERROR_NONE);
- return;
- }
+ return;
+ }
grpc_closure_list_append(
&pq->lists[GRPC_CHTTP2_PCL_INITIATE],
GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked, start_keepalive_ping,
@@ -1691,8 +1691,8 @@ static void send_keepalive_ping_locked(grpc_chttp2_transport* t) {
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,
@@ -1700,60 +1700,60 @@ void grpc_chttp2_retry_initiate_ping(void* tp, grpc_error* error) {
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;
- if (error == GRPC_ERROR_NONE) {
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING);
- }
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "retry_initiate_ping_locked");
-}
-
-void grpc_chttp2_ack_ping(grpc_chttp2_transport* t, uint64_t id) {
- grpc_chttp2_ping_queue* pq = &t->ping_queue;
- if (pq->inflight_id != id) {
+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;
+ if (error == GRPC_ERROR_NONE) {
+ grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING);
+ }
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "retry_initiate_ping_locked");
+}
+
+void grpc_chttp2_ack_ping(grpc_chttp2_transport* t, uint64_t id) {
+ grpc_chttp2_ping_queue* pq = &t->ping_queue;
+ if (pq->inflight_id != id) {
gpr_log(GPR_DEBUG, "Unknown ping response from %s: %" PRIx64,
t->peer_string.c_str(), id);
- return;
- }
+ return;
+ }
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);
- }
-}
-
-static void send_goaway(grpc_chttp2_transport* t, grpc_error* error) {
+ if (!grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_NEXT])) {
+ grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS);
+ }
+}
+
+static void send_goaway(grpc_chttp2_transport* t, grpc_error* error) {
// We want to log this irrespective of whether http tracing is enabled
gpr_log(GPR_INFO, "%s: Sending goaway err=%s", t->peer_string.c_str(),
grpc_error_string(error));
- t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED;
- grpc_http2_error_code http_error;
- grpc_slice slice;
- grpc_error_get_status(error, GRPC_MILLIS_INF_FUTURE, nullptr, &slice,
- &http_error, nullptr);
- grpc_chttp2_goaway_append(t->last_new_stream_id,
- static_cast<uint32_t>(http_error),
- grpc_slice_ref_internal(slice), &t->qbuf);
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT);
- GRPC_ERROR_UNREF(error);
-}
-
-void grpc_chttp2_add_ping_strike(grpc_chttp2_transport* t) {
- if (++t->ping_recv_state.ping_strikes > t->ping_policy.max_ping_strikes &&
- t->ping_policy.max_ping_strikes != 0) {
- send_goaway(t,
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("too_many_pings"),
- GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_ENHANCE_YOUR_CALM));
+ t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED;
+ grpc_http2_error_code http_error;
+ grpc_slice slice;
+ grpc_error_get_status(error, GRPC_MILLIS_INF_FUTURE, nullptr, &slice,
+ &http_error, nullptr);
+ grpc_chttp2_goaway_append(t->last_new_stream_id,
+ static_cast<uint32_t>(http_error),
+ grpc_slice_ref_internal(slice), &t->qbuf);
+ grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT);
+ GRPC_ERROR_UNREF(error);
+}
+
+void grpc_chttp2_add_ping_strike(grpc_chttp2_transport* t) {
+ if (++t->ping_recv_state.ping_strikes > t->ping_policy.max_ping_strikes &&
+ t->ping_policy.max_ping_strikes != 0) {
+ send_goaway(t,
+ grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("too_many_pings"),
+ GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_ENHANCE_YOUR_CALM));
// The transport will be closed after the write is done
- close_transport_locked(
- t, grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Too many pings"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
- }
-}
-
+ close_transport_locked(
+ t, grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Too many pings"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
+ }
+}
+
void grpc_chttp2_reset_ping_clock(grpc_chttp2_transport* t) {
if (!t->is_client) {
t->ping_recv_state.last_ping_recv_time = GRPC_MILLIS_INF_PAST;
@@ -1763,186 +1763,186 @@ void grpc_chttp2_reset_ping_clock(grpc_chttp2_transport* t) {
t->ping_policy.max_pings_without_data;
}
-static void perform_transport_op_locked(void* stream_op,
+static void perform_transport_op_locked(void* stream_op,
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);
-
- if (op->goaway_error) {
- send_goaway(t, op->goaway_error);
- }
-
- if (op->set_accept_stream) {
+ 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);
+
+ if (op->goaway_error) {
+ send_goaway(t, op->goaway_error);
+ }
+
+ 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;
- }
-
- if (op->bind_pollset) {
- grpc_endpoint_add_to_pollset(t->ep, op->bind_pollset);
- }
-
- if (op->bind_pollset_set) {
- grpc_endpoint_add_to_pollset_set(t->ep, op->bind_pollset_set);
- }
-
- if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
- send_ping_locked(t, op->send_ping.on_initiate, op->send_ping.on_ack);
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING);
- }
-
+ }
+
+ if (op->bind_pollset) {
+ grpc_endpoint_add_to_pollset(t->ep, op->bind_pollset);
+ }
+
+ if (op->bind_pollset_set) {
+ grpc_endpoint_add_to_pollset_set(t->ep, op->bind_pollset_set);
+ }
+
+ if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
+ send_ping_locked(t, op->send_ping.on_initiate, op->send_ping.on_ack);
+ 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->disconnect_with_error != GRPC_ERROR_NONE) {
- close_transport_locked(t, op->disconnect_with_error);
- }
-
+
+ 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_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);
+
+ 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)) {
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");
+ 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);
-}
-
+}
+
//
// INPUT PROCESSING - GENERAL
//
-
+
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) {
- grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
- if (!s->pending_byte_stream) {
- grpc_slice_buffer_reset_and_unref_internal(
- &s->unprocessed_incoming_frames_buffer);
- }
- }
- grpc_chttp2_incoming_metadata_buffer_publish(&s->metadata_buffer[0],
- s->recv_initial_metadata);
+ if (s->recv_initial_metadata_ready != nullptr &&
+ s->published_metadata[0] != GRPC_METADATA_NOT_PUBLISHED) {
+ if (s->seen_error) {
+ grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
+ if (!s->pending_byte_stream) {
+ grpc_slice_buffer_reset_and_unref_internal(
+ &s->unprocessed_incoming_frames_buffer);
+ }
+ }
+ grpc_chttp2_incoming_metadata_buffer_publish(&s->metadata_buffer[0],
+ s->recv_initial_metadata);
null_then_sched_closure(&s->recv_initial_metadata_ready);
- }
-}
-
+ }
+}
+
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) {
- *s->recv_message = nullptr;
- if (s->final_metadata_requested && s->seen_error) {
- grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
- if (!s->pending_byte_stream) {
- grpc_slice_buffer_reset_and_unref_internal(
- &s->unprocessed_incoming_frames_buffer);
- }
- }
- if (!s->pending_byte_stream) {
- while (s->unprocessed_incoming_frames_buffer.length > 0 ||
- s->frame_storage.length > 0) {
- if (s->unprocessed_incoming_frames_buffer.length == 0) {
- grpc_slice_buffer_swap(&s->unprocessed_incoming_frames_buffer,
- &s->frame_storage);
- s->unprocessed_incoming_frames_decompressed = false;
- }
- if (!s->unprocessed_incoming_frames_decompressed &&
- s->stream_decompression_method !=
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
- GPR_ASSERT(s->decompressed_data_buffer.length == 0);
- 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->unprocessed_incoming_frames_buffer,
- &s->decompressed_data_buffer, nullptr,
- GRPC_HEADER_SIZE_IN_BYTES - s->decompressed_header_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);
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Stream decompression error.");
- } else {
- s->decompressed_header_bytes += s->decompressed_data_buffer.length;
- if (s->decompressed_header_bytes == GRPC_HEADER_SIZE_IN_BYTES) {
- s->decompressed_header_bytes = 0;
- }
- error = grpc_deframe_unprocessed_incoming_frames(
- &s->data_parser, s, &s->decompressed_data_buffer, nullptr,
- s->recv_message);
- if (end_of_context) {
- grpc_stream_compression_context_destroy(
- s->stream_decompression_ctx);
- s->stream_decompression_ctx = nullptr;
- }
- }
- } else {
- error = grpc_deframe_unprocessed_incoming_frames(
- &s->data_parser, s, &s->unprocessed_incoming_frames_buffer,
- nullptr, s->recv_message);
- }
- if (error != GRPC_ERROR_NONE) {
- s->seen_error = true;
- grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
- grpc_slice_buffer_reset_and_unref_internal(
- &s->unprocessed_incoming_frames_buffer);
- break;
- } else if (*s->recv_message != nullptr) {
- break;
- }
- }
- }
- // save the length of the buffer before handing control back to application
- // threads. Needed to support correct flow control bookkeeping
- s->unprocessed_incoming_frames_buffer_cached_length =
- s->unprocessed_incoming_frames_buffer.length;
- if (error == GRPC_ERROR_NONE && *s->recv_message != nullptr) {
+ grpc_chttp2_stream* s) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (s->recv_message_ready != nullptr) {
+ *s->recv_message = nullptr;
+ if (s->final_metadata_requested && s->seen_error) {
+ grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
+ if (!s->pending_byte_stream) {
+ grpc_slice_buffer_reset_and_unref_internal(
+ &s->unprocessed_incoming_frames_buffer);
+ }
+ }
+ if (!s->pending_byte_stream) {
+ while (s->unprocessed_incoming_frames_buffer.length > 0 ||
+ s->frame_storage.length > 0) {
+ if (s->unprocessed_incoming_frames_buffer.length == 0) {
+ grpc_slice_buffer_swap(&s->unprocessed_incoming_frames_buffer,
+ &s->frame_storage);
+ s->unprocessed_incoming_frames_decompressed = false;
+ }
+ if (!s->unprocessed_incoming_frames_decompressed &&
+ s->stream_decompression_method !=
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) {
+ GPR_ASSERT(s->decompressed_data_buffer.length == 0);
+ 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->unprocessed_incoming_frames_buffer,
+ &s->decompressed_data_buffer, nullptr,
+ GRPC_HEADER_SIZE_IN_BYTES - s->decompressed_header_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);
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Stream decompression error.");
+ } else {
+ s->decompressed_header_bytes += s->decompressed_data_buffer.length;
+ if (s->decompressed_header_bytes == GRPC_HEADER_SIZE_IN_BYTES) {
+ s->decompressed_header_bytes = 0;
+ }
+ error = grpc_deframe_unprocessed_incoming_frames(
+ &s->data_parser, s, &s->decompressed_data_buffer, nullptr,
+ s->recv_message);
+ if (end_of_context) {
+ grpc_stream_compression_context_destroy(
+ s->stream_decompression_ctx);
+ s->stream_decompression_ctx = nullptr;
+ }
+ }
+ } else {
+ error = grpc_deframe_unprocessed_incoming_frames(
+ &s->data_parser, s, &s->unprocessed_incoming_frames_buffer,
+ nullptr, s->recv_message);
+ }
+ if (error != GRPC_ERROR_NONE) {
+ s->seen_error = true;
+ grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
+ grpc_slice_buffer_reset_and_unref_internal(
+ &s->unprocessed_incoming_frames_buffer);
+ break;
+ } else if (*s->recv_message != nullptr) {
+ break;
+ }
+ }
+ }
+ // save the length of the buffer before handing control back to application
+ // threads. Needed to support correct flow control bookkeeping
+ 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);
- } else if (s->published_metadata[1] != GRPC_METADATA_NOT_PUBLISHED) {
- *s->recv_message = nullptr;
+ } else if (s->published_metadata[1] != GRPC_METADATA_NOT_PUBLISHED) {
+ *s->recv_message = nullptr;
null_then_sched_closure(&s->recv_message_ready);
- }
- GRPC_ERROR_UNREF(error);
- }
-}
-
-void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- grpc_chttp2_maybe_complete_recv_message(t, s);
- if (s->recv_trailing_metadata_finished != nullptr && s->read_closed &&
- s->write_closed) {
- if (s->seen_error || !t->is_client) {
- grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
- if (!s->pending_byte_stream) {
- grpc_slice_buffer_reset_and_unref_internal(
- &s->unprocessed_incoming_frames_buffer);
- }
- }
- bool pending_data = s->pending_byte_stream ||
- s->unprocessed_incoming_frames_buffer.length > 0;
- if (s->read_closed && s->frame_storage.length > 0 && !pending_data &&
- !s->seen_error && s->recv_trailing_metadata_finished != nullptr) {
+ }
+ GRPC_ERROR_UNREF(error);
+ }
+}
+
+void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ grpc_chttp2_maybe_complete_recv_message(t, s);
+ if (s->recv_trailing_metadata_finished != nullptr && s->read_closed &&
+ s->write_closed) {
+ if (s->seen_error || !t->is_client) {
+ grpc_slice_buffer_reset_and_unref_internal(&s->frame_storage);
+ if (!s->pending_byte_stream) {
+ grpc_slice_buffer_reset_and_unref_internal(
+ &s->unprocessed_incoming_frames_buffer);
+ }
+ }
+ bool pending_data = s->pending_byte_stream ||
+ s->unprocessed_incoming_frames_buffer.length > 0;
+ if (s->read_closed && s->frame_storage.length > 0 && !pending_data &&
+ !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 ==
@@ -1950,17 +1950,17 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
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;
- }
+ &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,
@@ -1980,411 +1980,411 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
s->stream_decompression_ctx = nullptr;
}
}
- }
- }
- if (s->read_closed && s->frame_storage.length == 0 && !pending_data &&
- s->recv_trailing_metadata_finished != nullptr) {
+ }
+ }
+ if (s->read_closed && s->frame_storage.length == 0 && !pending_data &&
+ s->recv_trailing_metadata_finished != nullptr) {
grpc_transport_move_stats(&s->stats, s->collecting_stats);
s->collecting_stats = nullptr;
- grpc_chttp2_incoming_metadata_buffer_publish(&s->metadata_buffer[1],
- s->recv_trailing_metadata);
+ grpc_chttp2_incoming_metadata_buffer_publish(&s->metadata_buffer[1],
+ s->recv_trailing_metadata);
null_then_sched_closure(&s->recv_trailing_metadata_finished);
- }
- }
-}
-
-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));
+ }
+ }
+}
+
+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);
- if (t->incoming_stream == s) {
- t->incoming_stream = nullptr;
- grpc_chttp2_parsing_become_skip_parser(t);
- }
- if (s->pending_byte_stream) {
- if (s->on_next != nullptr) {
- grpc_core::Chttp2IncomingByteStream* bs = s->data_parser.parsing_frame;
- if (error == GRPC_ERROR_NONE) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message");
- }
- bs->PublishError(error);
- bs->Unref();
- s->data_parser.parsing_frame = nullptr;
- } else {
- GRPC_ERROR_UNREF(s->byte_stream_error);
- s->byte_stream_error = GRPC_ERROR_REF(error);
- }
- }
-
- if (grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
- post_benign_reclaimer(t);
- if (t->sent_goaway_state == GRPC_CHTTP2_GOAWAY_SENT) {
- close_transport_locked(
- t, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Last stream closed after sending GOAWAY", &error, 1));
- }
- }
- if (grpc_chttp2_list_remove_writable_stream(t, s)) {
- GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:remove_stream");
- }
+ if (t->incoming_stream == s) {
+ t->incoming_stream = nullptr;
+ grpc_chttp2_parsing_become_skip_parser(t);
+ }
+ if (s->pending_byte_stream) {
+ if (s->on_next != nullptr) {
+ grpc_core::Chttp2IncomingByteStream* bs = s->data_parser.parsing_frame;
+ if (error == GRPC_ERROR_NONE) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message");
+ }
+ bs->PublishError(error);
+ bs->Unref();
+ s->data_parser.parsing_frame = nullptr;
+ } else {
+ GRPC_ERROR_UNREF(s->byte_stream_error);
+ s->byte_stream_error = GRPC_ERROR_REF(error);
+ }
+ }
+
+ if (grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
+ post_benign_reclaimer(t);
+ if (t->sent_goaway_state == GRPC_CHTTP2_GOAWAY_SENT) {
+ close_transport_locked(
+ t, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Last stream closed after sending GOAWAY", &error, 1));
+ }
+ }
+ if (grpc_chttp2_list_remove_writable_stream(t, s)) {
+ GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:remove_stream");
+ }
grpc_chttp2_list_remove_stalled_by_stream(t, s);
grpc_chttp2_list_remove_stalled_by_transport(t, s);
-
- GRPC_ERROR_UNREF(error);
-
- maybe_start_some_streams(t);
-}
-
-void grpc_chttp2_cancel_stream(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_error* due_to_error) {
- if (!t->is_client && !s->sent_trailing_metadata &&
- grpc_error_has_clear_grpc_status(due_to_error)) {
- close_from_api(t, s, due_to_error);
- return;
- }
-
- if (!s->read_closed || !s->write_closed) {
- if (s->id != 0) {
- grpc_http2_error_code http_error;
- grpc_error_get_status(due_to_error, s->deadline, nullptr, nullptr,
- &http_error, nullptr);
+
+ GRPC_ERROR_UNREF(error);
+
+ maybe_start_some_streams(t);
+}
+
+void grpc_chttp2_cancel_stream(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_error* due_to_error) {
+ if (!t->is_client && !s->sent_trailing_metadata &&
+ grpc_error_has_clear_grpc_status(due_to_error)) {
+ close_from_api(t, s, due_to_error);
+ return;
+ }
+
+ if (!s->read_closed || !s->write_closed) {
+ if (s->id != 0) {
+ 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_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM);
- }
- }
- if (due_to_error != GRPC_ERROR_NONE && !s->seen_error) {
- s->seen_error = true;
- }
- grpc_chttp2_mark_stream_closed(t, s, 1, 1, due_to_error);
-}
-
-void grpc_chttp2_fake_status(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_error* error) {
- grpc_status_code status;
- grpc_slice slice;
- grpc_error_get_status(error, s->deadline, &status, &slice, nullptr, nullptr);
- if (status != GRPC_STATUS_OK) {
- s->seen_error = true;
- }
+ grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM);
+ }
+ }
+ if (due_to_error != GRPC_ERROR_NONE && !s->seen_error) {
+ s->seen_error = true;
+ }
+ grpc_chttp2_mark_stream_closed(t, s, 1, 1, due_to_error);
+}
+
+void grpc_chttp2_fake_status(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_error* error) {
+ grpc_status_code status;
+ grpc_slice slice;
+ grpc_error_get_status(error, s->deadline, &status, &slice, nullptr, nullptr);
+ if (status != GRPC_STATUS_OK) {
+ s->seen_error = true;
+ }
// stream_global->recv_trailing_metadata_finished gives us a
// last chance replacement: we've received trailing metadata,
// but something more important has become available to signal
// to the upper layers - drop what we've got, and then publish
// what we want - which is safe because we haven't told anyone
// about the metadata yet
- if (s->published_metadata[1] == GRPC_METADATA_NOT_PUBLISHED ||
- s->recv_trailing_metadata_finished != nullptr) {
- char status_string[GPR_LTOA_MIN_BUFSIZE];
- gpr_ltoa(status, status_string);
- GRPC_LOG_IF_ERROR("add_status",
- grpc_chttp2_incoming_metadata_buffer_replace_or_add(
- &s->metadata_buffer[1],
- grpc_mdelem_from_slices(
- GRPC_MDSTR_GRPC_STATUS,
+ if (s->published_metadata[1] == GRPC_METADATA_NOT_PUBLISHED ||
+ s->recv_trailing_metadata_finished != nullptr) {
+ char status_string[GPR_LTOA_MIN_BUFSIZE];
+ gpr_ltoa(status, status_string);
+ GRPC_LOG_IF_ERROR("add_status",
+ grpc_chttp2_incoming_metadata_buffer_replace_or_add(
+ &s->metadata_buffer[1],
+ grpc_mdelem_from_slices(
+ GRPC_MDSTR_GRPC_STATUS,
grpc_core::UnmanagedMemorySlice(status_string))));
- if (!GRPC_SLICE_IS_EMPTY(slice)) {
- GRPC_LOG_IF_ERROR(
- "add_status_message",
- grpc_chttp2_incoming_metadata_buffer_replace_or_add(
- &s->metadata_buffer[1],
+ if (!GRPC_SLICE_IS_EMPTY(slice)) {
+ GRPC_LOG_IF_ERROR(
+ "add_status_message",
+ grpc_chttp2_incoming_metadata_buffer_replace_or_add(
+ &s->metadata_buffer[1],
grpc_mdelem_create(GRPC_MDSTR_GRPC_MESSAGE, slice, nullptr)));
- }
- s->published_metadata[1] = GRPC_METADATA_SYNTHESIZED_FROM_FAKE;
- grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
- }
-
- GRPC_ERROR_UNREF(error);
-}
-
-static void add_error(grpc_error* error, grpc_error** refs, size_t* nrefs) {
- if (error == GRPC_ERROR_NONE) return;
- for (size_t i = 0; i < *nrefs; i++) {
- if (error == refs[i]) {
- return;
- }
- }
- refs[*nrefs] = error;
- ++*nrefs;
-}
-
-static grpc_error* removal_error(grpc_error* extra_error, grpc_chttp2_stream* s,
- const char* master_error_msg) {
- grpc_error* refs[3];
- size_t nrefs = 0;
- add_error(s->read_closed_error, refs, &nrefs);
- add_error(s->write_closed_error, refs, &nrefs);
- add_error(extra_error, refs, &nrefs);
- grpc_error* error = GRPC_ERROR_NONE;
- if (nrefs > 0) {
- error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(master_error_msg,
- refs, nrefs);
- }
- GRPC_ERROR_UNREF(extra_error);
- return error;
-}
-
-static void flush_write_list(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_chttp2_write_cb** list, grpc_error* error) {
- while (*list) {
- grpc_chttp2_write_cb* cb = *list;
- *list = cb->next;
- grpc_chttp2_complete_closure_step(t, s, &cb->closure, GRPC_ERROR_REF(error),
- "on_write_finished_cb");
- cb->next = t->write_cb_pool;
- t->write_cb_pool = cb;
- }
- GRPC_ERROR_UNREF(error);
-}
-
-void grpc_chttp2_fail_pending_writes(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s, grpc_error* error) {
- error =
- removal_error(error, s, "Pending writes failed due to stream closure");
- s->send_initial_metadata = nullptr;
- grpc_chttp2_complete_closure_step(t, s, &s->send_initial_metadata_finished,
- GRPC_ERROR_REF(error),
- "send_initial_metadata_finished");
-
- s->send_trailing_metadata = nullptr;
+ }
+ s->published_metadata[1] = GRPC_METADATA_SYNTHESIZED_FROM_FAKE;
+ grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
+ }
+
+ GRPC_ERROR_UNREF(error);
+}
+
+static void add_error(grpc_error* error, grpc_error** refs, size_t* nrefs) {
+ if (error == GRPC_ERROR_NONE) return;
+ for (size_t i = 0; i < *nrefs; i++) {
+ if (error == refs[i]) {
+ return;
+ }
+ }
+ refs[*nrefs] = error;
+ ++*nrefs;
+}
+
+static grpc_error* removal_error(grpc_error* extra_error, grpc_chttp2_stream* s,
+ const char* master_error_msg) {
+ grpc_error* refs[3];
+ size_t nrefs = 0;
+ add_error(s->read_closed_error, refs, &nrefs);
+ add_error(s->write_closed_error, refs, &nrefs);
+ add_error(extra_error, refs, &nrefs);
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (nrefs > 0) {
+ error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(master_error_msg,
+ refs, nrefs);
+ }
+ GRPC_ERROR_UNREF(extra_error);
+ return error;
+}
+
+static void flush_write_list(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_chttp2_write_cb** list, grpc_error* error) {
+ while (*list) {
+ grpc_chttp2_write_cb* cb = *list;
+ *list = cb->next;
+ grpc_chttp2_complete_closure_step(t, s, &cb->closure, GRPC_ERROR_REF(error),
+ "on_write_finished_cb");
+ cb->next = t->write_cb_pool;
+ t->write_cb_pool = cb;
+ }
+ GRPC_ERROR_UNREF(error);
+}
+
+void grpc_chttp2_fail_pending_writes(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s, grpc_error* error) {
+ error =
+ removal_error(error, s, "Pending writes failed due to stream closure");
+ s->send_initial_metadata = nullptr;
+ grpc_chttp2_complete_closure_step(t, s, &s->send_initial_metadata_finished,
+ GRPC_ERROR_REF(error),
+ "send_initial_metadata_finished");
+
+ s->send_trailing_metadata = nullptr;
s->sent_trailing_metadata_op = nullptr;
- grpc_chttp2_complete_closure_step(t, s, &s->send_trailing_metadata_finished,
- GRPC_ERROR_REF(error),
- "send_trailing_metadata_finished");
-
- s->fetching_send_message.reset();
- grpc_chttp2_complete_closure_step(t, s, &s->fetching_send_message_finished,
- GRPC_ERROR_REF(error),
- "fetching_send_message_finished");
- flush_write_list(t, s, &s->on_write_finished_cbs, GRPC_ERROR_REF(error));
- flush_write_list(t, s, &s->on_flow_controlled_cbs, error);
-}
-
-void grpc_chttp2_mark_stream_closed(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s, int close_reads,
- int close_writes, grpc_error* error) {
- if (s->read_closed && s->write_closed) {
+ grpc_chttp2_complete_closure_step(t, s, &s->send_trailing_metadata_finished,
+ GRPC_ERROR_REF(error),
+ "send_trailing_metadata_finished");
+
+ s->fetching_send_message.reset();
+ grpc_chttp2_complete_closure_step(t, s, &s->fetching_send_message_finished,
+ GRPC_ERROR_REF(error),
+ "fetching_send_message_finished");
+ flush_write_list(t, s, &s->on_write_finished_cbs, GRPC_ERROR_REF(error));
+ flush_write_list(t, s, &s->on_flow_controlled_cbs, error);
+}
+
+void grpc_chttp2_mark_stream_closed(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s, int close_reads,
+ int close_writes, grpc_error* error) {
+ if (s->read_closed && s->write_closed) {
// already closed, but we should still fake the status if needed.
grpc_error* overall_error = removal_error(error, s, "Stream removed");
if (overall_error != GRPC_ERROR_NONE) {
grpc_chttp2_fake_status(t, s, overall_error);
}
- grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
- return;
- }
- bool closed_read = false;
- bool became_closed = false;
- if (close_reads && !s->read_closed) {
- s->read_closed_error = GRPC_ERROR_REF(error);
- s->read_closed = true;
- closed_read = true;
- }
- if (close_writes && !s->write_closed) {
- s->write_closed_error = GRPC_ERROR_REF(error);
- s->write_closed = true;
- grpc_chttp2_fail_pending_writes(t, s, GRPC_ERROR_REF(error));
- }
- if (s->read_closed && s->write_closed) {
- became_closed = true;
- grpc_error* overall_error =
- removal_error(GRPC_ERROR_REF(error), s, "Stream removed");
- if (s->id != 0) {
- remove_stream(t, s->id, GRPC_ERROR_REF(overall_error));
- } else {
+ grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
+ return;
+ }
+ bool closed_read = false;
+ bool became_closed = false;
+ if (close_reads && !s->read_closed) {
+ s->read_closed_error = GRPC_ERROR_REF(error);
+ s->read_closed = true;
+ closed_read = true;
+ }
+ if (close_writes && !s->write_closed) {
+ s->write_closed_error = GRPC_ERROR_REF(error);
+ s->write_closed = true;
+ grpc_chttp2_fail_pending_writes(t, s, GRPC_ERROR_REF(error));
+ }
+ if (s->read_closed && s->write_closed) {
+ became_closed = true;
+ grpc_error* overall_error =
+ removal_error(GRPC_ERROR_REF(error), s, "Stream removed");
+ if (s->id != 0) {
+ remove_stream(t, s->id, GRPC_ERROR_REF(overall_error));
+ } else {
// Purge streams waiting on concurrency still waiting for id assignment
- grpc_chttp2_list_remove_waiting_for_concurrency(t, s);
- }
- if (overall_error != GRPC_ERROR_NONE) {
- grpc_chttp2_fake_status(t, s, overall_error);
- }
- }
- if (closed_read) {
- for (int i = 0; i < 2; i++) {
- if (s->published_metadata[i] == GRPC_METADATA_NOT_PUBLISHED) {
+ grpc_chttp2_list_remove_waiting_for_concurrency(t, s);
+ }
+ if (overall_error != GRPC_ERROR_NONE) {
+ grpc_chttp2_fake_status(t, s, overall_error);
+ }
+ }
+ 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;
- }
- }
- grpc_chttp2_maybe_complete_recv_initial_metadata(t, s);
- grpc_chttp2_maybe_complete_recv_message(t, s);
- }
- if (became_closed) {
- grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
- GRPC_CHTTP2_STREAM_UNREF(s, "chttp2");
- }
- GRPC_ERROR_UNREF(error);
-}
-
-static void close_from_api(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_error* error) {
- grpc_slice hdr;
- grpc_slice status_hdr;
- grpc_slice http_status_hdr;
- grpc_slice content_type_hdr;
- grpc_slice message_pfx;
- uint8_t* p;
- uint32_t len = 0;
- grpc_status_code grpc_status;
- grpc_slice slice;
- grpc_error_get_status(error, s->deadline, &grpc_status, &slice, nullptr,
- nullptr);
-
- GPR_ASSERT(grpc_status >= 0 && (int)grpc_status < 100);
-
+ }
+ }
+ grpc_chttp2_maybe_complete_recv_initial_metadata(t, s);
+ grpc_chttp2_maybe_complete_recv_message(t, s);
+ }
+ if (became_closed) {
+ grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
+ GRPC_CHTTP2_STREAM_UNREF(s, "chttp2");
+ }
+ GRPC_ERROR_UNREF(error);
+}
+
+static void close_from_api(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_error* error) {
+ grpc_slice hdr;
+ grpc_slice status_hdr;
+ grpc_slice http_status_hdr;
+ grpc_slice content_type_hdr;
+ grpc_slice message_pfx;
+ uint8_t* p;
+ uint32_t len = 0;
+ grpc_status_code grpc_status;
+ grpc_slice slice;
+ grpc_error_get_status(error, s->deadline, &grpc_status, &slice, nullptr,
+ nullptr);
+
+ GPR_ASSERT(grpc_status >= 0 && (int)grpc_status < 100);
+
// Hand roll a header block.
// This is unnecessarily ugly - at some point we should find a more
// elegant solution.
// It's complicated by the fact that our send machinery would be dead by
// the time we got around to sending this, so instead we ignore HPACK
// compression and just write the uncompressed bytes onto the wire.
- if (!s->sent_initial_metadata) {
- http_status_hdr = GRPC_SLICE_MALLOC(13);
- p = GRPC_SLICE_START_PTR(http_status_hdr);
- *p++ = 0x00;
- *p++ = 7;
- *p++ = ':';
- *p++ = 's';
- *p++ = 't';
- *p++ = 'a';
- *p++ = 't';
- *p++ = 'u';
- *p++ = 's';
- *p++ = 3;
- *p++ = '2';
- *p++ = '0';
- *p++ = '0';
- GPR_ASSERT(p == GRPC_SLICE_END_PTR(http_status_hdr));
- len += static_cast<uint32_t> GRPC_SLICE_LENGTH(http_status_hdr);
-
- content_type_hdr = GRPC_SLICE_MALLOC(31);
- p = GRPC_SLICE_START_PTR(content_type_hdr);
- *p++ = 0x00;
- *p++ = 12;
- *p++ = 'c';
- *p++ = 'o';
- *p++ = 'n';
- *p++ = 't';
- *p++ = 'e';
- *p++ = 'n';
- *p++ = 't';
- *p++ = '-';
- *p++ = 't';
- *p++ = 'y';
- *p++ = 'p';
- *p++ = 'e';
- *p++ = 16;
- *p++ = 'a';
- *p++ = 'p';
- *p++ = 'p';
- *p++ = 'l';
- *p++ = 'i';
- *p++ = 'c';
- *p++ = 'a';
- *p++ = 't';
- *p++ = 'i';
- *p++ = 'o';
- *p++ = 'n';
- *p++ = '/';
- *p++ = 'g';
- *p++ = 'r';
- *p++ = 'p';
- *p++ = 'c';
- GPR_ASSERT(p == GRPC_SLICE_END_PTR(content_type_hdr));
- len += static_cast<uint32_t> GRPC_SLICE_LENGTH(content_type_hdr);
- }
-
- status_hdr = GRPC_SLICE_MALLOC(15 + (grpc_status >= 10));
- p = GRPC_SLICE_START_PTR(status_hdr);
- *p++ = 0x00; /* literal header, not indexed */
- *p++ = 11; /* len(grpc-status) */
- *p++ = 'g';
- *p++ = 'r';
- *p++ = 'p';
- *p++ = 'c';
- *p++ = '-';
- *p++ = 's';
- *p++ = 't';
- *p++ = 'a';
- *p++ = 't';
- *p++ = 'u';
- *p++ = 's';
- if (grpc_status < 10) {
- *p++ = 1;
- *p++ = static_cast<uint8_t>('0' + grpc_status);
- } else {
- *p++ = 2;
- *p++ = static_cast<uint8_t>('0' + (grpc_status / 10));
- *p++ = static_cast<uint8_t>('0' + (grpc_status % 10));
- }
- GPR_ASSERT(p == GRPC_SLICE_END_PTR(status_hdr));
- len += static_cast<uint32_t> GRPC_SLICE_LENGTH(status_hdr);
-
- size_t msg_len = GRPC_SLICE_LENGTH(slice);
- GPR_ASSERT(msg_len <= UINT32_MAX);
- uint32_t msg_len_len = GRPC_CHTTP2_VARINT_LENGTH((uint32_t)msg_len, 1);
- message_pfx = GRPC_SLICE_MALLOC(14 + msg_len_len);
- p = GRPC_SLICE_START_PTR(message_pfx);
- *p++ = 0x00; /* literal header, not indexed */
- *p++ = 12; /* len(grpc-message) */
- *p++ = 'g';
- *p++ = 'r';
- *p++ = 'p';
- *p++ = 'c';
- *p++ = '-';
- *p++ = 'm';
- *p++ = 'e';
- *p++ = 's';
- *p++ = 's';
- *p++ = 'a';
- *p++ = 'g';
- *p++ = 'e';
- GRPC_CHTTP2_WRITE_VARINT((uint32_t)msg_len, 1, 0, p, (uint32_t)msg_len_len);
- p += msg_len_len;
- GPR_ASSERT(p == GRPC_SLICE_END_PTR(message_pfx));
- len += static_cast<uint32_t> GRPC_SLICE_LENGTH(message_pfx);
- len += static_cast<uint32_t>(msg_len);
-
- hdr = GRPC_SLICE_MALLOC(9);
- p = GRPC_SLICE_START_PTR(hdr);
- *p++ = static_cast<uint8_t>(len >> 16);
- *p++ = static_cast<uint8_t>(len >> 8);
- *p++ = static_cast<uint8_t>(len);
- *p++ = GRPC_CHTTP2_FRAME_HEADER;
- *p++ = GRPC_CHTTP2_DATA_FLAG_END_STREAM | GRPC_CHTTP2_DATA_FLAG_END_HEADERS;
- *p++ = static_cast<uint8_t>(s->id >> 24);
- *p++ = static_cast<uint8_t>(s->id >> 16);
- *p++ = static_cast<uint8_t>(s->id >> 8);
- *p++ = static_cast<uint8_t>(s->id);
- GPR_ASSERT(p == GRPC_SLICE_END_PTR(hdr));
-
- grpc_slice_buffer_add(&t->qbuf, hdr);
- if (!s->sent_initial_metadata) {
- grpc_slice_buffer_add(&t->qbuf, http_status_hdr);
- grpc_slice_buffer_add(&t->qbuf, content_type_hdr);
- }
- grpc_slice_buffer_add(&t->qbuf, status_hdr);
- grpc_slice_buffer_add(&t->qbuf, message_pfx);
- grpc_slice_buffer_add(&t->qbuf, grpc_slice_ref_internal(slice));
+ if (!s->sent_initial_metadata) {
+ http_status_hdr = GRPC_SLICE_MALLOC(13);
+ p = GRPC_SLICE_START_PTR(http_status_hdr);
+ *p++ = 0x00;
+ *p++ = 7;
+ *p++ = ':';
+ *p++ = 's';
+ *p++ = 't';
+ *p++ = 'a';
+ *p++ = 't';
+ *p++ = 'u';
+ *p++ = 's';
+ *p++ = 3;
+ *p++ = '2';
+ *p++ = '0';
+ *p++ = '0';
+ GPR_ASSERT(p == GRPC_SLICE_END_PTR(http_status_hdr));
+ len += static_cast<uint32_t> GRPC_SLICE_LENGTH(http_status_hdr);
+
+ content_type_hdr = GRPC_SLICE_MALLOC(31);
+ p = GRPC_SLICE_START_PTR(content_type_hdr);
+ *p++ = 0x00;
+ *p++ = 12;
+ *p++ = 'c';
+ *p++ = 'o';
+ *p++ = 'n';
+ *p++ = 't';
+ *p++ = 'e';
+ *p++ = 'n';
+ *p++ = 't';
+ *p++ = '-';
+ *p++ = 't';
+ *p++ = 'y';
+ *p++ = 'p';
+ *p++ = 'e';
+ *p++ = 16;
+ *p++ = 'a';
+ *p++ = 'p';
+ *p++ = 'p';
+ *p++ = 'l';
+ *p++ = 'i';
+ *p++ = 'c';
+ *p++ = 'a';
+ *p++ = 't';
+ *p++ = 'i';
+ *p++ = 'o';
+ *p++ = 'n';
+ *p++ = '/';
+ *p++ = 'g';
+ *p++ = 'r';
+ *p++ = 'p';
+ *p++ = 'c';
+ GPR_ASSERT(p == GRPC_SLICE_END_PTR(content_type_hdr));
+ len += static_cast<uint32_t> GRPC_SLICE_LENGTH(content_type_hdr);
+ }
+
+ status_hdr = GRPC_SLICE_MALLOC(15 + (grpc_status >= 10));
+ p = GRPC_SLICE_START_PTR(status_hdr);
+ *p++ = 0x00; /* literal header, not indexed */
+ *p++ = 11; /* len(grpc-status) */
+ *p++ = 'g';
+ *p++ = 'r';
+ *p++ = 'p';
+ *p++ = 'c';
+ *p++ = '-';
+ *p++ = 's';
+ *p++ = 't';
+ *p++ = 'a';
+ *p++ = 't';
+ *p++ = 'u';
+ *p++ = 's';
+ if (grpc_status < 10) {
+ *p++ = 1;
+ *p++ = static_cast<uint8_t>('0' + grpc_status);
+ } else {
+ *p++ = 2;
+ *p++ = static_cast<uint8_t>('0' + (grpc_status / 10));
+ *p++ = static_cast<uint8_t>('0' + (grpc_status % 10));
+ }
+ GPR_ASSERT(p == GRPC_SLICE_END_PTR(status_hdr));
+ len += static_cast<uint32_t> GRPC_SLICE_LENGTH(status_hdr);
+
+ size_t msg_len = GRPC_SLICE_LENGTH(slice);
+ GPR_ASSERT(msg_len <= UINT32_MAX);
+ uint32_t msg_len_len = GRPC_CHTTP2_VARINT_LENGTH((uint32_t)msg_len, 1);
+ message_pfx = GRPC_SLICE_MALLOC(14 + msg_len_len);
+ p = GRPC_SLICE_START_PTR(message_pfx);
+ *p++ = 0x00; /* literal header, not indexed */
+ *p++ = 12; /* len(grpc-message) */
+ *p++ = 'g';
+ *p++ = 'r';
+ *p++ = 'p';
+ *p++ = 'c';
+ *p++ = '-';
+ *p++ = 'm';
+ *p++ = 'e';
+ *p++ = 's';
+ *p++ = 's';
+ *p++ = 'a';
+ *p++ = 'g';
+ *p++ = 'e';
+ GRPC_CHTTP2_WRITE_VARINT((uint32_t)msg_len, 1, 0, p, (uint32_t)msg_len_len);
+ p += msg_len_len;
+ GPR_ASSERT(p == GRPC_SLICE_END_PTR(message_pfx));
+ len += static_cast<uint32_t> GRPC_SLICE_LENGTH(message_pfx);
+ len += static_cast<uint32_t>(msg_len);
+
+ hdr = GRPC_SLICE_MALLOC(9);
+ p = GRPC_SLICE_START_PTR(hdr);
+ *p++ = static_cast<uint8_t>(len >> 16);
+ *p++ = static_cast<uint8_t>(len >> 8);
+ *p++ = static_cast<uint8_t>(len);
+ *p++ = GRPC_CHTTP2_FRAME_HEADER;
+ *p++ = GRPC_CHTTP2_DATA_FLAG_END_STREAM | GRPC_CHTTP2_DATA_FLAG_END_HEADERS;
+ *p++ = static_cast<uint8_t>(s->id >> 24);
+ *p++ = static_cast<uint8_t>(s->id >> 16);
+ *p++ = static_cast<uint8_t>(s->id >> 8);
+ *p++ = static_cast<uint8_t>(s->id);
+ GPR_ASSERT(p == GRPC_SLICE_END_PTR(hdr));
+
+ grpc_slice_buffer_add(&t->qbuf, hdr);
+ if (!s->sent_initial_metadata) {
+ grpc_slice_buffer_add(&t->qbuf, http_status_hdr);
+ grpc_slice_buffer_add(&t->qbuf, content_type_hdr);
+ }
+ grpc_slice_buffer_add(&t->qbuf, status_hdr);
+ 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_mark_stream_closed(t, s, 1, 1, error);
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API);
-}
-
+
+ grpc_chttp2_mark_stream_closed(t, s, 1, 1, error);
+ grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API);
+}
+
struct cancel_stream_cb_args {
- grpc_error* error;
- grpc_chttp2_transport* t;
+ grpc_error* error;
+ grpc_chttp2_transport* t;
};
-
+
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) {
+ 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) &&
@@ -2392,81 +2392,81 @@ static void end_all_the_calls(grpc_chttp2_transport* t, grpc_error* 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);
-}
-
+ cancel_stream_cb_args args = {error, t};
+ grpc_chttp2_stream_map_for_each(&t->stream_map, cancel_stream_cb, &args);
+ GRPC_ERROR_UNREF(error);
+}
+
//
// INPUT PROCESSING - PARSING
//
-
-template <class F>
-static void WithUrgency(grpc_chttp2_transport* t,
- grpc_core::chttp2::FlowControlAction::Urgency urgency,
- grpc_chttp2_initiate_write_reason reason, F action) {
- switch (urgency) {
- case grpc_core::chttp2::FlowControlAction::Urgency::NO_ACTION_NEEDED:
- break;
- case grpc_core::chttp2::FlowControlAction::Urgency::UPDATE_IMMEDIATELY:
- grpc_chttp2_initiate_write(t, reason);
- // fallthrough
- case grpc_core::chttp2::FlowControlAction::Urgency::QUEUE_UPDATE:
- action();
- break;
- }
-}
-
-void grpc_chttp2_act_on_flowctl_action(
- const grpc_core::chttp2::FlowControlAction& action,
- grpc_chttp2_transport* t, grpc_chttp2_stream* s) {
- WithUrgency(t, action.send_stream_update(),
- GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL,
- [t, s]() { grpc_chttp2_mark_stream_writable(t, s); });
- WithUrgency(t, action.send_transport_update(),
- GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL, []() {});
- WithUrgency(t, action.send_initial_window_update(),
- GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS, [t, &action]() {
- queue_setting_update(t,
- GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE,
- action.initial_window_size());
- });
- WithUrgency(t, action.send_max_frame_size_update(),
- GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS, [t, &action]() {
- queue_setting_update(t, GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE,
- action.max_frame_size());
- });
-}
-
-static grpc_error* try_http_parsing(grpc_chttp2_transport* t) {
- grpc_http_parser parser;
- size_t i = 0;
- grpc_error* error = GRPC_ERROR_NONE;
- grpc_http_response response;
-
- grpc_http_parser_init(&parser, GRPC_HTTP_RESPONSE, &response);
-
- grpc_error* parse_error = GRPC_ERROR_NONE;
- for (; i < t->read_buffer.count && parse_error == GRPC_ERROR_NONE; i++) {
- parse_error =
- grpc_http_parser_parse(&parser, t->read_buffer.slices[i], nullptr);
- }
- if (parse_error == GRPC_ERROR_NONE &&
- (parse_error = grpc_http_parser_eof(&parser)) == GRPC_ERROR_NONE) {
- error = grpc_error_set_int(
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Trying to connect an http1.x server"),
- GRPC_ERROR_INT_HTTP_STATUS, response.status),
+
+template <class F>
+static void WithUrgency(grpc_chttp2_transport* t,
+ grpc_core::chttp2::FlowControlAction::Urgency urgency,
+ grpc_chttp2_initiate_write_reason reason, F action) {
+ switch (urgency) {
+ case grpc_core::chttp2::FlowControlAction::Urgency::NO_ACTION_NEEDED:
+ break;
+ case grpc_core::chttp2::FlowControlAction::Urgency::UPDATE_IMMEDIATELY:
+ grpc_chttp2_initiate_write(t, reason);
+ // fallthrough
+ case grpc_core::chttp2::FlowControlAction::Urgency::QUEUE_UPDATE:
+ action();
+ break;
+ }
+}
+
+void grpc_chttp2_act_on_flowctl_action(
+ const grpc_core::chttp2::FlowControlAction& action,
+ grpc_chttp2_transport* t, grpc_chttp2_stream* s) {
+ WithUrgency(t, action.send_stream_update(),
+ GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL,
+ [t, s]() { grpc_chttp2_mark_stream_writable(t, s); });
+ WithUrgency(t, action.send_transport_update(),
+ GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL, []() {});
+ WithUrgency(t, action.send_initial_window_update(),
+ GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS, [t, &action]() {
+ queue_setting_update(t,
+ GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE,
+ action.initial_window_size());
+ });
+ WithUrgency(t, action.send_max_frame_size_update(),
+ GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS, [t, &action]() {
+ queue_setting_update(t, GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE,
+ action.max_frame_size());
+ });
+}
+
+static grpc_error* try_http_parsing(grpc_chttp2_transport* t) {
+ grpc_http_parser parser;
+ size_t i = 0;
+ grpc_error* error = GRPC_ERROR_NONE;
+ grpc_http_response response;
+
+ grpc_http_parser_init(&parser, GRPC_HTTP_RESPONSE, &response);
+
+ grpc_error* parse_error = GRPC_ERROR_NONE;
+ for (; i < t->read_buffer.count && parse_error == GRPC_ERROR_NONE; i++) {
+ parse_error =
+ grpc_http_parser_parse(&parser, t->read_buffer.slices[i], nullptr);
+ }
+ if (parse_error == GRPC_ERROR_NONE &&
+ (parse_error = grpc_http_parser_eof(&parser)) == GRPC_ERROR_NONE) {
+ error = grpc_error_set_int(
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Trying to connect an http1.x server"),
+ GRPC_ERROR_INT_HTTP_STATUS, response.status),
GRPC_ERROR_INT_GRPC_STATUS,
grpc_http2_status_to_grpc_status(response.status));
- }
- GRPC_ERROR_UNREF(parse_error);
-
- grpc_http_parser_destroy(&parser);
- grpc_http_response_destroy(&response);
- return error;
-}
-
+ }
+ GRPC_ERROR_UNREF(parse_error);
+
+ grpc_http_parser_destroy(&parser);
+ grpc_http_response_destroy(&response);
+ return error;
+}
+
static void read_action(void* tp, grpc_error* error) {
grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
t->combiner->Run(
@@ -2474,79 +2474,79 @@ static void read_action(void* tp, grpc_error* error) {
GRPC_ERROR_REF(error));
}
-static void read_action_locked(void* tp, grpc_error* error) {
- GPR_TIMER_SCOPE("reading_action_locked", 0);
-
- grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
-
- GRPC_ERROR_REF(error);
-
- grpc_error* err = error;
- if (err != GRPC_ERROR_NONE) {
- err = grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Endpoint read failed", &err, 1),
- GRPC_ERROR_INT_OCCURRED_DURING_WRITE,
- t->write_state);
- }
- GPR_SWAP(grpc_error*, err, error);
- GRPC_ERROR_UNREF(err);
- if (t->closed_with_error == GRPC_ERROR_NONE) {
- GPR_TIMER_SCOPE("reading_action.parse", 0);
- size_t i = 0;
- grpc_error* errors[3] = {GRPC_ERROR_REF(error), GRPC_ERROR_NONE,
- GRPC_ERROR_NONE};
- for (; i < t->read_buffer.count && errors[1] == GRPC_ERROR_NONE; i++) {
- errors[1] = grpc_chttp2_perform_read(t, t->read_buffer.slices[i]);
- }
- if (errors[1] != GRPC_ERROR_NONE) {
- errors[2] = try_http_parsing(t);
- GRPC_ERROR_UNREF(error);
- error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Failed parsing HTTP/2", errors, GPR_ARRAY_SIZE(errors));
- }
- for (i = 0; i < GPR_ARRAY_SIZE(errors); i++) {
- GRPC_ERROR_UNREF(errors[i]);
- }
-
- GPR_TIMER_SCOPE("post_parse_locked", 0);
- if (t->initial_window_update != 0) {
- if (t->initial_window_update > 0) {
- grpc_chttp2_stream* s;
- while (grpc_chttp2_list_pop_stalled_by_stream(t, &s)) {
- grpc_chttp2_mark_stream_writable(t, s);
- grpc_chttp2_initiate_write(
- t, GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING);
- }
- }
- t->initial_window_update = 0;
- }
- }
-
- GPR_TIMER_SCOPE("post_reading_action_locked", 0);
- bool keep_reading = false;
- if (error == GRPC_ERROR_NONE && t->closed_with_error != GRPC_ERROR_NONE) {
- error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Transport closed", &t->closed_with_error, 1);
- }
- if (error != GRPC_ERROR_NONE) {
+static void read_action_locked(void* tp, grpc_error* error) {
+ GPR_TIMER_SCOPE("reading_action_locked", 0);
+
+ grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(tp);
+
+ GRPC_ERROR_REF(error);
+
+ grpc_error* err = error;
+ if (err != GRPC_ERROR_NONE) {
+ err = grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Endpoint read failed", &err, 1),
+ GRPC_ERROR_INT_OCCURRED_DURING_WRITE,
+ t->write_state);
+ }
+ GPR_SWAP(grpc_error*, err, error);
+ GRPC_ERROR_UNREF(err);
+ if (t->closed_with_error == GRPC_ERROR_NONE) {
+ GPR_TIMER_SCOPE("reading_action.parse", 0);
+ size_t i = 0;
+ grpc_error* errors[3] = {GRPC_ERROR_REF(error), GRPC_ERROR_NONE,
+ GRPC_ERROR_NONE};
+ for (; i < t->read_buffer.count && errors[1] == GRPC_ERROR_NONE; i++) {
+ errors[1] = grpc_chttp2_perform_read(t, t->read_buffer.slices[i]);
+ }
+ if (errors[1] != GRPC_ERROR_NONE) {
+ errors[2] = try_http_parsing(t);
+ GRPC_ERROR_UNREF(error);
+ error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Failed parsing HTTP/2", errors, GPR_ARRAY_SIZE(errors));
+ }
+ for (i = 0; i < GPR_ARRAY_SIZE(errors); i++) {
+ GRPC_ERROR_UNREF(errors[i]);
+ }
+
+ GPR_TIMER_SCOPE("post_parse_locked", 0);
+ if (t->initial_window_update != 0) {
+ if (t->initial_window_update > 0) {
+ grpc_chttp2_stream* s;
+ while (grpc_chttp2_list_pop_stalled_by_stream(t, &s)) {
+ grpc_chttp2_mark_stream_writable(t, s);
+ grpc_chttp2_initiate_write(
+ t, GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING);
+ }
+ }
+ t->initial_window_update = 0;
+ }
+ }
+
+ GPR_TIMER_SCOPE("post_reading_action_locked", 0);
+ bool keep_reading = false;
+ if (error == GRPC_ERROR_NONE && t->closed_with_error != GRPC_ERROR_NONE) {
+ error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Transport closed", &t->closed_with_error, 1);
+ }
+ if (error != GRPC_ERROR_NONE) {
// If a goaway frame was received, this might be the reason why the read
// failed. Add this info to the error
- if (t->goaway_error != GRPC_ERROR_NONE) {
- error = grpc_error_add_child(error, GRPC_ERROR_REF(t->goaway_error));
- }
-
- close_transport_locked(t, GRPC_ERROR_REF(error));
- t->endpoint_reading = 0;
- } else if (t->closed_with_error == GRPC_ERROR_NONE) {
- keep_reading = true;
+ if (t->goaway_error != GRPC_ERROR_NONE) {
+ error = grpc_error_add_child(error, GRPC_ERROR_REF(t->goaway_error));
+ }
+
+ close_transport_locked(t, GRPC_ERROR_REF(error));
+ t->endpoint_reading = 0;
+ } else if (t->closed_with_error == GRPC_ERROR_NONE) {
+ keep_reading = true;
// Since we have read a byte, reset the keepalive timer
if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING) {
grpc_timer_cancel(&t->keepalive_ping_timer);
}
- }
- grpc_slice_buffer_reset_and_unref_internal(&t->read_buffer);
-
- if (keep_reading) {
+ }
+ 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(
@@ -2557,13 +2557,13 @@ static void read_action_locked(void* tp, grpc_error* error) {
} else {
continue_read_action_locked(t);
}
- } else {
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "reading_action");
- }
-
- GRPC_ERROR_UNREF(error);
-}
-
+ } else {
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "reading_action");
+ }
+
+ 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,
@@ -2572,10 +2572,10 @@ static void continue_read_action_locked(grpc_chttp2_transport* t) {
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
+// 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();
+ t->flow_control->bdp_estimator()->SchedulePing();
send_ping_locked(
t,
GRPC_CLOSURE_INIT(&t->start_bdp_ping_locked, start_bdp_ping, t,
@@ -2585,8 +2585,8 @@ void schedule_bdp_ping_locked(grpc_chttp2_transport* t) {
// 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,
@@ -2594,23 +2594,23 @@ static void start_bdp_ping(void* tp, grpc_error* error) {
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);
+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)) {
gpr_log(GPR_INFO, "%s: Start BDP ping err=%s", t->peer_string.c_str(),
- grpc_error_string(error));
- }
+ grpc_error_string(error));
+ }
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();
+ 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,
@@ -2618,16 +2618,16 @@ static void finish_bdp_ping(void* tp, grpc_error* error) {
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);
+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)) {
gpr_log(GPR_INFO, "%s: Complete BDP ping err=%s", t->peer_string.c_str(),
- grpc_error_string(error));
- }
+ grpc_error_string(error));
+ }
if (error != GRPC_ERROR_NONE || t->closed_with_error != GRPC_ERROR_NONE) {
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "bdp_ping");
- return;
- }
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "bdp_ping");
+ return;
+ }
if (!t->bdp_ping_started) {
// start_bdp_ping_locked has not been run yet. Schedule
// finish_bdp_ping_locked to be run later.
@@ -2637,17 +2637,17 @@ static void finish_bdp_ping_locked(void* tp, grpc_error* 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_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_timer_init(&t->next_bdp_ping_timer, next_ping,
- &t->next_bdp_ping_timer_expired_locked);
-}
-
+ 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(
@@ -2656,14 +2656,14 @@ static void next_bdp_ping_timer_expired(void* tp, grpc_error* error) {
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);
- t->have_next_bdp_ping_timer = false;
- if (error != GRPC_ERROR_NONE) {
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "bdp_ping");
- return;
- }
+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);
+ t->have_next_bdp_ping_timer = false;
+ if (error != GRPC_ERROR_NONE) {
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "bdp_ping");
+ return;
+ }
if (t->flow_control->bdp_estimator()->accumulator() == 0) {
// Block the bdp ping till we receive more data.
t->bdp_ping_blocked = true;
@@ -2671,75 +2671,75 @@ static void next_bdp_ping_timer_expired_locked(void* tp, grpc_error* error) {
} else {
schedule_bdp_ping_locked(t);
}
-}
-
-void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args,
- bool is_client) {
- size_t i;
- if (args) {
- for (i = 0; i < args->num_args; i++) {
- if (0 == strcmp(args->args[i].key, GRPC_ARG_KEEPALIVE_TIME_MS)) {
- const int value = grpc_channel_arg_get_integer(
- &args->args[i], {is_client ? g_default_client_keepalive_time_ms
- : g_default_server_keepalive_time_ms,
- 1, INT_MAX});
- if (is_client) {
- g_default_client_keepalive_time_ms = value;
- } else {
- g_default_server_keepalive_time_ms = value;
- }
- } else if (0 ==
- strcmp(args->args[i].key, GRPC_ARG_KEEPALIVE_TIMEOUT_MS)) {
- const int value = grpc_channel_arg_get_integer(
- &args->args[i], {is_client ? g_default_client_keepalive_timeout_ms
- : g_default_server_keepalive_timeout_ms,
- 0, INT_MAX});
- if (is_client) {
- g_default_client_keepalive_timeout_ms = value;
- } else {
- g_default_server_keepalive_timeout_ms = value;
- }
- } else if (0 == strcmp(args->args[i].key,
- GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS)) {
- const bool value = static_cast<uint32_t>(grpc_channel_arg_get_integer(
- &args->args[i],
- {is_client ? g_default_client_keepalive_permit_without_calls
+}
+
+void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args,
+ bool is_client) {
+ size_t i;
+ if (args) {
+ for (i = 0; i < args->num_args; i++) {
+ if (0 == strcmp(args->args[i].key, GRPC_ARG_KEEPALIVE_TIME_MS)) {
+ const int value = grpc_channel_arg_get_integer(
+ &args->args[i], {is_client ? g_default_client_keepalive_time_ms
+ : g_default_server_keepalive_time_ms,
+ 1, INT_MAX});
+ if (is_client) {
+ g_default_client_keepalive_time_ms = value;
+ } else {
+ g_default_server_keepalive_time_ms = value;
+ }
+ } else if (0 ==
+ strcmp(args->args[i].key, GRPC_ARG_KEEPALIVE_TIMEOUT_MS)) {
+ const int value = grpc_channel_arg_get_integer(
+ &args->args[i], {is_client ? g_default_client_keepalive_timeout_ms
+ : g_default_server_keepalive_timeout_ms,
+ 0, INT_MAX});
+ if (is_client) {
+ g_default_client_keepalive_timeout_ms = value;
+ } else {
+ g_default_server_keepalive_timeout_ms = value;
+ }
+ } else if (0 == strcmp(args->args[i].key,
+ GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS)) {
+ 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,
- 0, 1}));
- if (is_client) {
- g_default_client_keepalive_permit_without_calls = value;
- } else {
- g_default_server_keepalive_permit_without_calls = value;
- }
- } else if (0 ==
- strcmp(args->args[i].key, GRPC_ARG_HTTP2_MAX_PING_STRIKES)) {
- g_default_max_ping_strikes = grpc_channel_arg_get_integer(
- &args->args[i], {g_default_max_ping_strikes, 0, INT_MAX});
- } else if (0 == strcmp(args->args[i].key,
- GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA)) {
- g_default_max_pings_without_data = grpc_channel_arg_get_integer(
- &args->args[i], {g_default_max_pings_without_data, 0, INT_MAX});
- } else if (0 ==
- strcmp(
- args->args[i].key,
- GRPC_ARG_HTTP2_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS)) {
- g_default_min_sent_ping_interval_without_data_ms =
- grpc_channel_arg_get_integer(
- &args->args[i],
- {g_default_min_sent_ping_interval_without_data_ms, 0, INT_MAX});
- } else if (0 ==
- strcmp(
- args->args[i].key,
- GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS)) {
- g_default_min_recv_ping_interval_without_data_ms =
- grpc_channel_arg_get_integer(
- &args->args[i],
- {g_default_min_recv_ping_interval_without_data_ms, 0, INT_MAX});
- }
- }
- }
-}
-
+ 0, 1}));
+ if (is_client) {
+ g_default_client_keepalive_permit_without_calls = value;
+ } else {
+ g_default_server_keepalive_permit_without_calls = value;
+ }
+ } else if (0 ==
+ strcmp(args->args[i].key, GRPC_ARG_HTTP2_MAX_PING_STRIKES)) {
+ g_default_max_ping_strikes = grpc_channel_arg_get_integer(
+ &args->args[i], {g_default_max_ping_strikes, 0, INT_MAX});
+ } else if (0 == strcmp(args->args[i].key,
+ GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA)) {
+ g_default_max_pings_without_data = grpc_channel_arg_get_integer(
+ &args->args[i], {g_default_max_pings_without_data, 0, INT_MAX});
+ } else if (0 ==
+ strcmp(
+ args->args[i].key,
+ GRPC_ARG_HTTP2_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS)) {
+ g_default_min_sent_ping_interval_without_data_ms =
+ grpc_channel_arg_get_integer(
+ &args->args[i],
+ {g_default_min_sent_ping_interval_without_data_ms, 0, INT_MAX});
+ } else if (0 ==
+ strcmp(
+ args->args[i].key,
+ GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS)) {
+ g_default_min_recv_ping_interval_without_data_ms =
+ grpc_channel_arg_get_integer(
+ &args->args[i],
+ {g_default_min_recv_ping_interval_without_data_ms, 0, INT_MAX});
+ }
+ }
+ }
+}
+
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,
@@ -2747,39 +2747,39 @@ static void init_keepalive_ping(void* arg, grpc_error* error) {
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);
- if (t->destroying || t->closed_with_error != GRPC_ERROR_NONE) {
- t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING;
- } else if (error == GRPC_ERROR_NONE) {
- if (t->keepalive_permit_without_calls ||
- grpc_chttp2_stream_map_size(&t->stream_map) > 0) {
- t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_PINGING;
- GRPC_CHTTP2_REF_TRANSPORT(t, "keepalive ping end");
+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);
+ if (t->destroying || t->closed_with_error != GRPC_ERROR_NONE) {
+ t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING;
+ } else if (error == GRPC_ERROR_NONE) {
+ if (t->keepalive_permit_without_calls ||
+ grpc_chttp2_stream_map_size(&t->stream_map) > 0) {
+ t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_PINGING;
+ GRPC_CHTTP2_REF_TRANSPORT(t, "keepalive ping end");
grpc_timer_init_unset(&t->keepalive_watchdog_timer);
- send_keepalive_ping_locked(t);
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING);
- } else {
- GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping");
+ send_keepalive_ping_locked(t);
+ 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_timer_init(&t->keepalive_ping_timer,
- grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
- &t->init_keepalive_ping_locked);
- }
- } else if (error == GRPC_ERROR_CANCELLED) {
+ grpc_timer_init(&t->keepalive_ping_timer,
+ grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
+ &t->init_keepalive_ping_locked);
+ }
+ } else if (error == GRPC_ERROR_CANCELLED) {
// The keepalive ping timer may be cancelled by bdp
- GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping");
+ 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_timer_init(&t->keepalive_ping_timer,
- grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
- &t->init_keepalive_ping_locked);
- }
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "init keepalive ping");
-}
-
+ grpc_timer_init(&t->keepalive_ping_timer,
+ grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
+ &t->init_keepalive_ping_locked);
+ }
+ 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,
@@ -2787,8 +2787,8 @@ static void start_keepalive_ping(void* arg, grpc_error* error) {
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);
+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) {
return;
}
@@ -2799,15 +2799,15 @@ static void start_keepalive_ping_locked(void* arg, grpc_error* error) {
GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) {
gpr_log(GPR_INFO, "%s: Start keepalive ping", t->peer_string.c_str());
}
- GRPC_CHTTP2_REF_TRANSPORT(t, "keepalive watchdog");
+ 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_timer_init(&t->keepalive_watchdog_timer,
- grpc_core::ExecCtx::Get()->Now() + t->keepalive_timeout,
- &t->keepalive_watchdog_fired_locked);
+ 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,
@@ -2815,10 +2815,10 @@ static void finish_keepalive_ping(void* arg, grpc_error* error) {
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) {
- if (error == GRPC_ERROR_NONE) {
+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) {
+ if (error == GRPC_ERROR_NONE) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) ||
GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) {
gpr_log(GPR_INFO, "%s: Finish keepalive ping", t->peer_string.c_str());
@@ -2833,19 +2833,19 @@ static void finish_keepalive_ping_locked(void* arg, grpc_error* 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");
+ 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_timer_init(&t->keepalive_ping_timer,
- grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
- &t->init_keepalive_ping_locked);
- }
- }
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "keepalive ping end");
-}
-
+ grpc_timer_init(&t->keepalive_ping_timer,
+ grpc_core::ExecCtx::Get()->Now() + t->keepalive_time,
+ &t->init_keepalive_ping_locked);
+ }
+ }
+ 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(
@@ -2854,175 +2854,175 @@ static void keepalive_watchdog_fired(void* arg, grpc_error* error) {
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) {
- if (error == GRPC_ERROR_NONE) {
+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) {
+ if (error == GRPC_ERROR_NONE) {
gpr_log(GPR_INFO, "%s: Keepalive watchdog fired. Closing transport.",
t->peer_string.c_str());
- t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING;
- close_transport_locked(
+ t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING;
+ close_transport_locked(
t, grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"keepalive watchdog timeout"),
GRPC_ERROR_INT_GRPC_STATUS,
GRPC_STATUS_UNAVAILABLE));
- }
- } else {
+ }
+ } else {
// The watchdog timer should have been cancelled by
// finish_keepalive_ping_locked.
if (GPR_UNLIKELY(error != GRPC_ERROR_CANCELLED)) {
- gpr_log(GPR_ERROR, "keepalive_ping_end state error: %d (expect: %d)",
- t->keepalive_state, GRPC_CHTTP2_KEEPALIVE_STATE_PINGING);
- }
- }
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "keepalive watchdog");
-}
-
+ gpr_log(GPR_ERROR, "keepalive_ping_end state error: %d (expect: %d)",
+ t->keepalive_state, GRPC_CHTTP2_KEEPALIVE_STATE_PINGING);
+ }
+ }
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "keepalive watchdog");
+}
+
//
// CALLBACK LOOP
//
-
-static void connectivity_state_set(grpc_chttp2_transport* t,
- grpc_connectivity_state state,
+
+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));
t->state_tracker.SetState(state, status, reason);
-}
-
+}
+
//
// POLLSET STUFF
//
-
+
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);
-}
-
+ 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*/,
- 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);
-}
-
+ 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);
+}
+
//
// BYTE STREAM
//
-
-static void reset_byte_stream(void* arg, grpc_error* error) {
- grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(arg);
- s->pending_byte_stream = false;
- if (error == GRPC_ERROR_NONE) {
- grpc_chttp2_maybe_complete_recv_message(s->t, s);
- grpc_chttp2_maybe_complete_recv_trailing_metadata(s->t, s);
- } else {
- GPR_ASSERT(error != GRPC_ERROR_NONE);
+
+static void reset_byte_stream(void* arg, grpc_error* error) {
+ grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(arg);
+ s->pending_byte_stream = false;
+ if (error == GRPC_ERROR_NONE) {
+ grpc_chttp2_maybe_complete_recv_message(s->t, s);
+ 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));
- s->on_next = nullptr;
- GRPC_ERROR_UNREF(s->byte_stream_error);
- s->byte_stream_error = GRPC_ERROR_NONE;
- grpc_chttp2_cancel_stream(s->t, s, GRPC_ERROR_REF(error));
- s->byte_stream_error = GRPC_ERROR_REF(error);
- }
-}
-
-namespace grpc_core {
-
-Chttp2IncomingByteStream::Chttp2IncomingByteStream(
- grpc_chttp2_transport* transport, grpc_chttp2_stream* stream,
- uint32_t frame_size, uint32_t flags)
- : ByteStream(frame_size, flags),
- transport_(transport),
- stream_(stream),
+ s->on_next = nullptr;
+ GRPC_ERROR_UNREF(s->byte_stream_error);
+ s->byte_stream_error = GRPC_ERROR_NONE;
+ grpc_chttp2_cancel_stream(s->t, s, GRPC_ERROR_REF(error));
+ s->byte_stream_error = GRPC_ERROR_REF(error);
+ }
+}
+
+namespace grpc_core {
+
+Chttp2IncomingByteStream::Chttp2IncomingByteStream(
+ grpc_chttp2_transport* transport, grpc_chttp2_stream* stream,
+ uint32_t frame_size, uint32_t flags)
+ : ByteStream(frame_size, flags),
+ transport_(transport),
+ stream_(stream),
refs_(2),
- remaining_bytes_(frame_size) {
- GRPC_ERROR_UNREF(stream->byte_stream_error);
- stream->byte_stream_error = GRPC_ERROR_NONE;
-}
-
-void Chttp2IncomingByteStream::OrphanLocked(void* arg,
+ remaining_bytes_(frame_size) {
+ GRPC_ERROR_UNREF(stream->byte_stream_error);
+ stream->byte_stream_error = GRPC_ERROR_NONE;
+}
+
+void Chttp2IncomingByteStream::OrphanLocked(void* arg,
grpc_error* /*error_ignored*/) {
- Chttp2IncomingByteStream* bs = static_cast<Chttp2IncomingByteStream*>(arg);
- grpc_chttp2_stream* s = bs->stream_;
- grpc_chttp2_transport* t = s->t;
- bs->Unref();
- s->pending_byte_stream = false;
- grpc_chttp2_maybe_complete_recv_message(t, s);
- grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
-}
-
-void Chttp2IncomingByteStream::Orphan() {
- GPR_TIMER_SCOPE("incoming_byte_stream_destroy", 0);
+ Chttp2IncomingByteStream* bs = static_cast<Chttp2IncomingByteStream*>(arg);
+ grpc_chttp2_stream* s = bs->stream_;
+ grpc_chttp2_transport* t = s->t;
+ bs->Unref();
+ s->pending_byte_stream = false;
+ grpc_chttp2_maybe_complete_recv_message(t, s);
+ grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s);
+}
+
+void Chttp2IncomingByteStream::Orphan() {
+ GPR_TIMER_SCOPE("incoming_byte_stream_destroy", 0);
transport_->combiner->Run(
- GRPC_CLOSURE_INIT(&destroy_action_,
+ GRPC_CLOSURE_INIT(&destroy_action_,
&Chttp2IncomingByteStream::OrphanLocked, this, nullptr),
- GRPC_ERROR_NONE);
-}
-
-void Chttp2IncomingByteStream::NextLocked(void* arg,
+ GRPC_ERROR_NONE);
+}
+
+void Chttp2IncomingByteStream::NextLocked(void* arg,
grpc_error* /*error_ignored*/) {
- Chttp2IncomingByteStream* bs = static_cast<Chttp2IncomingByteStream*>(arg);
- grpc_chttp2_transport* t = bs->transport_;
- grpc_chttp2_stream* s = bs->stream_;
- size_t cur_length = s->frame_storage.length;
- if (!s->read_closed) {
- s->flow_control->IncomingByteStreamUpdate(bs->next_action_.max_size_hint,
- cur_length);
- grpc_chttp2_act_on_flowctl_action(s->flow_control->MakeAction(), t, s);
- }
- GPR_ASSERT(s->unprocessed_incoming_frames_buffer.length == 0);
- if (s->frame_storage.length > 0) {
- grpc_slice_buffer_swap(&s->frame_storage,
- &s->unprocessed_incoming_frames_buffer);
- s->unprocessed_incoming_frames_decompressed = false;
+ Chttp2IncomingByteStream* bs = static_cast<Chttp2IncomingByteStream*>(arg);
+ grpc_chttp2_transport* t = bs->transport_;
+ grpc_chttp2_stream* s = bs->stream_;
+ size_t cur_length = s->frame_storage.length;
+ if (!s->read_closed) {
+ s->flow_control->IncomingByteStreamUpdate(bs->next_action_.max_size_hint,
+ cur_length);
+ grpc_chttp2_act_on_flowctl_action(s->flow_control->MakeAction(), t, s);
+ }
+ GPR_ASSERT(s->unprocessed_incoming_frames_buffer.length == 0);
+ if (s->frame_storage.length > 0) {
+ 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);
- } else if (s->byte_stream_error != 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));
- if (s->data_parser.parsing_frame != nullptr) {
- s->data_parser.parsing_frame->Unref();
- s->data_parser.parsing_frame = nullptr;
- }
- } else if (s->read_closed) {
- if (bs->remaining_bytes_ != 0) {
+ if (s->data_parser.parsing_frame != nullptr) {
+ s->data_parser.parsing_frame->Unref();
+ s->data_parser.parsing_frame = nullptr;
+ }
+ } else if (s->read_closed) {
+ 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));
- if (s->data_parser.parsing_frame != nullptr) {
- s->data_parser.parsing_frame->Unref();
- s->data_parser.parsing_frame = nullptr;
- }
- } else {
+ if (s->data_parser.parsing_frame != nullptr) {
+ s->data_parser.parsing_frame->Unref();
+ s->data_parser.parsing_frame = nullptr;
+ }
+ } else {
// Should never reach here.
- GPR_ASSERT(false);
- }
- } else {
- s->on_next = bs->next_action_.on_complete;
- }
- bs->Unref();
-}
-
-bool Chttp2IncomingByteStream::Next(size_t max_size_hint,
- grpc_closure* on_complete) {
- GPR_TIMER_SCOPE("incoming_byte_stream_next", 0);
- if (stream_->unprocessed_incoming_frames_buffer.length > 0) {
- return true;
- } else {
- Ref();
- next_action_.max_size_hint = max_size_hint;
- next_action_.on_complete = on_complete;
+ GPR_ASSERT(false);
+ }
+ } else {
+ s->on_next = bs->next_action_.on_complete;
+ }
+ bs->Unref();
+}
+
+bool Chttp2IncomingByteStream::Next(size_t max_size_hint,
+ grpc_closure* on_complete) {
+ GPR_TIMER_SCOPE("incoming_byte_stream_next", 0);
+ if (stream_->unprocessed_incoming_frames_buffer.length > 0) {
+ return true;
+ } else {
+ Ref();
+ next_action_.max_size_hint = max_size_hint;
+ next_action_.on_complete = on_complete;
transport_->combiner->Run(
- GRPC_CLOSURE_INIT(&next_action_.closure,
+ GRPC_CLOSURE_INIT(&next_action_.closure,
&Chttp2IncomingByteStream::NextLocked, this, nullptr),
- GRPC_ERROR_NONE);
- return false;
- }
-}
-
+ GRPC_ERROR_NONE);
+ return false;
+ }
+}
+
void Chttp2IncomingByteStream::MaybeCreateStreamDecompressionCtx() {
GPR_DEBUG_ASSERT(stream_->stream_decompression_method !=
GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS);
@@ -3032,126 +3032,126 @@ void Chttp2IncomingByteStream::MaybeCreateStreamDecompressionCtx() {
}
}
-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) {
+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) {
- bool end_of_context;
+ bool end_of_context;
MaybeCreateStreamDecompressionCtx();
- if (!grpc_stream_decompress(stream_->stream_decompression_ctx,
- &stream_->unprocessed_incoming_frames_buffer,
- &stream_->decompressed_data_buffer, nullptr,
- MAX_SIZE_T, &end_of_context)) {
- error =
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Stream decompression error.");
- return error;
- }
- GPR_ASSERT(stream_->unprocessed_incoming_frames_buffer.length == 0);
- grpc_slice_buffer_swap(&stream_->unprocessed_incoming_frames_buffer,
- &stream_->decompressed_data_buffer);
- stream_->unprocessed_incoming_frames_decompressed = true;
- if (end_of_context) {
- grpc_stream_compression_context_destroy(
- stream_->stream_decompression_ctx);
- stream_->stream_decompression_ctx = nullptr;
- }
- if (stream_->unprocessed_incoming_frames_buffer.length == 0) {
- *slice = grpc_empty_slice();
- }
- }
- error = grpc_deframe_unprocessed_incoming_frames(
- &stream_->data_parser, stream_,
- &stream_->unprocessed_incoming_frames_buffer, slice, nullptr);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
- } else {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message");
+ if (!grpc_stream_decompress(stream_->stream_decompression_ctx,
+ &stream_->unprocessed_incoming_frames_buffer,
+ &stream_->decompressed_data_buffer, nullptr,
+ MAX_SIZE_T, &end_of_context)) {
+ error =
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Stream decompression error.");
+ return error;
+ }
+ GPR_ASSERT(stream_->unprocessed_incoming_frames_buffer.length == 0);
+ grpc_slice_buffer_swap(&stream_->unprocessed_incoming_frames_buffer,
+ &stream_->decompressed_data_buffer);
+ stream_->unprocessed_incoming_frames_decompressed = true;
+ if (end_of_context) {
+ grpc_stream_compression_context_destroy(
+ stream_->stream_decompression_ctx);
+ stream_->stream_decompression_ctx = nullptr;
+ }
+ if (stream_->unprocessed_incoming_frames_buffer.length == 0) {
+ *slice = grpc_empty_slice();
+ }
+ }
+ error = grpc_deframe_unprocessed_incoming_frames(
+ &stream_->data_parser, stream_,
+ &stream_->unprocessed_incoming_frames_buffer, slice, nullptr);
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+ } else {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message");
stream_->t->combiner->Run(&stream_->reset_byte_stream,
GRPC_ERROR_REF(error));
- return error;
- }
- return GRPC_ERROR_NONE;
-}
-
-void Chttp2IncomingByteStream::PublishError(grpc_error* error) {
- GPR_ASSERT(error != GRPC_ERROR_NONE);
+ return error;
+ }
+ return GRPC_ERROR_NONE;
+}
+
+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));
- 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));
-}
-
+ 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_slice* slice_out) {
- if (remaining_bytes_ < GRPC_SLICE_LENGTH(slice)) {
- grpc_error* error =
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Too many bytes in stream");
+ 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));
- grpc_slice_unref_internal(slice);
- return error;
- } else {
- remaining_bytes_ -= static_cast<uint32_t> GRPC_SLICE_LENGTH(slice);
- if (slice_out != nullptr) {
- *slice_out = slice;
- }
- return GRPC_ERROR_NONE;
- }
-}
-
-grpc_error* Chttp2IncomingByteStream::Finished(grpc_error* error,
- bool reset_on_error) {
- if (error == GRPC_ERROR_NONE) {
- if (remaining_bytes_ != 0) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message");
- }
- }
- if (error != GRPC_ERROR_NONE && reset_on_error) {
+ grpc_slice_unref_internal(slice);
+ return error;
+ } else {
+ remaining_bytes_ -= static_cast<uint32_t> GRPC_SLICE_LENGTH(slice);
+ if (slice_out != nullptr) {
+ *slice_out = slice;
+ }
+ return GRPC_ERROR_NONE;
+ }
+}
+
+grpc_error* Chttp2IncomingByteStream::Finished(grpc_error* error,
+ bool reset_on_error) {
+ if (error == GRPC_ERROR_NONE) {
+ if (remaining_bytes_ != 0) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message");
+ }
+ }
+ if (error != GRPC_ERROR_NONE && reset_on_error) {
transport_->combiner->Run(&stream_->reset_byte_stream,
GRPC_ERROR_REF(error));
- }
- Unref();
- return error;
-}
-
-void Chttp2IncomingByteStream::Shutdown(grpc_error* error) {
- GRPC_ERROR_UNREF(Finished(error, true /* reset_on_error */));
-}
-
-} // namespace grpc_core
-
+ }
+ Unref();
+ return error;
+}
+
+void Chttp2IncomingByteStream::Shutdown(grpc_error* error) {
+ GRPC_ERROR_UNREF(Finished(error, true /* reset_on_error */));
+}
+
+} // namespace grpc_core
+
//
// RESOURCE QUOTAS
//
-
-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");
+
+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_resource_user_post_reclaimer(grpc_endpoint_get_resource_user(t->ep),
- false, &t->benign_reclaimer_locked);
- }
-}
-
-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_resource_user_post_reclaimer(grpc_endpoint_get_resource_user(t->ep),
+ false, &t->benign_reclaimer_locked);
+ }
+}
+
+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_resource_user_post_reclaimer(grpc_endpoint_get_resource_user(t->ep),
- true, &t->destructive_reclaimer_locked);
- }
-}
-
+ 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,
@@ -3159,36 +3159,36 @@ static void benign_reclaimer(void* arg, grpc_error* error) {
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) {
+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)) {
- gpr_log(GPR_INFO, "HTTP2: %s - send goaway to free memory",
+ gpr_log(GPR_INFO, "HTTP2: %s - send goaway to free memory",
t->peer_string.c_str());
- }
- send_goaway(t,
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Buffers full"),
- GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_ENHANCE_YOUR_CALM));
+ }
+ send_goaway(t,
+ 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)) {
- gpr_log(GPR_INFO,
- "HTTP2: %s - skip benign reclamation, there are still %" PRIdPTR
- " streams",
+ gpr_log(GPR_INFO,
+ "HTTP2: %s - skip benign reclamation, there are still %" PRIdPTR
+ " streams",
t->peer_string.c_str(),
grpc_chttp2_stream_map_size(&t->stream_map));
- }
- t->benign_reclaimer_registered = false;
- if (error != GRPC_ERROR_CANCELLED) {
- grpc_resource_user_finish_reclamation(
- grpc_endpoint_get_resource_user(t->ep));
- }
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "benign_reclaimer");
-}
-
+ }
+ t->benign_reclaimer_registered = false;
+ if (error != GRPC_ERROR_CANCELLED) {
+ grpc_resource_user_finish_reclamation(
+ grpc_endpoint_get_resource_user(t->ep));
+ }
+ 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,
@@ -3196,107 +3196,107 @@ static void destructive_reclaimer(void* arg, grpc_error* error) {
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);
- t->destructive_reclaimer_registered = false;
- if (error == GRPC_ERROR_NONE && n > 0) {
- grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(
- grpc_chttp2_stream_map_rand(&t->stream_map));
+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);
+ t->destructive_reclaimer_registered = false;
+ 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)) {
gpr_log(GPR_INFO, "HTTP2: %s - abandon stream id %d",
t->peer_string.c_str(), s->id);
- }
- grpc_chttp2_cancel_stream(
- t, s,
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Buffers full"),
- GRPC_ERROR_INT_HTTP2_ERROR,
- GRPC_HTTP2_ENHANCE_YOUR_CALM));
- if (n > 1) {
+ }
+ grpc_chttp2_cancel_stream(
+ t, s,
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Buffers full"),
+ GRPC_ERROR_INT_HTTP2_ERROR,
+ GRPC_HTTP2_ENHANCE_YOUR_CALM));
+ if (n > 1) {
// Since we cancel one stream per destructive reclamation, if
// there are more streams left, we can immediately post a new
// reclaimer in case the resource quota needs to free more
// memory
- post_destructive_reclaimer(t);
- }
- }
- if (error != GRPC_ERROR_CANCELLED) {
- grpc_resource_user_finish_reclamation(
- grpc_endpoint_get_resource_user(t->ep));
- }
- GRPC_CHTTP2_UNREF_TRANSPORT(t, "destructive_reclaimer");
-}
-
+ post_destructive_reclaimer(t);
+ }
+ }
+ if (error != GRPC_ERROR_CANCELLED) {
+ grpc_resource_user_finish_reclamation(
+ grpc_endpoint_get_resource_user(t->ep));
+ }
+ GRPC_CHTTP2_UNREF_TRANSPORT(t, "destructive_reclaimer");
+}
+
//
// MONITORING
//
-
-const char* grpc_chttp2_initiate_write_reason_string(
- grpc_chttp2_initiate_write_reason reason) {
- switch (reason) {
- case GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE:
- return "INITIAL_WRITE";
- case GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM:
- return "START_NEW_STREAM";
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE:
- return "SEND_MESSAGE";
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_INITIAL_METADATA:
- return "SEND_INITIAL_METADATA";
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_TRAILING_METADATA:
- return "SEND_TRAILING_METADATA";
- case GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING:
- return "RETRY_SEND_PING";
- case GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS:
- return "CONTINUE_PINGS";
- case GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT:
- return "GOAWAY_SENT";
- case GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM:
- return "RST_STREAM";
- case GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API:
- return "CLOSE_FROM_API";
- case GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL:
- return "STREAM_FLOW_CONTROL";
- case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL:
- return "TRANSPORT_FLOW_CONTROL";
- case GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS:
- return "SEND_SETTINGS";
- case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING:
- return "FLOW_CONTROL_UNSTALLED_BY_SETTING";
- case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE:
- return "FLOW_CONTROL_UNSTALLED_BY_UPDATE";
- case GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING:
- return "APPLICATION_PING";
+
+const char* grpc_chttp2_initiate_write_reason_string(
+ grpc_chttp2_initiate_write_reason reason) {
+ switch (reason) {
+ case GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE:
+ return "INITIAL_WRITE";
+ case GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM:
+ return "START_NEW_STREAM";
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE:
+ return "SEND_MESSAGE";
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_INITIAL_METADATA:
+ return "SEND_INITIAL_METADATA";
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_TRAILING_METADATA:
+ return "SEND_TRAILING_METADATA";
+ case GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING:
+ return "RETRY_SEND_PING";
+ case GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS:
+ return "CONTINUE_PINGS";
+ case GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT:
+ return "GOAWAY_SENT";
+ case GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM:
+ return "RST_STREAM";
+ case GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API:
+ return "CLOSE_FROM_API";
+ case GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL:
+ return "STREAM_FLOW_CONTROL";
+ case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL:
+ return "TRANSPORT_FLOW_CONTROL";
+ case GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS:
+ return "SEND_SETTINGS";
+ case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING:
+ return "FLOW_CONTROL_UNSTALLED_BY_SETTING";
+ case GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE:
+ return "FLOW_CONTROL_UNSTALLED_BY_UPDATE";
+ case GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING:
+ return "APPLICATION_PING";
case GRPC_CHTTP2_INITIATE_WRITE_BDP_PING:
return "BDP_PING";
- case GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING:
- return "KEEPALIVE_PING";
- case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED:
- return "TRANSPORT_FLOW_CONTROL_UNSTALLED";
- case GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE:
- return "PING_RESPONSE";
- case GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM:
- return "FORCE_RST_STREAM";
- }
- GPR_UNREACHABLE_CODE(return "unknown");
-}
-
-static grpc_endpoint* chttp2_get_endpoint(grpc_transport* t) {
- return (reinterpret_cast<grpc_chttp2_transport*>(t))->ep;
-}
-
-static const grpc_transport_vtable vtable = {sizeof(grpc_chttp2_stream),
- "chttp2",
- init_stream,
- set_pollset,
- set_pollset_set,
- perform_stream_op,
- perform_transport_op,
- destroy_stream,
- destroy_transport,
- chttp2_get_endpoint};
-
-static const grpc_transport_vtable* get_vtable(void) { return &vtable; }
-
+ case GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING:
+ return "KEEPALIVE_PING";
+ case GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED:
+ return "TRANSPORT_FLOW_CONTROL_UNSTALLED";
+ case GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE:
+ return "PING_RESPONSE";
+ case GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM:
+ return "FORCE_RST_STREAM";
+ }
+ GPR_UNREACHABLE_CODE(return "unknown");
+}
+
+static grpc_endpoint* chttp2_get_endpoint(grpc_transport* t) {
+ return (reinterpret_cast<grpc_chttp2_transport*>(t))->ep;
+}
+
+static const grpc_transport_vtable vtable = {sizeof(grpc_chttp2_stream),
+ "chttp2",
+ init_stream,
+ set_pollset,
+ set_pollset_set,
+ perform_stream_op,
+ perform_transport_op,
+ destroy_stream,
+ destroy_transport,
+ chttp2_get_endpoint};
+
+static const grpc_transport_vtable* get_vtable(void) { return &vtable; }
+
grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode>
grpc_chttp2_transport_get_socket_node(grpc_transport* transport) {
grpc_chttp2_transport* t =
@@ -3304,27 +3304,27 @@ grpc_chttp2_transport_get_socket_node(grpc_transport* transport) {
return t->channelz_socket;
}
-grpc_transport* grpc_create_chttp2_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);
- return &t->base;
-}
-
-void grpc_chttp2_transport_start_reading(
- grpc_transport* transport, grpc_slice_buffer* read_buffer,
- grpc_closure* notify_on_receive_settings) {
- grpc_chttp2_transport* t =
- reinterpret_cast<grpc_chttp2_transport*>(transport);
- GRPC_CHTTP2_REF_TRANSPORT(
- t, "reading_action"); /* matches unref inside reading_action */
- if (read_buffer != nullptr) {
- grpc_slice_buffer_move_into(read_buffer, &t->read_buffer);
- gpr_free(read_buffer);
- }
- t->notify_on_receive_settings = notify_on_receive_settings;
+ return &t->base;
+}
+
+void grpc_chttp2_transport_start_reading(
+ grpc_transport* transport, grpc_slice_buffer* read_buffer,
+ grpc_closure* notify_on_receive_settings) {
+ grpc_chttp2_transport* t =
+ reinterpret_cast<grpc_chttp2_transport*>(transport);
+ GRPC_CHTTP2_REF_TRANSPORT(
+ t, "reading_action"); /* matches unref inside reading_action */
+ if (read_buffer != nullptr) {
+ grpc_slice_buffer_move_into(read_buffer, &t->read_buffer);
+ 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);
-}
+}
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 b04630bbe2b..0ea8692a80d 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
@@ -1,52 +1,52 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_CHTTP2_TRANSPORT_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CHTTP2_TRANSPORT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/transport/transport.h"
-extern grpc_core::TraceFlag grpc_http_trace;
+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::TraceFlag grpc_trace_http2_stream_state;
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_refcount;
extern grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_hpack_parser;
-extern bool g_flow_control_enabled;
+extern bool g_flow_control_enabled;
-grpc_transport* grpc_create_chttp2_transport(
+grpc_transport* grpc_create_chttp2_transport(
const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client,
grpc_resource_user* resource_user = nullptr);
-
+
grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode>
grpc_chttp2_transport_get_socket_node(grpc_transport* transport);
/// Takes ownership of \a read_buffer, which (if non-NULL) contains
/// leftover bytes previously read from the endpoint (e.g., by handshakers).
-/// If non-null, \a notify_on_receive_settings will be scheduled when
-/// HTTP/2 settings are received from the peer.
-void grpc_chttp2_transport_start_reading(
- grpc_transport* transport, grpc_slice_buffer* read_buffer,
- grpc_closure* notify_on_receive_settings);
+/// If non-null, \a notify_on_receive_settings will be scheduled when
+/// HTTP/2 settings are received from the peer.
+void grpc_chttp2_transport_start_reading(
+ grpc_transport* transport, grpc_slice_buffer* read_buffer,
+ grpc_closure* notify_on_receive_settings);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CHTTP2_TRANSPORT_H */
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 fd76c4b3d9a..16c9dd2068c 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
@@ -1,241 +1,241 @@
-/*
- *
- * 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/ext/transport/chttp2/transport/flow_control.h"
-
-#include <inttypes.h>
-#include <limits.h>
-#include <math.h>
-#include <string.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/transport/chttp2/transport/flow_control.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <math.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-#include "src/core/lib/gpr/string.h"
-
-grpc_core::TraceFlag grpc_flowctl_trace(false, "flowctl");
-
-namespace grpc_core {
-namespace chttp2 {
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+#include "src/core/lib/gpr/string.h"
+
+grpc_core::TraceFlag grpc_flowctl_trace(false, "flowctl");
+
+namespace grpc_core {
+namespace chttp2 {
+
TestOnlyTransportTargetWindowEstimatesMocker*
g_test_only_transport_target_window_estimates_mocker;
-namespace {
-
-static constexpr const int kTracePadding = 30;
+namespace {
+
+static constexpr const int kTracePadding = 30;
static constexpr const uint32_t kMaxWindowUpdateSize = (1u << 31) - 1;
-
-static char* fmt_int64_diff_str(int64_t old_val, int64_t new_val) {
+
+static char* fmt_int64_diff_str(int64_t old_val, int64_t new_val) {
TString str;
- if (old_val != new_val) {
+ if (old_val != new_val) {
str = y_absl::StrFormat("%" PRId64 " -> %" PRId64 "", old_val, new_val);
- } else {
+ } else {
str = y_absl::StrFormat("%" PRId64 "", old_val);
- }
+ }
return gpr_leftpad(str.c_str(), ' ', kTracePadding);
-}
-
-static char* fmt_uint32_diff_str(uint32_t old_val, uint32_t new_val) {
+}
+
+static char* fmt_uint32_diff_str(uint32_t old_val, uint32_t new_val) {
TString str;
if (old_val != new_val) {
str = y_absl::StrFormat("%" PRIu32 " -> %" PRIu32 "", old_val, new_val);
- } else {
+ } else {
str = y_absl::StrFormat("%" PRIu32 "", old_val);
- }
+ }
return gpr_leftpad(str.c_str(), ' ', kTracePadding);
-}
-} // namespace
-
-void FlowControlTrace::Init(const char* reason, TransportFlowControl* tfc,
- StreamFlowControl* sfc) {
- tfc_ = tfc;
- sfc_ = sfc;
- reason_ = reason;
- remote_window_ = tfc->remote_window();
- target_window_ = tfc->target_window();
- announced_window_ = tfc->announced_window();
- if (sfc != nullptr) {
- remote_window_delta_ = sfc->remote_window_delta();
- local_window_delta_ = sfc->local_window_delta();
- announced_window_delta_ = sfc->announced_window_delta();
- }
-}
-
-void FlowControlTrace::Finish() {
- uint32_t acked_local_window =
- tfc_->transport()->settings[GRPC_SENT_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
- uint32_t remote_window =
- tfc_->transport()->settings[GRPC_PEER_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
- char* trw_str = fmt_int64_diff_str(remote_window_, tfc_->remote_window());
- char* tlw_str = fmt_int64_diff_str(target_window_, tfc_->target_window());
- char* taw_str =
- fmt_int64_diff_str(announced_window_, tfc_->announced_window());
- char* srw_str;
- char* slw_str;
- char* saw_str;
- if (sfc_ != nullptr) {
- srw_str = fmt_int64_diff_str(remote_window_delta_ + remote_window,
- sfc_->remote_window_delta() + remote_window);
+}
+} // namespace
+
+void FlowControlTrace::Init(const char* reason, TransportFlowControl* tfc,
+ StreamFlowControl* sfc) {
+ tfc_ = tfc;
+ sfc_ = sfc;
+ reason_ = reason;
+ remote_window_ = tfc->remote_window();
+ target_window_ = tfc->target_window();
+ announced_window_ = tfc->announced_window();
+ if (sfc != nullptr) {
+ remote_window_delta_ = sfc->remote_window_delta();
+ local_window_delta_ = sfc->local_window_delta();
+ announced_window_delta_ = sfc->announced_window_delta();
+ }
+}
+
+void FlowControlTrace::Finish() {
+ uint32_t acked_local_window =
+ tfc_->transport()->settings[GRPC_SENT_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
+ uint32_t remote_window =
+ tfc_->transport()->settings[GRPC_PEER_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
+ char* trw_str = fmt_int64_diff_str(remote_window_, tfc_->remote_window());
+ char* tlw_str = fmt_int64_diff_str(target_window_, tfc_->target_window());
+ char* taw_str =
+ fmt_int64_diff_str(announced_window_, tfc_->announced_window());
+ char* srw_str;
+ char* slw_str;
+ char* saw_str;
+ if (sfc_ != nullptr) {
+ srw_str = fmt_int64_diff_str(remote_window_delta_ + remote_window,
+ sfc_->remote_window_delta() + remote_window);
slw_str =
fmt_int64_diff_str(local_window_delta_ + acked_local_window,
sfc_->local_window_delta() + acked_local_window);
saw_str =
fmt_int64_diff_str(announced_window_delta_ + acked_local_window,
sfc_->announced_window_delta() + acked_local_window);
- } else {
- srw_str = gpr_leftpad("", ' ', kTracePadding);
- slw_str = gpr_leftpad("", ' ', kTracePadding);
- saw_str = gpr_leftpad("", ' ', kTracePadding);
- }
- gpr_log(GPR_DEBUG,
+ } else {
+ srw_str = gpr_leftpad("", ' ', kTracePadding);
+ slw_str = gpr_leftpad("", ' ', kTracePadding);
+ saw_str = gpr_leftpad("", ' ', kTracePadding);
+ }
+ gpr_log(GPR_DEBUG,
"%p[%u][%s] | %s | trw:%s, tlw:%s, taw:%s, srw:%s, slw:%s, saw:%s",
- tfc_, sfc_ != nullptr ? sfc_->stream()->id : 0,
- tfc_->transport()->is_client ? "cli" : "svr", reason_, trw_str,
- tlw_str, taw_str, srw_str, slw_str, saw_str);
- gpr_free(trw_str);
- gpr_free(tlw_str);
- gpr_free(taw_str);
- gpr_free(srw_str);
- gpr_free(slw_str);
- gpr_free(saw_str);
-}
-
-const char* FlowControlAction::UrgencyString(Urgency u) {
- switch (u) {
- case Urgency::NO_ACTION_NEEDED:
- return "no action";
- case Urgency::UPDATE_IMMEDIATELY:
- return "update immediately";
- case Urgency::QUEUE_UPDATE:
- return "queue update";
- default:
- GPR_UNREACHABLE_CODE(return "unknown");
- }
- GPR_UNREACHABLE_CODE(return "unknown");
-}
-
-void FlowControlAction::Trace(grpc_chttp2_transport* t) const {
- char* iw_str = fmt_uint32_diff_str(
- t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE],
- initial_window_size_);
- char* mf_str = fmt_uint32_diff_str(
- t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE],
- max_frame_size_);
- gpr_log(GPR_DEBUG, "t[%s], s[%s], iw:%s:%s mf:%s:%s",
- UrgencyString(send_transport_update_),
- UrgencyString(send_stream_update_),
- UrgencyString(send_initial_window_update_), iw_str,
- UrgencyString(send_max_frame_size_update_), mf_str);
- gpr_free(iw_str);
- gpr_free(mf_str);
-}
-
-TransportFlowControlDisabled::TransportFlowControlDisabled(
- grpc_chttp2_transport* t) {
- remote_window_ = kMaxWindow;
- target_initial_window_size_ = kMaxWindow;
- announced_window_ = kMaxWindow;
- t->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE] =
- kFrameSize;
- t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE] =
- kFrameSize;
- t->settings[GRPC_ACKED_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE] =
- kFrameSize;
- t->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE] =
- kMaxWindow;
- t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE] =
- kMaxWindow;
- t->settings[GRPC_ACKED_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE] =
- kMaxWindow;
-}
-
-TransportFlowControl::TransportFlowControl(const grpc_chttp2_transport* t,
- bool enable_bdp_probe)
- : t_(t),
- enable_bdp_probe_(enable_bdp_probe),
+ tfc_, sfc_ != nullptr ? sfc_->stream()->id : 0,
+ tfc_->transport()->is_client ? "cli" : "svr", reason_, trw_str,
+ tlw_str, taw_str, srw_str, slw_str, saw_str);
+ gpr_free(trw_str);
+ gpr_free(tlw_str);
+ gpr_free(taw_str);
+ gpr_free(srw_str);
+ gpr_free(slw_str);
+ gpr_free(saw_str);
+}
+
+const char* FlowControlAction::UrgencyString(Urgency u) {
+ switch (u) {
+ case Urgency::NO_ACTION_NEEDED:
+ return "no action";
+ case Urgency::UPDATE_IMMEDIATELY:
+ return "update immediately";
+ case Urgency::QUEUE_UPDATE:
+ return "queue update";
+ default:
+ GPR_UNREACHABLE_CODE(return "unknown");
+ }
+ GPR_UNREACHABLE_CODE(return "unknown");
+}
+
+void FlowControlAction::Trace(grpc_chttp2_transport* t) const {
+ char* iw_str = fmt_uint32_diff_str(
+ t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE],
+ initial_window_size_);
+ char* mf_str = fmt_uint32_diff_str(
+ t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE],
+ max_frame_size_);
+ gpr_log(GPR_DEBUG, "t[%s], s[%s], iw:%s:%s mf:%s:%s",
+ UrgencyString(send_transport_update_),
+ UrgencyString(send_stream_update_),
+ UrgencyString(send_initial_window_update_), iw_str,
+ UrgencyString(send_max_frame_size_update_), mf_str);
+ gpr_free(iw_str);
+ gpr_free(mf_str);
+}
+
+TransportFlowControlDisabled::TransportFlowControlDisabled(
+ grpc_chttp2_transport* t) {
+ remote_window_ = kMaxWindow;
+ target_initial_window_size_ = kMaxWindow;
+ announced_window_ = kMaxWindow;
+ t->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE] =
+ kFrameSize;
+ t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE] =
+ kFrameSize;
+ t->settings[GRPC_ACKED_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE] =
+ kFrameSize;
+ t->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE] =
+ kMaxWindow;
+ t->settings[GRPC_SENT_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE] =
+ kMaxWindow;
+ t->settings[GRPC_ACKED_SETTINGS][GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE] =
+ kMaxWindow;
+}
+
+TransportFlowControl::TransportFlowControl(const grpc_chttp2_transport* t,
+ bool enable_bdp_probe)
+ : t_(t),
+ enable_bdp_probe_(enable_bdp_probe),
bdp_estimator_(t->peer_string.c_str()),
- pid_controller_(grpc_core::PidController::Args()
- .set_gain_p(4)
- .set_gain_i(8)
- .set_gain_d(0)
- .set_initial_control_value(TargetLogBdp())
- .set_min_control_value(-1)
- .set_max_control_value(25)
- .set_integral_range(10)),
- last_pid_update_(grpc_core::ExecCtx::Get()->Now()) {}
-
-uint32_t TransportFlowControl::MaybeSendUpdate(bool writing_anyway) {
- FlowControlTrace trace("t updt sent", this, nullptr);
- const uint32_t target_announced_window =
+ pid_controller_(grpc_core::PidController::Args()
+ .set_gain_p(4)
+ .set_gain_i(8)
+ .set_gain_d(0)
+ .set_initial_control_value(TargetLogBdp())
+ .set_min_control_value(-1)
+ .set_max_control_value(25)
+ .set_integral_range(10)),
+ last_pid_update_(grpc_core::ExecCtx::Get()->Now()) {}
+
+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());
- if ((writing_anyway || announced_window_ <= target_announced_window / 2) &&
- announced_window_ != target_announced_window) {
- const uint32_t announce = static_cast<uint32_t> GPR_CLAMP(
+ if ((writing_anyway || announced_window_ <= target_announced_window / 2) &&
+ announced_window_ != target_announced_window) {
+ const uint32_t announce = static_cast<uint32_t> GPR_CLAMP(
target_announced_window - announced_window_, 0, kMaxWindowUpdateSize);
- announced_window_ += announce;
- return announce;
- }
- return 0;
-}
-
-grpc_error* TransportFlowControl::ValidateRecvData(
- int64_t incoming_frame_size) {
- if (incoming_frame_size > announced_window_) {
+ announced_window_ += announce;
+ return announce;
+ }
+ return 0;
+}
+
+grpc_error* TransportFlowControl::ValidateRecvData(
+ int64_t incoming_frame_size) {
+ if (incoming_frame_size > announced_window_) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("frame of size %" PRId64
" overflows local window of %" PRId64,
incoming_frame_size, announced_window_)
.c_str());
- }
- return GRPC_ERROR_NONE;
-}
-
-StreamFlowControl::StreamFlowControl(TransportFlowControl* tfc,
- const grpc_chttp2_stream* s)
- : tfc_(tfc), s_(s) {}
-
-grpc_error* StreamFlowControl::RecvData(int64_t incoming_frame_size) {
- FlowControlTrace trace(" data recv", tfc_, this);
-
- grpc_error* error = GRPC_ERROR_NONE;
- error = tfc_->ValidateRecvData(incoming_frame_size);
- if (error != GRPC_ERROR_NONE) return error;
-
- uint32_t sent_init_window =
- tfc_->transport()->settings[GRPC_SENT_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
- uint32_t acked_init_window =
- tfc_->transport()->settings[GRPC_ACKED_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
-
- int64_t acked_stream_window = announced_window_delta_ + acked_init_window;
- int64_t sent_stream_window = announced_window_delta_ + sent_init_window;
- if (incoming_frame_size > acked_stream_window) {
+ }
+ return GRPC_ERROR_NONE;
+}
+
+StreamFlowControl::StreamFlowControl(TransportFlowControl* tfc,
+ const grpc_chttp2_stream* s)
+ : tfc_(tfc), s_(s) {}
+
+grpc_error* StreamFlowControl::RecvData(int64_t incoming_frame_size) {
+ FlowControlTrace trace(" data recv", tfc_, this);
+
+ grpc_error* error = GRPC_ERROR_NONE;
+ error = tfc_->ValidateRecvData(incoming_frame_size);
+ if (error != GRPC_ERROR_NONE) return error;
+
+ uint32_t sent_init_window =
+ tfc_->transport()->settings[GRPC_SENT_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
+ uint32_t acked_init_window =
+ tfc_->transport()->settings[GRPC_ACKED_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
+
+ int64_t acked_stream_window = announced_window_delta_ + acked_init_window;
+ int64_t sent_stream_window = announced_window_delta_ + sent_init_window;
+ if (incoming_frame_size > acked_stream_window) {
//hotfix - do not check incoming_frame_size <= sent_stream_window - with old grpc version this is not true
gpr_log(GPR_ERROR,
"Incoming frame of size %" PRId64
@@ -247,110 +247,110 @@ grpc_error* StreamFlowControl::RecvData(int64_t incoming_frame_size) {
"broken HTTP2 implementations in the wild.\n"
"See (for example) https://github.com/netty/netty/issues/6520.",
incoming_frame_size, acked_stream_window, sent_stream_window);
- }
-
- UpdateAnnouncedWindowDelta(tfc_, -incoming_frame_size);
- local_window_delta_ -= incoming_frame_size;
- tfc_->CommitRecvData(incoming_frame_size);
- return GRPC_ERROR_NONE;
-}
-
-uint32_t StreamFlowControl::MaybeSendUpdate() {
- FlowControlTrace trace("s updt sent", tfc_, this);
- if (local_window_delta_ > announced_window_delta_) {
- uint32_t announce = static_cast<uint32_t> GPR_CLAMP(
+ }
+
+ UpdateAnnouncedWindowDelta(tfc_, -incoming_frame_size);
+ local_window_delta_ -= incoming_frame_size;
+ tfc_->CommitRecvData(incoming_frame_size);
+ return GRPC_ERROR_NONE;
+}
+
+uint32_t StreamFlowControl::MaybeSendUpdate() {
+ FlowControlTrace trace("s updt sent", tfc_, this);
+ if (local_window_delta_ > announced_window_delta_) {
+ uint32_t announce = static_cast<uint32_t> GPR_CLAMP(
local_window_delta_ - announced_window_delta_, 0, kMaxWindowUpdateSize);
- UpdateAnnouncedWindowDelta(tfc_, announce);
- return announce;
- }
- return 0;
-}
-
-void StreamFlowControl::IncomingByteStreamUpdate(size_t max_size_hint,
- size_t have_already) {
- FlowControlTrace trace("app st recv", tfc_, this);
- uint32_t max_recv_bytes;
- uint32_t sent_init_window =
- tfc_->transport()->settings[GRPC_SENT_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
-
- /* clamp max recv hint to an allowable size */
+ UpdateAnnouncedWindowDelta(tfc_, announce);
+ return announce;
+ }
+ return 0;
+}
+
+void StreamFlowControl::IncomingByteStreamUpdate(size_t max_size_hint,
+ size_t have_already) {
+ FlowControlTrace trace("app st recv", tfc_, this);
+ uint32_t max_recv_bytes;
+ uint32_t sent_init_window =
+ tfc_->transport()->settings[GRPC_SENT_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
+
+ /* clamp max recv hint to an allowable size */
if (max_size_hint >= kMaxWindowUpdateSize - sent_init_window) {
max_recv_bytes = kMaxWindowUpdateSize - sent_init_window;
- } else {
- max_recv_bytes = static_cast<uint32_t>(max_size_hint);
- }
-
- /* account for bytes already received but unknown to higher layers */
- if (max_recv_bytes >= have_already) {
- max_recv_bytes -= static_cast<uint32_t>(have_already);
- } else {
- max_recv_bytes = 0;
- }
-
- /* add some small lookahead to keep pipelines flowing */
+ } else {
+ max_recv_bytes = static_cast<uint32_t>(max_size_hint);
+ }
+
+ /* account for bytes already received but unknown to higher layers */
+ if (max_recv_bytes >= have_already) {
+ max_recv_bytes -= static_cast<uint32_t>(have_already);
+ } else {
+ max_recv_bytes = 0;
+ }
+
+ /* add some small lookahead to keep pipelines flowing */
GPR_DEBUG_ASSERT(max_recv_bytes <= kMaxWindowUpdateSize - sent_init_window);
- if (local_window_delta_ < max_recv_bytes) {
- uint32_t add_max_recv_bytes =
- static_cast<uint32_t>(max_recv_bytes - local_window_delta_);
- local_window_delta_ += add_max_recv_bytes;
- }
-}
-
-// Take in a target and modifies it based on the memory pressure of the system
-static double AdjustForMemoryPressure(grpc_resource_quota* quota,
- double target) {
- // do not increase window under heavy memory pressure.
- double memory_pressure = grpc_resource_quota_get_memory_pressure(quota);
- static const double kLowMemPressure = 0.1;
- static const double kZeroTarget = 22;
- static const double kHighMemPressure = 0.8;
- static const double kMaxMemPressure = 0.9;
- if (memory_pressure < kLowMemPressure && target < kZeroTarget) {
- target = (target - kZeroTarget) * memory_pressure / kLowMemPressure +
- kZeroTarget;
- } else if (memory_pressure > kHighMemPressure) {
- target *= 1 - GPR_MIN(1, (memory_pressure - kHighMemPressure) /
- (kMaxMemPressure - kHighMemPressure));
- }
- return target;
-}
-
-double TransportFlowControl::TargetLogBdp() {
- return AdjustForMemoryPressure(
- grpc_resource_user_quota(grpc_endpoint_get_resource_user(t_->ep)),
- 1 + log2(bdp_estimator_.EstimateBdp()));
-}
-
-double TransportFlowControl::SmoothLogBdp(double value) {
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
- double bdp_error = value - pid_controller_.last_control_value();
- const double dt = static_cast<double>(now - last_pid_update_) * 1e-3;
- last_pid_update_ = now;
- // Limit dt to 100ms
- const double kMaxDt = 0.1;
- return pid_controller_.Update(bdp_error, dt > kMaxDt ? kMaxDt : dt);
-}
-
-FlowControlAction::Urgency TransportFlowControl::DeltaUrgency(
- int64_t value, grpc_chttp2_setting_id setting_id) {
- int64_t delta = value - static_cast<int64_t>(
- t_->settings[GRPC_LOCAL_SETTINGS][setting_id]);
- // TODO(ncteisen): tune this
- if (delta != 0 && (delta <= -value / 5 || delta >= value / 5)) {
- return FlowControlAction::Urgency::QUEUE_UPDATE;
- } else {
- return FlowControlAction::Urgency::NO_ACTION_NEEDED;
- }
-}
-
-FlowControlAction TransportFlowControl::PeriodicUpdate() {
- FlowControlAction action;
- if (enable_bdp_probe_) {
- // get bdp estimate and update initial_window accordingly.
- // target might change based on how much memory pressure we are under
- // TODO(ncteisen): experiment with setting target to be huge under low
- // memory pressure.
+ if (local_window_delta_ < max_recv_bytes) {
+ uint32_t add_max_recv_bytes =
+ static_cast<uint32_t>(max_recv_bytes - local_window_delta_);
+ local_window_delta_ += add_max_recv_bytes;
+ }
+}
+
+// Take in a target and modifies it based on the memory pressure of the system
+static double AdjustForMemoryPressure(grpc_resource_quota* quota,
+ double target) {
+ // do not increase window under heavy memory pressure.
+ double memory_pressure = grpc_resource_quota_get_memory_pressure(quota);
+ static const double kLowMemPressure = 0.1;
+ static const double kZeroTarget = 22;
+ static const double kHighMemPressure = 0.8;
+ static const double kMaxMemPressure = 0.9;
+ if (memory_pressure < kLowMemPressure && target < kZeroTarget) {
+ target = (target - kZeroTarget) * memory_pressure / kLowMemPressure +
+ kZeroTarget;
+ } else if (memory_pressure > kHighMemPressure) {
+ target *= 1 - GPR_MIN(1, (memory_pressure - kHighMemPressure) /
+ (kMaxMemPressure - kHighMemPressure));
+ }
+ return target;
+}
+
+double TransportFlowControl::TargetLogBdp() {
+ return AdjustForMemoryPressure(
+ grpc_resource_user_quota(grpc_endpoint_get_resource_user(t_->ep)),
+ 1 + log2(bdp_estimator_.EstimateBdp()));
+}
+
+double TransportFlowControl::SmoothLogBdp(double value) {
+ grpc_millis now = grpc_core::ExecCtx::Get()->Now();
+ double bdp_error = value - pid_controller_.last_control_value();
+ const double dt = static_cast<double>(now - last_pid_update_) * 1e-3;
+ last_pid_update_ = now;
+ // Limit dt to 100ms
+ const double kMaxDt = 0.1;
+ return pid_controller_.Update(bdp_error, dt > kMaxDt ? kMaxDt : dt);
+}
+
+FlowControlAction::Urgency TransportFlowControl::DeltaUrgency(
+ int64_t value, grpc_chttp2_setting_id setting_id) {
+ int64_t delta = value - static_cast<int64_t>(
+ t_->settings[GRPC_LOCAL_SETTINGS][setting_id]);
+ // TODO(ncteisen): tune this
+ if (delta != 0 && (delta <= -value / 5 || delta >= value / 5)) {
+ return FlowControlAction::Urgency::QUEUE_UPDATE;
+ } else {
+ return FlowControlAction::Urgency::NO_ACTION_NEEDED;
+ }
+}
+
+FlowControlAction TransportFlowControl::PeriodicUpdate() {
+ FlowControlAction action;
+ if (enable_bdp_probe_) {
+ // get bdp estimate and update initial_window accordingly.
+ // target might change based on how much memory pressure we are under
+ // TODO(ncteisen): experiment with setting target to be huge under low
+ // memory pressure.
double target = pow(2, SmoothLogBdp(TargetLogBdp()));
if (g_test_only_transport_target_window_estimates_mocker != nullptr) {
// Hook for simulating unusual flow control situations in tests.
@@ -358,47 +358,47 @@ FlowControlAction TransportFlowControl::PeriodicUpdate() {
->ComputeNextTargetInitialWindowSizeFromPeriodicUpdate(
target_initial_window_size_ /* current target */);
}
- // Though initial window 'could' drop to 0, we keep the floor at 128
- target_initial_window_size_ =
- static_cast<int32_t> GPR_CLAMP(target, 128, INT32_MAX);
-
- action.set_send_initial_window_update(
- DeltaUrgency(target_initial_window_size_,
- GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE),
- static_cast<uint32_t>(target_initial_window_size_));
-
- // get bandwidth estimate and update max_frame accordingly.
- double bw_dbl = bdp_estimator_.EstimateBandwidth();
- // we target the max of BDP or bandwidth in microseconds.
- int32_t frame_size = static_cast<int32_t> GPR_CLAMP(
- GPR_MAX((int32_t)GPR_CLAMP(bw_dbl, 0, INT_MAX) / 1000,
- target_initial_window_size_),
- 16384, 16777215);
- action.set_send_max_frame_size_update(
- DeltaUrgency(static_cast<int64_t>(frame_size),
- GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE),
- frame_size);
- }
- return UpdateAction(action);
-}
-
-FlowControlAction StreamFlowControl::UpdateAction(FlowControlAction action) {
- // TODO(ncteisen): tune this
- if (!s_->read_closed) {
- uint32_t sent_init_window =
- tfc_->transport()->settings[GRPC_SENT_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
- if (local_window_delta_ > announced_window_delta_ &&
- announced_window_delta_ + sent_init_window <= sent_init_window / 2) {
- action.set_send_stream_update(
- FlowControlAction::Urgency::UPDATE_IMMEDIATELY);
- } else if (local_window_delta_ > announced_window_delta_) {
- action.set_send_stream_update(FlowControlAction::Urgency::QUEUE_UPDATE);
- }
- }
-
- return action;
-}
-
-} // namespace chttp2
-} // namespace grpc_core
+ // Though initial window 'could' drop to 0, we keep the floor at 128
+ target_initial_window_size_ =
+ static_cast<int32_t> GPR_CLAMP(target, 128, INT32_MAX);
+
+ action.set_send_initial_window_update(
+ DeltaUrgency(target_initial_window_size_,
+ GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE),
+ static_cast<uint32_t>(target_initial_window_size_));
+
+ // get bandwidth estimate and update max_frame accordingly.
+ double bw_dbl = bdp_estimator_.EstimateBandwidth();
+ // we target the max of BDP or bandwidth in microseconds.
+ int32_t frame_size = static_cast<int32_t> GPR_CLAMP(
+ GPR_MAX((int32_t)GPR_CLAMP(bw_dbl, 0, INT_MAX) / 1000,
+ target_initial_window_size_),
+ 16384, 16777215);
+ action.set_send_max_frame_size_update(
+ DeltaUrgency(static_cast<int64_t>(frame_size),
+ GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE),
+ frame_size);
+ }
+ return UpdateAction(action);
+}
+
+FlowControlAction StreamFlowControl::UpdateAction(FlowControlAction action) {
+ // TODO(ncteisen): tune this
+ if (!s_->read_closed) {
+ uint32_t sent_init_window =
+ tfc_->transport()->settings[GRPC_SENT_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE];
+ if (local_window_delta_ > announced_window_delta_ &&
+ announced_window_delta_ + sent_init_window <= sent_init_window / 2) {
+ action.set_send_stream_update(
+ FlowControlAction::Urgency::UPDATE_IMMEDIATELY);
+ } else if (local_window_delta_ > announced_window_delta_) {
+ action.set_send_stream_update(FlowControlAction::Urgency::QUEUE_UPDATE);
+ }
+ }
+
+ return action;
+}
+
+} // namespace chttp2
+} // namespace grpc_core
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 a55ab82efb4..25130903868 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
@@ -1,471 +1,471 @@
-/*
- *
- * 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_EXT_TRANSPORT_CHTTP2_TRANSPORT_FLOW_CONTROL_H
-#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FLOW_CONTROL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdint.h>
-
-#include "src/core/ext/transport/chttp2/transport/http2_settings.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/transport/bdp_estimator.h"
-#include "src/core/lib/transport/pid_controller.h"
-
-struct grpc_chttp2_transport;
-struct grpc_chttp2_stream;
-
-extern grpc_core::TraceFlag grpc_flowctl_trace;
-
-namespace grpc {
-namespace testing {
-class TrickledCHTTP2; // to make this a friend
-} // namespace testing
-} // namespace grpc
-
-namespace grpc_core {
-namespace chttp2 {
-
-static constexpr uint32_t kDefaultWindow = 65535;
-static constexpr int64_t kMaxWindow = static_cast<int64_t>((1u << 31) - 1);
-// TODO(ncteisen): Tune this
-static constexpr uint32_t kFrameSize = 1024 * 1024;
-
-class TransportFlowControl;
-class StreamFlowControl;
-
-// Encapsulates a collections of actions the transport needs to take with
-// regard to flow control. Each action comes with urgencies that tell the
-// transport how quickly the action must take place.
-class FlowControlAction {
- public:
- enum class Urgency : uint8_t {
- // Nothing to be done.
- NO_ACTION_NEEDED = 0,
- // Initiate a write to update the initial window immediately.
- UPDATE_IMMEDIATELY,
- // Push the flow control update into a send buffer, to be sent
- // out the next time a write is initiated.
- QUEUE_UPDATE,
- };
-
- Urgency send_stream_update() const { return send_stream_update_; }
- Urgency send_transport_update() const { return send_transport_update_; }
- Urgency send_initial_window_update() const {
- return send_initial_window_update_;
- }
- Urgency send_max_frame_size_update() const {
- return send_max_frame_size_update_;
- }
- uint32_t initial_window_size() const { return initial_window_size_; }
- uint32_t max_frame_size() const { return max_frame_size_; }
-
- FlowControlAction& set_send_stream_update(Urgency u) {
- send_stream_update_ = u;
- return *this;
- }
- FlowControlAction& set_send_transport_update(Urgency u) {
- send_transport_update_ = u;
- return *this;
- }
- FlowControlAction& set_send_initial_window_update(Urgency u,
- uint32_t update) {
- send_initial_window_update_ = u;
- initial_window_size_ = update;
- return *this;
- }
- FlowControlAction& set_send_max_frame_size_update(Urgency u,
- uint32_t update) {
- send_max_frame_size_update_ = u;
- max_frame_size_ = update;
- return *this;
- }
-
- static const char* UrgencyString(Urgency u);
- void Trace(grpc_chttp2_transport* t) const;
-
- private:
- Urgency send_stream_update_ = Urgency::NO_ACTION_NEEDED;
- Urgency send_transport_update_ = Urgency::NO_ACTION_NEEDED;
- Urgency send_initial_window_update_ = Urgency::NO_ACTION_NEEDED;
- Urgency send_max_frame_size_update_ = Urgency::NO_ACTION_NEEDED;
- uint32_t initial_window_size_ = 0;
- uint32_t max_frame_size_ = 0;
-};
-
-class FlowControlTrace {
- public:
- FlowControlTrace(const char* reason, TransportFlowControl* tfc,
- StreamFlowControl* sfc) {
- if (enabled_) Init(reason, tfc, sfc);
- }
-
- ~FlowControlTrace() {
- if (enabled_) Finish();
- }
-
- private:
- void Init(const char* reason, TransportFlowControl* tfc,
- StreamFlowControl* sfc);
- void Finish();
-
+/*
+ *
+ * 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_EXT_TRANSPORT_CHTTP2_TRANSPORT_FLOW_CONTROL_H
+#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FLOW_CONTROL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdint.h>
+
+#include "src/core/ext/transport/chttp2/transport/http2_settings.h"
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/transport/bdp_estimator.h"
+#include "src/core/lib/transport/pid_controller.h"
+
+struct grpc_chttp2_transport;
+struct grpc_chttp2_stream;
+
+extern grpc_core::TraceFlag grpc_flowctl_trace;
+
+namespace grpc {
+namespace testing {
+class TrickledCHTTP2; // to make this a friend
+} // namespace testing
+} // namespace grpc
+
+namespace grpc_core {
+namespace chttp2 {
+
+static constexpr uint32_t kDefaultWindow = 65535;
+static constexpr int64_t kMaxWindow = static_cast<int64_t>((1u << 31) - 1);
+// TODO(ncteisen): Tune this
+static constexpr uint32_t kFrameSize = 1024 * 1024;
+
+class TransportFlowControl;
+class StreamFlowControl;
+
+// Encapsulates a collections of actions the transport needs to take with
+// regard to flow control. Each action comes with urgencies that tell the
+// transport how quickly the action must take place.
+class FlowControlAction {
+ public:
+ enum class Urgency : uint8_t {
+ // Nothing to be done.
+ NO_ACTION_NEEDED = 0,
+ // Initiate a write to update the initial window immediately.
+ UPDATE_IMMEDIATELY,
+ // Push the flow control update into a send buffer, to be sent
+ // out the next time a write is initiated.
+ QUEUE_UPDATE,
+ };
+
+ Urgency send_stream_update() const { return send_stream_update_; }
+ Urgency send_transport_update() const { return send_transport_update_; }
+ Urgency send_initial_window_update() const {
+ return send_initial_window_update_;
+ }
+ Urgency send_max_frame_size_update() const {
+ return send_max_frame_size_update_;
+ }
+ uint32_t initial_window_size() const { return initial_window_size_; }
+ uint32_t max_frame_size() const { return max_frame_size_; }
+
+ FlowControlAction& set_send_stream_update(Urgency u) {
+ send_stream_update_ = u;
+ return *this;
+ }
+ FlowControlAction& set_send_transport_update(Urgency u) {
+ send_transport_update_ = u;
+ return *this;
+ }
+ FlowControlAction& set_send_initial_window_update(Urgency u,
+ uint32_t update) {
+ send_initial_window_update_ = u;
+ initial_window_size_ = update;
+ return *this;
+ }
+ FlowControlAction& set_send_max_frame_size_update(Urgency u,
+ uint32_t update) {
+ send_max_frame_size_update_ = u;
+ max_frame_size_ = update;
+ return *this;
+ }
+
+ static const char* UrgencyString(Urgency u);
+ void Trace(grpc_chttp2_transport* t) const;
+
+ private:
+ Urgency send_stream_update_ = Urgency::NO_ACTION_NEEDED;
+ Urgency send_transport_update_ = Urgency::NO_ACTION_NEEDED;
+ Urgency send_initial_window_update_ = Urgency::NO_ACTION_NEEDED;
+ Urgency send_max_frame_size_update_ = Urgency::NO_ACTION_NEEDED;
+ uint32_t initial_window_size_ = 0;
+ uint32_t max_frame_size_ = 0;
+};
+
+class FlowControlTrace {
+ public:
+ FlowControlTrace(const char* reason, TransportFlowControl* tfc,
+ StreamFlowControl* sfc) {
+ if (enabled_) Init(reason, tfc, sfc);
+ }
+
+ ~FlowControlTrace() {
+ if (enabled_) Finish();
+ }
+
+ private:
+ void Init(const char* reason, TransportFlowControl* tfc,
+ StreamFlowControl* sfc);
+ void Finish();
+
const bool enabled_ = GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace);
-
- TransportFlowControl* tfc_;
- StreamFlowControl* sfc_;
- const char* reason_;
- int64_t remote_window_;
- int64_t target_window_;
- int64_t announced_window_;
- int64_t remote_window_delta_;
- int64_t local_window_delta_;
- int64_t announced_window_delta_;
-};
-
-// Fat interface with all methods a flow control implementation needs to
+
+ TransportFlowControl* tfc_;
+ StreamFlowControl* sfc_;
+ const char* reason_;
+ int64_t remote_window_;
+ int64_t target_window_;
+ int64_t announced_window_;
+ int64_t remote_window_delta_;
+ int64_t local_window_delta_;
+ int64_t announced_window_delta_;
+};
+
+// Fat interface with all methods a flow control implementation needs to
// support.
-class TransportFlowControlBase {
- public:
- TransportFlowControlBase() {}
- virtual ~TransportFlowControlBase() {}
-
- // Is flow control enabled? This is needed in other codepaths like the checks
- // in parsing and in writing.
+class TransportFlowControlBase {
+ public:
+ TransportFlowControlBase() {}
+ virtual ~TransportFlowControlBase() {}
+
+ // Is flow control enabled? This is needed in other codepaths like the checks
+ // in parsing and in writing.
virtual bool flow_control_enabled() const = 0;
-
- // Called to check if the transport needs to send a WINDOW_UPDATE frame
+
+ // Called to check if the transport needs to send a WINDOW_UPDATE frame
virtual uint32_t MaybeSendUpdate(bool /* writing_anyway */) = 0;
-
- // Using the protected members, returns and Action to be taken by the
- // tranport.
+
+ // Using the protected members, returns and Action to be taken by the
+ // tranport.
virtual FlowControlAction MakeAction() = 0;
-
- // Using the protected members, returns and Action to be taken by the
- // tranport. Also checks for updates to our BDP estimate and acts
- // accordingly.
+
+ // Using the protected members, returns and Action to be taken by the
+ // tranport. Also checks for updates to our BDP estimate and acts
+ // accordingly.
virtual FlowControlAction PeriodicUpdate() = 0;
-
- // Called to do bookkeeping when a stream owned by this transport sends
- // data on the wire
+
+ // Called to do bookkeeping when a stream owned by this transport sends
+ // data on the wire
virtual void StreamSentData(int64_t /* size */) = 0;
-
- // Called to do bookkeeping when a stream owned by this transport receives
- // data from the wire. Also does error checking for frame size.
+
+ // Called to do bookkeeping when a stream owned by this transport receives
+ // data from the wire. Also does error checking for frame size.
virtual grpc_error* RecvData(int64_t /* incoming_frame_size */) = 0;
-
- // Called to do bookkeeping when we receive a WINDOW_UPDATE frame.
+
+ // Called to do bookkeeping when we receive a WINDOW_UPDATE frame.
virtual void RecvUpdate(uint32_t /* size */) = 0;
-
- // Returns the BdpEstimator held by this object. Caller is responsible for
- // checking for nullptr. TODO(ncteisen): consider fully encapsulating all
- // bdp estimator actions inside TransportFlowControl
- virtual BdpEstimator* bdp_estimator() { return nullptr; }
-
- // Getters
- int64_t remote_window() const { return remote_window_; }
- virtual int64_t target_window() const { return target_initial_window_size_; }
- int64_t announced_window() const { return announced_window_; }
-
- // Used in certain benchmarks in which we don't want FlowControl to be a
- // factor
- virtual void TestOnlyForceHugeWindow() {}
-
- protected:
- friend class ::grpc::testing::TrickledCHTTP2;
- int64_t remote_window_ = kDefaultWindow;
- int64_t target_initial_window_size_ = kDefaultWindow;
- int64_t announced_window_ = kDefaultWindow;
-};
-
-// Implementation of flow control that does NOTHING. Always returns maximum
-// values, never initiates writes, and assumes that the remote peer is doing
-// the same. To be used to narrow down on flow control as the cause of negative
-// performance.
-class TransportFlowControlDisabled final : public TransportFlowControlBase {
- public:
- // Maxes out all values
- TransportFlowControlDisabled(grpc_chttp2_transport* t);
-
- bool flow_control_enabled() const override { return false; }
-
- // Never do anything.
+
+ // Returns the BdpEstimator held by this object. Caller is responsible for
+ // checking for nullptr. TODO(ncteisen): consider fully encapsulating all
+ // bdp estimator actions inside TransportFlowControl
+ virtual BdpEstimator* bdp_estimator() { return nullptr; }
+
+ // Getters
+ int64_t remote_window() const { return remote_window_; }
+ virtual int64_t target_window() const { return target_initial_window_size_; }
+ int64_t announced_window() const { return announced_window_; }
+
+ // Used in certain benchmarks in which we don't want FlowControl to be a
+ // factor
+ virtual void TestOnlyForceHugeWindow() {}
+
+ protected:
+ friend class ::grpc::testing::TrickledCHTTP2;
+ int64_t remote_window_ = kDefaultWindow;
+ int64_t target_initial_window_size_ = kDefaultWindow;
+ int64_t announced_window_ = kDefaultWindow;
+};
+
+// Implementation of flow control that does NOTHING. Always returns maximum
+// values, never initiates writes, and assumes that the remote peer is doing
+// the same. To be used to narrow down on flow control as the cause of negative
+// performance.
+class TransportFlowControlDisabled final : public TransportFlowControlBase {
+ public:
+ // Maxes out all values
+ TransportFlowControlDisabled(grpc_chttp2_transport* t);
+
+ bool flow_control_enabled() const override { return false; }
+
+ // Never do anything.
uint32_t MaybeSendUpdate(bool /* writing_anyway */) override { return 0; }
- FlowControlAction MakeAction() override { return FlowControlAction(); }
- FlowControlAction PeriodicUpdate() override { return FlowControlAction(); }
+ 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 {
- return GRPC_ERROR_NONE;
- }
+ return GRPC_ERROR_NONE;
+ }
void RecvUpdate(uint32_t /* size */) override {}
-};
-
-// Implementation of flow control that abides to HTTP/2 spec and attempts
-// to be as performant as possible.
-class TransportFlowControl final : public TransportFlowControlBase {
- public:
- TransportFlowControl(const grpc_chttp2_transport* t, bool enable_bdp_probe);
- ~TransportFlowControl() {}
-
- bool flow_control_enabled() const override { return true; }
-
- bool bdp_probe() const { return enable_bdp_probe_; }
-
- // returns an announce if we should send a transport update to our peer,
- // else returns zero; writing_anyway indicates if a write would happen
- // regardless of the send - if it is false and this function returns non-zero,
- // this announce will cause a write to occur
- uint32_t MaybeSendUpdate(bool writing_anyway) override;
-
- // Reads the flow control data and returns and actionable struct that will
- // tell chttp2 exactly what it needs to do
- FlowControlAction MakeAction() override {
- return UpdateAction(FlowControlAction());
- }
-
- // Call periodically (at a low-ish rate, 100ms - 10s makes sense)
- // to perform more complex flow control calculations and return an action
- // to let chttp2 change its parameters
- FlowControlAction PeriodicUpdate() override;
-
- void StreamSentData(int64_t size) override { remote_window_ -= size; }
-
- grpc_error* ValidateRecvData(int64_t incoming_frame_size);
- void CommitRecvData(int64_t incoming_frame_size) {
- announced_window_ -= incoming_frame_size;
- }
-
- grpc_error* RecvData(int64_t incoming_frame_size) override {
- FlowControlTrace trace(" data recv", this, nullptr);
- grpc_error* error = ValidateRecvData(incoming_frame_size);
- if (error != GRPC_ERROR_NONE) return error;
- CommitRecvData(incoming_frame_size);
- return GRPC_ERROR_NONE;
- }
-
- // we have received a WINDOW_UPDATE frame for a transport
- void RecvUpdate(uint32_t size) override {
- FlowControlTrace trace("t updt recv", this, nullptr);
- remote_window_ += size;
- }
-
- // See comment above announced_stream_total_over_incoming_window_ for the
- // logic behind this decision.
- int64_t target_window() const override {
- return static_cast<uint32_t> GPR_MIN(
- (int64_t)((1u << 31) - 1),
- announced_stream_total_over_incoming_window_ +
- target_initial_window_size_);
- }
-
- const grpc_chttp2_transport* transport() const { return t_; }
-
- void PreUpdateAnnouncedWindowOverIncomingWindow(int64_t delta) {
- if (delta > 0) {
- announced_stream_total_over_incoming_window_ -= delta;
- }
- }
-
- void PostUpdateAnnouncedWindowOverIncomingWindow(int64_t delta) {
- if (delta > 0) {
- announced_stream_total_over_incoming_window_ += delta;
- }
- }
-
- BdpEstimator* bdp_estimator() override { return &bdp_estimator_; }
-
- void TestOnlyForceHugeWindow() override {
- announced_window_ = 1024 * 1024 * 1024;
- remote_window_ = 1024 * 1024 * 1024;
- }
-
- private:
- double TargetLogBdp();
- double SmoothLogBdp(double value);
- FlowControlAction::Urgency DeltaUrgency(int64_t value,
- grpc_chttp2_setting_id setting_id);
-
- FlowControlAction UpdateAction(FlowControlAction action) {
- if (announced_window_ < target_window() / 2) {
- action.set_send_transport_update(
- FlowControlAction::Urgency::UPDATE_IMMEDIATELY);
- }
- return action;
- }
-
- const grpc_chttp2_transport* const t_;
-
- /** calculating what we should give for local window:
- we track the total amount of flow control over initial window size
- across all streams: this is data that we want to receive right now (it
- has an outstanding read)
- and the total amount of flow control under initial window size across all
- streams: this is data we've read early
- we want to adjust incoming_window such that:
- incoming_window = total_over - max(bdp - total_under, 0) */
- int64_t announced_stream_total_over_incoming_window_ = 0;
-
- /** should we probe bdp? */
- const bool enable_bdp_probe_;
-
- /* bdp estimation */
- grpc_core::BdpEstimator bdp_estimator_;
-
- /* pid controller */
- grpc_core::PidController pid_controller_;
- grpc_millis last_pid_update_ = 0;
-};
-
-// Fat interface with all methods a stream flow control implementation needs
+};
+
+// Implementation of flow control that abides to HTTP/2 spec and attempts
+// to be as performant as possible.
+class TransportFlowControl final : public TransportFlowControlBase {
+ public:
+ TransportFlowControl(const grpc_chttp2_transport* t, bool enable_bdp_probe);
+ ~TransportFlowControl() {}
+
+ bool flow_control_enabled() const override { return true; }
+
+ bool bdp_probe() const { return enable_bdp_probe_; }
+
+ // returns an announce if we should send a transport update to our peer,
+ // else returns zero; writing_anyway indicates if a write would happen
+ // regardless of the send - if it is false and this function returns non-zero,
+ // this announce will cause a write to occur
+ uint32_t MaybeSendUpdate(bool writing_anyway) override;
+
+ // Reads the flow control data and returns and actionable struct that will
+ // tell chttp2 exactly what it needs to do
+ FlowControlAction MakeAction() override {
+ return UpdateAction(FlowControlAction());
+ }
+
+ // Call periodically (at a low-ish rate, 100ms - 10s makes sense)
+ // to perform more complex flow control calculations and return an action
+ // to let chttp2 change its parameters
+ FlowControlAction PeriodicUpdate() override;
+
+ void StreamSentData(int64_t size) override { remote_window_ -= size; }
+
+ grpc_error* ValidateRecvData(int64_t incoming_frame_size);
+ void CommitRecvData(int64_t incoming_frame_size) {
+ announced_window_ -= incoming_frame_size;
+ }
+
+ grpc_error* RecvData(int64_t incoming_frame_size) override {
+ FlowControlTrace trace(" data recv", this, nullptr);
+ grpc_error* error = ValidateRecvData(incoming_frame_size);
+ if (error != GRPC_ERROR_NONE) return error;
+ CommitRecvData(incoming_frame_size);
+ return GRPC_ERROR_NONE;
+ }
+
+ // we have received a WINDOW_UPDATE frame for a transport
+ void RecvUpdate(uint32_t size) override {
+ FlowControlTrace trace("t updt recv", this, nullptr);
+ remote_window_ += size;
+ }
+
+ // See comment above announced_stream_total_over_incoming_window_ for the
+ // logic behind this decision.
+ int64_t target_window() const override {
+ return static_cast<uint32_t> GPR_MIN(
+ (int64_t)((1u << 31) - 1),
+ announced_stream_total_over_incoming_window_ +
+ target_initial_window_size_);
+ }
+
+ const grpc_chttp2_transport* transport() const { return t_; }
+
+ void PreUpdateAnnouncedWindowOverIncomingWindow(int64_t delta) {
+ if (delta > 0) {
+ announced_stream_total_over_incoming_window_ -= delta;
+ }
+ }
+
+ void PostUpdateAnnouncedWindowOverIncomingWindow(int64_t delta) {
+ if (delta > 0) {
+ announced_stream_total_over_incoming_window_ += delta;
+ }
+ }
+
+ BdpEstimator* bdp_estimator() override { return &bdp_estimator_; }
+
+ void TestOnlyForceHugeWindow() override {
+ announced_window_ = 1024 * 1024 * 1024;
+ remote_window_ = 1024 * 1024 * 1024;
+ }
+
+ private:
+ double TargetLogBdp();
+ double SmoothLogBdp(double value);
+ FlowControlAction::Urgency DeltaUrgency(int64_t value,
+ grpc_chttp2_setting_id setting_id);
+
+ FlowControlAction UpdateAction(FlowControlAction action) {
+ if (announced_window_ < target_window() / 2) {
+ action.set_send_transport_update(
+ FlowControlAction::Urgency::UPDATE_IMMEDIATELY);
+ }
+ return action;
+ }
+
+ const grpc_chttp2_transport* const t_;
+
+ /** calculating what we should give for local window:
+ we track the total amount of flow control over initial window size
+ across all streams: this is data that we want to receive right now (it
+ has an outstanding read)
+ and the total amount of flow control under initial window size across all
+ streams: this is data we've read early
+ we want to adjust incoming_window such that:
+ incoming_window = total_over - max(bdp - total_under, 0) */
+ int64_t announced_stream_total_over_incoming_window_ = 0;
+
+ /** should we probe bdp? */
+ const bool enable_bdp_probe_;
+
+ /* bdp estimation */
+ grpc_core::BdpEstimator bdp_estimator_;
+
+ /* pid controller */
+ grpc_core::PidController pid_controller_;
+ grpc_millis last_pid_update_ = 0;
+};
+
+// Fat interface with all methods a stream flow control implementation needs
// to support.
-class StreamFlowControlBase {
- public:
- StreamFlowControlBase() {}
- virtual ~StreamFlowControlBase() {}
-
- // Updates an action using the protected members.
+class StreamFlowControlBase {
+ public:
+ StreamFlowControlBase() {}
+ virtual ~StreamFlowControlBase() {}
+
+ // Updates an action using the protected members.
virtual FlowControlAction UpdateAction(FlowControlAction /* action */) {
abort();
}
-
- // Using the protected members, returns an Action for this stream to be
- // taken by the tranport.
+
+ // Using the protected members, returns an Action for this stream to be
+ // taken by the tranport.
virtual FlowControlAction MakeAction() = 0;
-
- // Bookkeeping for when data is sent on this stream.
+
+ // Bookkeeping for when data is sent on this stream.
virtual void SentData(int64_t /* outgoing_frame_size */) = 0;
-
- // Bookkeeping and error checking for when data is received by this stream.
+
+ // Bookkeeping and error checking for when data is received by this stream.
virtual grpc_error* RecvData(int64_t /* incoming_frame_size */) = 0;
-
- // Called to check if this stream needs to send a WINDOW_UPDATE frame.
+
+ // Called to check if this stream needs to send a WINDOW_UPDATE frame.
virtual uint32_t MaybeSendUpdate() = 0;
-
- // Bookkeeping for receiving a WINDOW_UPDATE from for this stream.
+
+ // Bookkeeping for receiving a WINDOW_UPDATE from for this stream.
virtual void RecvUpdate(uint32_t /* size */) = 0;
-
- // 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.
+
+ // 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 */) {
- abort();
- }
-
- // Used in certain benchmarks in which we don't want FlowControl to be a
- // factor
- virtual void TestOnlyForceHugeWindow() {}
-
- // Getters
- int64_t remote_window_delta() { return remote_window_delta_; }
- int64_t local_window_delta() { return local_window_delta_; }
- int64_t announced_window_delta() { return announced_window_delta_; }
-
- protected:
- friend class ::grpc::testing::TrickledCHTTP2;
- int64_t remote_window_delta_ = 0;
- int64_t local_window_delta_ = 0;
- int64_t announced_window_delta_ = 0;
-};
-
-// Implementation of flow control that does NOTHING. Always returns maximum
-// values, never initiates writes, and assumes that the remote peer is doing
-// the same. To be used to narrow down on flow control as the cause of negative
-// performance.
-class StreamFlowControlDisabled : public StreamFlowControlBase {
- public:
- FlowControlAction UpdateAction(FlowControlAction action) override {
- return action;
- }
- FlowControlAction MakeAction() override { return FlowControlAction(); }
+ abort();
+ }
+
+ // Used in certain benchmarks in which we don't want FlowControl to be a
+ // factor
+ virtual void TestOnlyForceHugeWindow() {}
+
+ // Getters
+ int64_t remote_window_delta() { return remote_window_delta_; }
+ int64_t local_window_delta() { return local_window_delta_; }
+ int64_t announced_window_delta() { return announced_window_delta_; }
+
+ protected:
+ friend class ::grpc::testing::TrickledCHTTP2;
+ int64_t remote_window_delta_ = 0;
+ int64_t local_window_delta_ = 0;
+ int64_t announced_window_delta_ = 0;
+};
+
+// Implementation of flow control that does NOTHING. Always returns maximum
+// values, never initiates writes, and assumes that the remote peer is doing
+// the same. To be used to narrow down on flow control as the cause of negative
+// performance.
+class StreamFlowControlDisabled : public StreamFlowControlBase {
+ public:
+ FlowControlAction UpdateAction(FlowControlAction action) override {
+ return action;
+ }
+ FlowControlAction MakeAction() override { return FlowControlAction(); }
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; }
+ 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 {}
-};
-
-// Implementation of flow control that abides to HTTP/2 spec and attempts
-// to be as performant as possible.
-class StreamFlowControl final : public StreamFlowControlBase {
- public:
- StreamFlowControl(TransportFlowControl* tfc, const grpc_chttp2_stream* s);
- ~StreamFlowControl() {
- tfc_->PreUpdateAnnouncedWindowOverIncomingWindow(announced_window_delta_);
- }
-
- FlowControlAction UpdateAction(FlowControlAction action) override;
- FlowControlAction MakeAction() override {
- return UpdateAction(tfc_->MakeAction());
- }
-
- // we have sent data on the wire, we must track this in our bookkeeping for
- // the remote peer's flow control.
- void SentData(int64_t outgoing_frame_size) override {
- FlowControlTrace tracer(" data sent", tfc_, this);
- tfc_->StreamSentData(outgoing_frame_size);
- remote_window_delta_ -= outgoing_frame_size;
- }
-
- // we have received data from the wire
- grpc_error* RecvData(int64_t incoming_frame_size) override;
-
- // returns an announce if we should send a stream update to our peer, else
- // returns zero
- uint32_t MaybeSendUpdate() override;
-
- // we have received a WINDOW_UPDATE frame for a stream
- void RecvUpdate(uint32_t size) override {
- FlowControlTrace trace("s updt recv", tfc_, this);
- remote_window_delta_ += size;
- }
-
- // the application is asking for a certain amount of bytes
- void IncomingByteStreamUpdate(size_t max_size_hint,
- size_t have_already) override;
-
- int64_t remote_window_delta() const { return remote_window_delta_; }
- int64_t local_window_delta() const { return local_window_delta_; }
- int64_t announced_window_delta() const { return announced_window_delta_; }
-
- const grpc_chttp2_stream* stream() const { return s_; }
-
- void TestOnlyForceHugeWindow() override {
- announced_window_delta_ = 1024 * 1024 * 1024;
- local_window_delta_ = 1024 * 1024 * 1024;
- remote_window_delta_ = 1024 * 1024 * 1024;
- }
-
- private:
- TransportFlowControl* const tfc_;
- const grpc_chttp2_stream* const s_;
-
- void UpdateAnnouncedWindowDelta(TransportFlowControl* tfc, int64_t change) {
- tfc->PreUpdateAnnouncedWindowOverIncomingWindow(announced_window_delta_);
- announced_window_delta_ += change;
- tfc->PostUpdateAnnouncedWindowOverIncomingWindow(announced_window_delta_);
- }
-};
-
+};
+
+// Implementation of flow control that abides to HTTP/2 spec and attempts
+// to be as performant as possible.
+class StreamFlowControl final : public StreamFlowControlBase {
+ public:
+ StreamFlowControl(TransportFlowControl* tfc, const grpc_chttp2_stream* s);
+ ~StreamFlowControl() {
+ tfc_->PreUpdateAnnouncedWindowOverIncomingWindow(announced_window_delta_);
+ }
+
+ FlowControlAction UpdateAction(FlowControlAction action) override;
+ FlowControlAction MakeAction() override {
+ return UpdateAction(tfc_->MakeAction());
+ }
+
+ // we have sent data on the wire, we must track this in our bookkeeping for
+ // the remote peer's flow control.
+ void SentData(int64_t outgoing_frame_size) override {
+ FlowControlTrace tracer(" data sent", tfc_, this);
+ tfc_->StreamSentData(outgoing_frame_size);
+ remote_window_delta_ -= outgoing_frame_size;
+ }
+
+ // we have received data from the wire
+ grpc_error* RecvData(int64_t incoming_frame_size) override;
+
+ // returns an announce if we should send a stream update to our peer, else
+ // returns zero
+ uint32_t MaybeSendUpdate() override;
+
+ // we have received a WINDOW_UPDATE frame for a stream
+ void RecvUpdate(uint32_t size) override {
+ FlowControlTrace trace("s updt recv", tfc_, this);
+ remote_window_delta_ += size;
+ }
+
+ // the application is asking for a certain amount of bytes
+ void IncomingByteStreamUpdate(size_t max_size_hint,
+ size_t have_already) override;
+
+ int64_t remote_window_delta() const { return remote_window_delta_; }
+ int64_t local_window_delta() const { return local_window_delta_; }
+ int64_t announced_window_delta() const { return announced_window_delta_; }
+
+ const grpc_chttp2_stream* stream() const { return s_; }
+
+ void TestOnlyForceHugeWindow() override {
+ announced_window_delta_ = 1024 * 1024 * 1024;
+ local_window_delta_ = 1024 * 1024 * 1024;
+ remote_window_delta_ = 1024 * 1024 * 1024;
+ }
+
+ private:
+ TransportFlowControl* const tfc_;
+ const grpc_chttp2_stream* const s_;
+
+ void UpdateAnnouncedWindowDelta(TransportFlowControl* tfc, int64_t change) {
+ tfc->PreUpdateAnnouncedWindowOverIncomingWindow(announced_window_delta_);
+ announced_window_delta_ += change;
+ tfc->PostUpdateAnnouncedWindowOverIncomingWindow(announced_window_delta_);
+ }
+};
+
class TestOnlyTransportTargetWindowEstimatesMocker {
public:
virtual ~TestOnlyTransportTargetWindowEstimatesMocker() {}
@@ -476,7 +476,7 @@ class TestOnlyTransportTargetWindowEstimatesMocker {
extern TestOnlyTransportTargetWindowEstimatesMocker*
g_test_only_transport_target_window_estimates_mocker;
-} // namespace chttp2
-} // namespace grpc_core
-
-#endif
+} // namespace chttp2
+} // namespace grpc_core
+
+#endif
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame.h
index 083c0076e71..5f5a0993ed9 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,8 +21,8 @@
#include <grpc/support/port_platform.h>
-#include <grpc/slice.h>
-
+#include <grpc/slice.h>
+
#include "src/core/lib/iomgr/error.h"
/* defined in internal.h */
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 6869bdb006d..08e26f66d6e 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
@@ -1,304 +1,304 @@
-/*
- *
- * 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/transport/chttp2/transport/frame_data.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/transport/chttp2/transport/frame_data.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/transport/transport.h"
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/transport/transport.h"
+
grpc_chttp2_data_parser::~grpc_chttp2_data_parser() {
if (parsing_frame != nullptr) {
GRPC_ERROR_UNREF(parsing_frame->Finished(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Parser destroyed"), false));
- }
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Parser destroyed"), false));
+ }
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) {
- if (flags & ~GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
+ if (flags & ~GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
return grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("unsupported data flags: 0x%02x", flags).c_str()),
GRPC_ERROR_INT_STREAM_ID, static_cast<intptr_t>(stream_id));
- }
-
- if (flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
- s->received_last_frame = true;
+ }
+
+ if (flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
+ s->received_last_frame = true;
s->eos_received = true;
- } else {
- s->received_last_frame = false;
- }
-
- return GRPC_ERROR_NONE;
-}
-
-void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf,
- uint32_t write_bytes, int is_eof,
- grpc_transport_one_way_stats* stats,
- grpc_slice_buffer* outbuf) {
- grpc_slice hdr;
- uint8_t* p;
- static const size_t header_size = 9;
-
- hdr = GRPC_SLICE_MALLOC(header_size);
- p = GRPC_SLICE_START_PTR(hdr);
- GPR_ASSERT(write_bytes < (1 << 24));
- *p++ = static_cast<uint8_t>(write_bytes >> 16);
- *p++ = static_cast<uint8_t>(write_bytes >> 8);
- *p++ = static_cast<uint8_t>(write_bytes);
- *p++ = GRPC_CHTTP2_FRAME_DATA;
- *p++ = is_eof ? GRPC_CHTTP2_DATA_FLAG_END_STREAM : 0;
- *p++ = static_cast<uint8_t>(id >> 24);
- *p++ = static_cast<uint8_t>(id >> 16);
- *p++ = static_cast<uint8_t>(id >> 8);
- *p++ = static_cast<uint8_t>(id);
- grpc_slice_buffer_add(outbuf, hdr);
-
- grpc_slice_buffer_move_first_no_ref(inbuf, write_bytes, outbuf);
-
- stats->framing_bytes += header_size;
- stats->data_bytes += write_bytes;
-}
-
-grpc_error* grpc_deframe_unprocessed_incoming_frames(
- grpc_chttp2_data_parser* p, grpc_chttp2_stream* s,
- grpc_slice_buffer* slices, grpc_slice* slice_out,
- grpc_core::OrphanablePtr<grpc_core::ByteStream>* stream_out) {
- grpc_error* error = GRPC_ERROR_NONE;
- grpc_chttp2_transport* t = s->t;
-
- while (slices->count > 0) {
- uint8_t* beg = nullptr;
- uint8_t* end = nullptr;
- uint8_t* cur = nullptr;
-
+ } else {
+ s->received_last_frame = false;
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf,
+ uint32_t write_bytes, int is_eof,
+ grpc_transport_one_way_stats* stats,
+ grpc_slice_buffer* outbuf) {
+ grpc_slice hdr;
+ uint8_t* p;
+ static const size_t header_size = 9;
+
+ hdr = GRPC_SLICE_MALLOC(header_size);
+ p = GRPC_SLICE_START_PTR(hdr);
+ GPR_ASSERT(write_bytes < (1 << 24));
+ *p++ = static_cast<uint8_t>(write_bytes >> 16);
+ *p++ = static_cast<uint8_t>(write_bytes >> 8);
+ *p++ = static_cast<uint8_t>(write_bytes);
+ *p++ = GRPC_CHTTP2_FRAME_DATA;
+ *p++ = is_eof ? GRPC_CHTTP2_DATA_FLAG_END_STREAM : 0;
+ *p++ = static_cast<uint8_t>(id >> 24);
+ *p++ = static_cast<uint8_t>(id >> 16);
+ *p++ = static_cast<uint8_t>(id >> 8);
+ *p++ = static_cast<uint8_t>(id);
+ grpc_slice_buffer_add(outbuf, hdr);
+
+ grpc_slice_buffer_move_first_no_ref(inbuf, write_bytes, outbuf);
+
+ stats->framing_bytes += header_size;
+ stats->data_bytes += write_bytes;
+}
+
+grpc_error* grpc_deframe_unprocessed_incoming_frames(
+ grpc_chttp2_data_parser* p, grpc_chttp2_stream* s,
+ grpc_slice_buffer* slices, grpc_slice* slice_out,
+ grpc_core::OrphanablePtr<grpc_core::ByteStream>* stream_out) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ grpc_chttp2_transport* t = s->t;
+
+ while (slices->count > 0) {
+ uint8_t* beg = nullptr;
+ 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);
- cur = beg;
- uint32_t message_flags;
-
- if (cur == end) {
+ cur = beg;
+ uint32_t message_flags;
+
+ if (cur == end) {
grpc_slice_buffer_remove_first(slices);
- continue;
- }
-
- switch (p->state) {
- case GRPC_CHTTP2_DATA_ERROR:
- p->state = GRPC_CHTTP2_DATA_ERROR;
+ continue;
+ }
+
+ switch (p->state) {
+ case GRPC_CHTTP2_DATA_ERROR:
+ p->state = GRPC_CHTTP2_DATA_ERROR;
grpc_slice_buffer_remove_first(slices);
- return GRPC_ERROR_REF(p->error);
- case GRPC_CHTTP2_DATA_FH_0:
- s->stats.incoming.framing_bytes++;
- p->frame_type = *cur;
- switch (p->frame_type) {
- case 0:
- p->is_frame_compressed = false; /* GPR_FALSE */
- break;
- case 1:
- p->is_frame_compressed = true; /* GPR_TRUE */
- break;
- default:
+ return GRPC_ERROR_REF(p->error);
+ case GRPC_CHTTP2_DATA_FH_0:
+ s->stats.incoming.framing_bytes++;
+ p->frame_type = *cur;
+ switch (p->frame_type) {
+ case 0:
+ p->is_frame_compressed = false; /* GPR_FALSE */
+ break;
+ case 1:
+ p->is_frame_compressed = true; /* GPR_TRUE */
+ break;
+ default:
p->error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("Bad GRPC frame type 0x%02x", p->frame_type)
.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_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_int(p->error, GRPC_ERROR_INT_OFFSET, cur - beg);
- p->state = GRPC_CHTTP2_DATA_ERROR;
+ 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);
- return GRPC_ERROR_REF(p->error);
- }
- if (++cur == end) {
- p->state = GRPC_CHTTP2_DATA_FH_1;
+ return GRPC_ERROR_REF(p->error);
+ }
+ if (++cur == end) {
+ p->state = GRPC_CHTTP2_DATA_FH_1;
grpc_slice_buffer_remove_first(slices);
- continue;
- }
- /* fallthrough */
- case GRPC_CHTTP2_DATA_FH_1:
- s->stats.incoming.framing_bytes++;
- p->frame_size = (static_cast<uint32_t>(*cur)) << 24;
- if (++cur == end) {
- p->state = GRPC_CHTTP2_DATA_FH_2;
+ continue;
+ }
+ /* fallthrough */
+ case GRPC_CHTTP2_DATA_FH_1:
+ s->stats.incoming.framing_bytes++;
+ 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);
- continue;
- }
- /* fallthrough */
- case GRPC_CHTTP2_DATA_FH_2:
- s->stats.incoming.framing_bytes++;
- p->frame_size |= (static_cast<uint32_t>(*cur)) << 16;
- if (++cur == end) {
- p->state = GRPC_CHTTP2_DATA_FH_3;
+ continue;
+ }
+ /* fallthrough */
+ case GRPC_CHTTP2_DATA_FH_2:
+ s->stats.incoming.framing_bytes++;
+ 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);
- continue;
- }
- /* fallthrough */
- case GRPC_CHTTP2_DATA_FH_3:
- s->stats.incoming.framing_bytes++;
- p->frame_size |= (static_cast<uint32_t>(*cur)) << 8;
- if (++cur == end) {
- p->state = GRPC_CHTTP2_DATA_FH_4;
+ continue;
+ }
+ /* fallthrough */
+ case GRPC_CHTTP2_DATA_FH_3:
+ s->stats.incoming.framing_bytes++;
+ 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);
- continue;
- }
- /* fallthrough */
- case GRPC_CHTTP2_DATA_FH_4:
- s->stats.incoming.framing_bytes++;
- GPR_ASSERT(stream_out != nullptr);
- GPR_ASSERT(p->parsing_frame == nullptr);
- p->frame_size |= (static_cast<uint32_t>(*cur));
+ continue;
+ }
+ /* fallthrough */
+ case GRPC_CHTTP2_DATA_FH_4:
+ s->stats.incoming.framing_bytes++;
+ GPR_ASSERT(stream_out != nullptr);
+ GPR_ASSERT(p->parsing_frame == nullptr);
+ p->frame_size |= (static_cast<uint32_t>(*cur));
if (t->channelz_socket != nullptr) {
t->channelz_socket->RecordMessageReceived();
}
- p->state = GRPC_CHTTP2_DATA_FRAME;
- ++cur;
- message_flags = 0;
- if (p->is_frame_compressed) {
- message_flags |= GRPC_WRITE_INTERNAL_COMPRESS;
- }
+ p->state = GRPC_CHTTP2_DATA_FRAME;
+ ++cur;
+ message_flags = 0;
+ if (p->is_frame_compressed) {
+ message_flags |= GRPC_WRITE_INTERNAL_COMPRESS;
+ }
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) {
- GRPC_ERROR_UNREF(p->parsing_frame->Finished(GRPC_ERROR_NONE, true));
- p->parsing_frame = nullptr;
- p->state = GRPC_CHTTP2_DATA_FH_0;
- }
- s->pending_byte_stream = true;
- if (cur != end) {
+ t, s, p->frame_size, message_flags);
+ stream_out->reset(p->parsing_frame);
+ if (p->parsing_frame->remaining_bytes() == 0) {
+ GRPC_ERROR_UNREF(p->parsing_frame->Finished(GRPC_ERROR_NONE, true));
+ p->parsing_frame = nullptr;
+ p->state = GRPC_CHTTP2_DATA_FH_0;
+ }
+ 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);
- }
- return GRPC_ERROR_NONE;
- case GRPC_CHTTP2_DATA_FRAME: {
- GPR_ASSERT(p->parsing_frame != nullptr);
- GPR_ASSERT(slice_out != nullptr);
- if (cur == end) {
+ }
+ 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);
- continue;
- }
- uint32_t remaining = static_cast<uint32_t>(end - cur);
- if (remaining == p->frame_size) {
- s->stats.incoming.data_bytes += remaining;
- if (GRPC_ERROR_NONE !=
- (error = p->parsing_frame->Push(
+ continue;
+ }
+ uint32_t remaining = static_cast<uint32_t>(end - cur);
+ 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),
- static_cast<size_t>(end - beg)),
- slice_out))) {
+ static_cast<size_t>(end - beg)),
+ slice_out))) {
grpc_slice_buffer_remove_first(slices);
- return error;
- }
- if (GRPC_ERROR_NONE !=
- (error = p->parsing_frame->Finished(GRPC_ERROR_NONE, true))) {
+ return error;
+ }
+ if (GRPC_ERROR_NONE !=
+ (error = p->parsing_frame->Finished(GRPC_ERROR_NONE, true))) {
grpc_slice_buffer_remove_first(slices);
- return error;
- }
- p->parsing_frame = nullptr;
- p->state = GRPC_CHTTP2_DATA_FH_0;
+ return error;
+ }
+ p->parsing_frame = nullptr;
+ p->state = GRPC_CHTTP2_DATA_FH_0;
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(
+ 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),
- static_cast<size_t>(end - beg)),
- slice_out))) {
- return error;
- }
- p->frame_size -= remaining;
+ static_cast<size_t>(end - beg)),
+ slice_out))) {
+ return error;
+ }
+ p->frame_size -= remaining;
grpc_slice_buffer_remove_first(slices);
- return GRPC_ERROR_NONE;
- } else {
- GPR_ASSERT(remaining > p->frame_size);
- s->stats.incoming.data_bytes += p->frame_size;
- if (GRPC_ERROR_NONE !=
- p->parsing_frame->Push(
- grpc_slice_sub(
+ return GRPC_ERROR_NONE;
+ } else {
+ GPR_ASSERT(remaining > p->frame_size);
+ s->stats.incoming.data_bytes += p->frame_size;
+ if (GRPC_ERROR_NONE !=
+ p->parsing_frame->Push(
+ grpc_slice_sub(
*slice, static_cast<size_t>(cur - beg),
- static_cast<size_t>(cur + p->frame_size - beg)),
- slice_out)) {
+ static_cast<size_t>(cur + p->frame_size - beg)),
+ slice_out)) {
grpc_slice_buffer_remove_first(slices);
- return error;
- }
- if (GRPC_ERROR_NONE !=
- (error = p->parsing_frame->Finished(GRPC_ERROR_NONE, true))) {
+ return error;
+ }
+ if (GRPC_ERROR_NONE !=
+ (error = p->parsing_frame->Finished(GRPC_ERROR_NONE, true))) {
grpc_slice_buffer_remove_first(slices);
- return error;
- }
- p->parsing_frame = nullptr;
- p->state = GRPC_CHTTP2_DATA_FH_0;
- cur += p->frame_size;
+ 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));
- return GRPC_ERROR_NONE;
- }
- }
- }
- }
- return GRPC_ERROR_NONE;
-}
-
+ return GRPC_ERROR_NONE;
+ }
+ }
+ }
+ }
+ return GRPC_ERROR_NONE;
+}
+
grpc_error* grpc_chttp2_data_parser_parse(void* /*parser*/,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+ grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
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);
- grpc_chttp2_maybe_complete_recv_message(t, s);
- } else if (s->on_next) {
- GPR_ASSERT(s->frame_storage.length == 0);
- grpc_slice_ref_internal(slice);
- grpc_slice_buffer_add(&s->unprocessed_incoming_frames_buffer, slice);
+ if (!s->pending_byte_stream) {
+ grpc_slice_ref_internal(slice);
+ grpc_slice_buffer_add(&s->frame_storage, slice);
+ grpc_chttp2_maybe_complete_recv_message(t, s);
+ } else if (s->on_next) {
+ 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);
- s->on_next = nullptr;
- s->unprocessed_incoming_frames_decompressed = false;
- } else {
- grpc_slice_ref_internal(slice);
- grpc_slice_buffer_add(&s->frame_storage, slice);
- }
-
- if (is_last && s->received_last_frame) {
- grpc_chttp2_mark_stream_closed(t, s, true, false, GRPC_ERROR_NONE);
- }
-
- return GRPC_ERROR_NONE;
-}
+ s->on_next = nullptr;
+ s->unprocessed_incoming_frames_decompressed = false;
+ } else {
+ grpc_slice_ref_internal(slice);
+ grpc_slice_buffer_add(&s->frame_storage, slice);
+ }
+
+ if (is_last && s->received_last_frame) {
+ grpc_chttp2_mark_stream_closed(t, s, true, false, GRPC_ERROR_NONE);
+ }
+
+ return GRPC_ERROR_NONE;
+}
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 ec3890098ec..08cfb7b0257 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
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,8 +21,8 @@
/* Parser for GRPC streams embedded in DATA frames */
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include <grpc/slice_buffer.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
@@ -39,9 +39,9 @@ typedef enum {
GRPC_CHTTP2_DATA_ERROR
} grpc_chttp2_stream_state;
-namespace grpc_core {
-class Chttp2IncomingByteStream;
-} // namespace grpc_core
+namespace grpc_core {
+class Chttp2IncomingByteStream;
+} // namespace grpc_core
struct grpc_chttp2_data_parser {
grpc_chttp2_data_parser() = default;
@@ -57,26 +57,26 @@ struct grpc_chttp2_data_parser {
};
/* start processing a new data frame */
-grpc_error* grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser* parser,
+grpc_error* grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser* parser,
uint8_t flags,
- uint32_t stream_id,
- grpc_chttp2_stream* s);
+ uint32_t stream_id,
+ grpc_chttp2_stream* s);
/* handle a slice of a data frame - is_last indicates the last slice of a
frame */
-grpc_error* grpc_chttp2_data_parser_parse(void* parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+grpc_error* grpc_chttp2_data_parser_parse(void* parser,
+ grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
const grpc_slice& slice, int is_last);
-void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf,
+void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf,
uint32_t write_bytes, int is_eof,
- grpc_transport_one_way_stats* stats,
- grpc_slice_buffer* outbuf);
-
-grpc_error* grpc_deframe_unprocessed_incoming_frames(
- grpc_chttp2_data_parser* p, grpc_chttp2_stream* s,
- grpc_slice_buffer* slices, grpc_slice* slice_out,
- grpc_core::OrphanablePtr<grpc_core::ByteStream>* stream_out);
+ grpc_transport_one_way_stats* stats,
+ grpc_slice_buffer* outbuf);
+grpc_error* grpc_deframe_unprocessed_incoming_frames(
+ grpc_chttp2_data_parser* p, grpc_chttp2_stream* s,
+ grpc_slice_buffer* slices, grpc_slice* slice_out,
+ grpc_core::OrphanablePtr<grpc_core::ByteStream>* stream_out);
+
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_DATA_H */
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 79a8a03dc7e..7804bbb6a0d 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
@@ -1,185 +1,185 @@
-/*
- *
- * 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/transport/chttp2/transport/frame_goaway.h"
-#include "src/core/ext/transport/chttp2/transport/internal.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/transport/chttp2/transport/frame_goaway.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser* p) {
- p->debug_data = nullptr;
-}
-
-void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser* p) {
- gpr_free(p->debug_data);
-}
-
-grpc_error* grpc_chttp2_goaway_parser_begin_frame(grpc_chttp2_goaway_parser* p,
- uint32_t length,
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser* p) {
+ p->debug_data = nullptr;
+}
+
+void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser* p) {
+ gpr_free(p->debug_data);
+}
+
+grpc_error* grpc_chttp2_goaway_parser_begin_frame(grpc_chttp2_goaway_parser* p,
+ uint32_t length,
uint8_t /*flags*/) {
- if (length < 8) {
+ if (length < 8) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("goaway frame too short (%d bytes)", length).c_str());
- }
-
- gpr_free(p->debug_data);
- p->debug_length = length - 8;
- p->debug_data = static_cast<char*>(gpr_malloc(p->debug_length));
- p->debug_pos = 0;
- p->state = GRPC_CHTTP2_GOAWAY_LSI0;
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_chttp2_goaway_parser_parse(void* parser,
- grpc_chttp2_transport* t,
+ }
+
+ gpr_free(p->debug_data);
+ p->debug_length = length - 8;
+ p->debug_data = static_cast<char*>(gpr_malloc(p->debug_length));
+ p->debug_pos = 0;
+ p->state = GRPC_CHTTP2_GOAWAY_LSI0;
+ return GRPC_ERROR_NONE;
+}
+
+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_goaway_parser* p =
- static_cast<grpc_chttp2_goaway_parser*>(parser);
-
- switch (p->state) {
- case GRPC_CHTTP2_GOAWAY_LSI0:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_LSI0;
- return GRPC_ERROR_NONE;
- }
- p->last_stream_id = (static_cast<uint32_t>(*cur)) << 24;
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_LSI1:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_LSI1;
- return GRPC_ERROR_NONE;
- }
- p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 16;
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_LSI2:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_LSI2;
- return GRPC_ERROR_NONE;
- }
- p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 8;
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_LSI3:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_LSI3;
- return GRPC_ERROR_NONE;
- }
- p->last_stream_id |= (static_cast<uint32_t>(*cur));
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_ERR0:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_ERR0;
- return GRPC_ERROR_NONE;
- }
- p->error_code = (static_cast<uint32_t>(*cur)) << 24;
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_ERR1:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_ERR1;
- return GRPC_ERROR_NONE;
- }
- p->error_code |= (static_cast<uint32_t>(*cur)) << 16;
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_ERR2:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_ERR2;
- return GRPC_ERROR_NONE;
- }
- p->error_code |= (static_cast<uint32_t>(*cur)) << 8;
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_ERR3:
- if (cur == end) {
- p->state = GRPC_CHTTP2_GOAWAY_ERR3;
- return GRPC_ERROR_NONE;
- }
- p->error_code |= (static_cast<uint32_t>(*cur));
- ++cur;
- /* fallthrough */
- case GRPC_CHTTP2_GOAWAY_DEBUG:
- if (end != cur)
- memcpy(p->debug_data + p->debug_pos, cur,
- static_cast<size_t>(end - cur));
- GPR_ASSERT((size_t)(end - cur) < UINT32_MAX - p->debug_pos);
- p->debug_pos += static_cast<uint32_t>(end - cur);
- p->state = GRPC_CHTTP2_GOAWAY_DEBUG;
- if (is_last) {
- grpc_chttp2_add_incoming_goaway(
+ grpc_chttp2_goaway_parser* p =
+ static_cast<grpc_chttp2_goaway_parser*>(parser);
+
+ switch (p->state) {
+ case GRPC_CHTTP2_GOAWAY_LSI0:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_LSI0;
+ return GRPC_ERROR_NONE;
+ }
+ p->last_stream_id = (static_cast<uint32_t>(*cur)) << 24;
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_LSI1:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_LSI1;
+ return GRPC_ERROR_NONE;
+ }
+ p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 16;
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_LSI2:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_LSI2;
+ return GRPC_ERROR_NONE;
+ }
+ p->last_stream_id |= (static_cast<uint32_t>(*cur)) << 8;
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_LSI3:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_LSI3;
+ return GRPC_ERROR_NONE;
+ }
+ p->last_stream_id |= (static_cast<uint32_t>(*cur));
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_ERR0:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_ERR0;
+ return GRPC_ERROR_NONE;
+ }
+ p->error_code = (static_cast<uint32_t>(*cur)) << 24;
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_ERR1:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_ERR1;
+ return GRPC_ERROR_NONE;
+ }
+ p->error_code |= (static_cast<uint32_t>(*cur)) << 16;
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_ERR2:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_ERR2;
+ return GRPC_ERROR_NONE;
+ }
+ p->error_code |= (static_cast<uint32_t>(*cur)) << 8;
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_ERR3:
+ if (cur == end) {
+ p->state = GRPC_CHTTP2_GOAWAY_ERR3;
+ return GRPC_ERROR_NONE;
+ }
+ p->error_code |= (static_cast<uint32_t>(*cur));
+ ++cur;
+ /* fallthrough */
+ case GRPC_CHTTP2_GOAWAY_DEBUG:
+ if (end != cur)
+ memcpy(p->debug_data + p->debug_pos, cur,
+ static_cast<size_t>(end - cur));
+ GPR_ASSERT((size_t)(end - cur) < UINT32_MAX - p->debug_pos);
+ p->debug_pos += static_cast<uint32_t>(end - cur);
+ p->state = GRPC_CHTTP2_GOAWAY_DEBUG;
+ if (is_last) {
+ grpc_chttp2_add_incoming_goaway(
t, p->error_code, p->last_stream_id,
- grpc_slice_new(p->debug_data, p->debug_length, gpr_free));
- p->debug_data = nullptr;
- }
- return GRPC_ERROR_NONE;
- }
- GPR_UNREACHABLE_CODE(
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here"));
-}
-
-void grpc_chttp2_goaway_append(uint32_t last_stream_id, uint32_t error_code,
+ grpc_slice_new(p->debug_data, p->debug_length, gpr_free));
+ p->debug_data = nullptr;
+ }
+ return GRPC_ERROR_NONE;
+ }
+ GPR_UNREACHABLE_CODE(
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here"));
+}
+
+void grpc_chttp2_goaway_append(uint32_t last_stream_id, uint32_t error_code,
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);
- uint32_t frame_length;
- GPR_ASSERT(GRPC_SLICE_LENGTH(debug_data) < UINT32_MAX - 4 - 4);
- frame_length = 4 + 4 + static_cast<uint32_t> GRPC_SLICE_LENGTH(debug_data);
-
- /* frame header: length */
- *p++ = static_cast<uint8_t>(frame_length >> 16);
- *p++ = static_cast<uint8_t>(frame_length >> 8);
- *p++ = static_cast<uint8_t>(frame_length);
- /* frame header: type */
- *p++ = GRPC_CHTTP2_FRAME_GOAWAY;
- /* frame header: flags */
- *p++ = 0;
- /* frame header: stream id */
- *p++ = 0;
- *p++ = 0;
- *p++ = 0;
- *p++ = 0;
- /* payload: last stream id */
- *p++ = static_cast<uint8_t>(last_stream_id >> 24);
- *p++ = static_cast<uint8_t>(last_stream_id >> 16);
- *p++ = static_cast<uint8_t>(last_stream_id >> 8);
- *p++ = static_cast<uint8_t>(last_stream_id);
- /* payload: error code */
- *p++ = static_cast<uint8_t>(error_code >> 24);
- *p++ = static_cast<uint8_t>(error_code >> 16);
- *p++ = static_cast<uint8_t>(error_code >> 8);
- *p++ = static_cast<uint8_t>(error_code);
- GPR_ASSERT(p == GRPC_SLICE_END_PTR(header));
- grpc_slice_buffer_add(slice_buffer, header);
- grpc_slice_buffer_add(slice_buffer, debug_data);
-}
+ grpc_slice_buffer* slice_buffer) {
+ grpc_slice header = GRPC_SLICE_MALLOC(9 + 4 + 4);
+ uint8_t* p = GRPC_SLICE_START_PTR(header);
+ uint32_t frame_length;
+ GPR_ASSERT(GRPC_SLICE_LENGTH(debug_data) < UINT32_MAX - 4 - 4);
+ frame_length = 4 + 4 + static_cast<uint32_t> GRPC_SLICE_LENGTH(debug_data);
+
+ /* frame header: length */
+ *p++ = static_cast<uint8_t>(frame_length >> 16);
+ *p++ = static_cast<uint8_t>(frame_length >> 8);
+ *p++ = static_cast<uint8_t>(frame_length);
+ /* frame header: type */
+ *p++ = GRPC_CHTTP2_FRAME_GOAWAY;
+ /* frame header: flags */
+ *p++ = 0;
+ /* frame header: stream id */
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = 0;
+ /* payload: last stream id */
+ *p++ = static_cast<uint8_t>(last_stream_id >> 24);
+ *p++ = static_cast<uint8_t>(last_stream_id >> 16);
+ *p++ = static_cast<uint8_t>(last_stream_id >> 8);
+ *p++ = static_cast<uint8_t>(last_stream_id);
+ /* payload: error code */
+ *p++ = static_cast<uint8_t>(error_code >> 24);
+ *p++ = static_cast<uint8_t>(error_code >> 16);
+ *p++ = static_cast<uint8_t>(error_code >> 8);
+ *p++ = static_cast<uint8_t>(error_code);
+ GPR_ASSERT(p == GRPC_SLICE_END_PTR(header));
+ grpc_slice_buffer_add(slice_buffer, header);
+ grpc_slice_buffer_add(slice_buffer, debug_data);
+}
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 df6274d6286..075706d1fa1 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_FRAME_GOAWAY_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_GOAWAY_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include <grpc/slice_buffer.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
@@ -41,22 +41,22 @@ struct grpc_chttp2_goaway_parser {
grpc_chttp2_goaway_parse_state state;
uint32_t last_stream_id;
uint32_t error_code;
- char* debug_data;
+ char* debug_data;
uint32_t debug_length;
uint32_t debug_pos;
};
-void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser* p);
-void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser* p);
-grpc_error* grpc_chttp2_goaway_parser_begin_frame(
- grpc_chttp2_goaway_parser* parser, uint32_t length, uint8_t flags);
-grpc_error* grpc_chttp2_goaway_parser_parse(void* parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser* p);
+void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser* p);
+grpc_error* grpc_chttp2_goaway_parser_begin_frame(
+ grpc_chttp2_goaway_parser* parser, uint32_t length, uint8_t flags);
+grpc_error* grpc_chttp2_goaway_parser_parse(void* parser,
+ grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
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,
- grpc_slice_buffer* slice_buffer);
+ 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 ae152099ba5..6af753b93e1 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
@@ -1,132 +1,132 @@
-/*
- *
- * 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/transport/chttp2/transport/frame_ping.h"
-#include "src/core/ext/transport/chttp2/transport/internal.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/transport/chttp2/transport/frame_ping.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-static bool g_disable_ping_ack = false;
-
-grpc_slice grpc_chttp2_ping_create(uint8_t ack, uint64_t opaque_8bytes) {
- grpc_slice slice = GRPC_SLICE_MALLOC(9 + 8);
- uint8_t* p = GRPC_SLICE_START_PTR(slice);
-
- *p++ = 0;
- *p++ = 0;
- *p++ = 8;
- *p++ = GRPC_CHTTP2_FRAME_PING;
- *p++ = ack ? 1 : 0;
- *p++ = 0;
- *p++ = 0;
- *p++ = 0;
- *p++ = 0;
- *p++ = static_cast<uint8_t>(opaque_8bytes >> 56);
- *p++ = static_cast<uint8_t>(opaque_8bytes >> 48);
- *p++ = static_cast<uint8_t>(opaque_8bytes >> 40);
- *p++ = static_cast<uint8_t>(opaque_8bytes >> 32);
- *p++ = static_cast<uint8_t>(opaque_8bytes >> 24);
- *p++ = static_cast<uint8_t>(opaque_8bytes >> 16);
- *p++ = static_cast<uint8_t>(opaque_8bytes >> 8);
- *p++ = static_cast<uint8_t>(opaque_8bytes);
-
- return slice;
-}
-
-grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser,
- uint32_t length,
- uint8_t flags) {
- if (flags & 0xfe || length != 8) {
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+static bool g_disable_ping_ack = false;
+
+grpc_slice grpc_chttp2_ping_create(uint8_t ack, uint64_t opaque_8bytes) {
+ grpc_slice slice = GRPC_SLICE_MALLOC(9 + 8);
+ uint8_t* p = GRPC_SLICE_START_PTR(slice);
+
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = 8;
+ *p++ = GRPC_CHTTP2_FRAME_PING;
+ *p++ = ack ? 1 : 0;
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = static_cast<uint8_t>(opaque_8bytes >> 56);
+ *p++ = static_cast<uint8_t>(opaque_8bytes >> 48);
+ *p++ = static_cast<uint8_t>(opaque_8bytes >> 40);
+ *p++ = static_cast<uint8_t>(opaque_8bytes >> 32);
+ *p++ = static_cast<uint8_t>(opaque_8bytes >> 24);
+ *p++ = static_cast<uint8_t>(opaque_8bytes >> 16);
+ *p++ = static_cast<uint8_t>(opaque_8bytes >> 8);
+ *p++ = static_cast<uint8_t>(opaque_8bytes);
+
+ return slice;
+}
+
+grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser,
+ uint32_t length,
+ uint8_t flags) {
+ if (flags & 0xfe || length != 8) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("invalid ping: length=%d, flags=%02x", length, flags)
.c_str());
- }
- parser->byte = 0;
- parser->is_ack = flags;
- parser->opaque_8bytes = 0;
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_chttp2_ping_parser_parse(void* parser,
- grpc_chttp2_transport* t,
+ }
+ parser->byte = 0;
+ parser->is_ack = flags;
+ parser->opaque_8bytes = 0;
+ return GRPC_ERROR_NONE;
+}
+
+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_ping_parser* p = static_cast<grpc_chttp2_ping_parser*>(parser);
-
- while (p->byte != 8 && cur != end) {
- p->opaque_8bytes |= ((static_cast<uint64_t>(*cur)) << (56 - 8 * p->byte));
- cur++;
- p->byte++;
- }
-
- if (p->byte == 8) {
- GPR_ASSERT(is_last);
- if (p->is_ack) {
- grpc_chttp2_ack_ping(t, p->opaque_8bytes);
- } else {
- if (!t->is_client) {
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
- grpc_millis next_allowed_ping =
- t->ping_recv_state.last_ping_recv_time +
- t->ping_policy.min_recv_ping_interval_without_data;
-
- if (t->keepalive_permit_without_calls == 0 &&
- grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
- /* According to RFC1122, the interval of TCP Keep-Alive is default to
- no less than two hours. When there is no outstanding streams, we
- restrict the number of PINGS equivalent to TCP Keep-Alive. */
- next_allowed_ping =
- t->ping_recv_state.last_ping_recv_time + 7200 * GPR_MS_PER_SEC;
- }
-
- if (next_allowed_ping > now) {
- grpc_chttp2_add_ping_strike(t);
- }
-
- t->ping_recv_state.last_ping_recv_time = now;
- }
- if (!g_disable_ping_ack) {
- if (t->ping_ack_count == t->ping_ack_capacity) {
- t->ping_ack_capacity = GPR_MAX(t->ping_ack_capacity * 3 / 2, 3);
- t->ping_acks = static_cast<uint64_t*>(gpr_realloc(
- t->ping_acks, t->ping_ack_capacity * sizeof(*t->ping_acks)));
- }
+ grpc_chttp2_ping_parser* p = static_cast<grpc_chttp2_ping_parser*>(parser);
+
+ while (p->byte != 8 && cur != end) {
+ p->opaque_8bytes |= ((static_cast<uint64_t>(*cur)) << (56 - 8 * p->byte));
+ cur++;
+ p->byte++;
+ }
+
+ if (p->byte == 8) {
+ GPR_ASSERT(is_last);
+ if (p->is_ack) {
+ grpc_chttp2_ack_ping(t, p->opaque_8bytes);
+ } else {
+ if (!t->is_client) {
+ grpc_millis now = grpc_core::ExecCtx::Get()->Now();
+ grpc_millis next_allowed_ping =
+ t->ping_recv_state.last_ping_recv_time +
+ t->ping_policy.min_recv_ping_interval_without_data;
+
+ if (t->keepalive_permit_without_calls == 0 &&
+ grpc_chttp2_stream_map_size(&t->stream_map) == 0) {
+ /* According to RFC1122, the interval of TCP Keep-Alive is default to
+ no less than two hours. When there is no outstanding streams, we
+ restrict the number of PINGS equivalent to TCP Keep-Alive. */
+ next_allowed_ping =
+ t->ping_recv_state.last_ping_recv_time + 7200 * GPR_MS_PER_SEC;
+ }
+
+ if (next_allowed_ping > now) {
+ grpc_chttp2_add_ping_strike(t);
+ }
+
+ t->ping_recv_state.last_ping_recv_time = now;
+ }
+ if (!g_disable_ping_ack) {
+ if (t->ping_ack_count == t->ping_ack_capacity) {
+ t->ping_ack_capacity = GPR_MAX(t->ping_ack_capacity * 3 / 2, 3);
+ 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->ping_acks[t->ping_ack_count++] = p->opaque_8bytes;
- grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE);
- }
- }
- }
-
- return GRPC_ERROR_NONE;
-}
-
-void grpc_set_disable_ping_ack(bool disable_ping_ack) {
- g_disable_ping_ack = disable_ping_ack;
-}
+ t->ping_acks[t->ping_ack_count++] = p->opaque_8bytes;
+ grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE);
+ }
+ }
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+void grpc_set_disable_ping_ack(bool disable_ping_ack) {
+ g_disable_ping_ack = disable_ping_ack;
+}
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 e356bf43f07..69c528e0982 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
@@ -1,44 +1,44 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_FRAME_PING_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_PING_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
struct grpc_chttp2_ping_parser {
uint8_t byte;
uint8_t is_ack;
- uint64_t opaque_8bytes;
+ uint64_t opaque_8bytes;
};
-grpc_slice grpc_chttp2_ping_create(uint8_t ack, uint64_t opaque_8bytes);
+grpc_slice grpc_chttp2_ping_create(uint8_t ack, uint64_t opaque_8bytes);
-grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser,
+grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser,
uint32_t length, uint8_t flags);
-grpc_error* grpc_chttp2_ping_parser_parse(void* parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+grpc_error* grpc_chttp2_ping_parser_parse(void* parser,
+ grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
const grpc_slice& slice, int is_last);
-/* Test-only function for disabling ping ack */
-void grpc_set_disable_ping_ack(bool disable_ping_ack);
-
+/* Test-only function for disabling ping ack */
+void grpc_set_disable_ping_ack(bool disable_ping_ack);
+
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_PING_H */
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 5113329991b..2c314cfd794 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
@@ -1,65 +1,65 @@
-/*
- *
- * 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/transport/chttp2/transport/frame_rst_stream.h"
-#include "src/core/ext/transport/chttp2/transport/internal.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/transport/chttp2/transport/frame_rst_stream.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/ext/transport/chttp2/transport/frame.h"
+#include <grpc/support/alloc.h>
+#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/transport/http2_errors.h"
-
-grpc_slice grpc_chttp2_rst_stream_create(uint32_t id, uint32_t code,
- grpc_transport_one_way_stats* stats) {
- static const size_t frame_size = 13;
- grpc_slice slice = GRPC_SLICE_MALLOC(frame_size);
+#include "src/core/lib/transport/http2_errors.h"
+
+grpc_slice grpc_chttp2_rst_stream_create(uint32_t id, uint32_t code,
+ grpc_transport_one_way_stats* stats) {
+ static const size_t frame_size = 13;
+ grpc_slice slice = GRPC_SLICE_MALLOC(frame_size);
if (stats != nullptr) stats->framing_bytes += frame_size;
- uint8_t* p = GRPC_SLICE_START_PTR(slice);
-
- // Frame size.
- *p++ = 0;
- *p++ = 0;
- *p++ = 4;
- // Frame type.
- *p++ = GRPC_CHTTP2_FRAME_RST_STREAM;
- // Flags.
- *p++ = 0;
- // Stream ID.
- *p++ = static_cast<uint8_t>(id >> 24);
- *p++ = static_cast<uint8_t>(id >> 16);
- *p++ = static_cast<uint8_t>(id >> 8);
- *p++ = static_cast<uint8_t>(id);
- // Error code.
- *p++ = static_cast<uint8_t>(code >> 24);
- *p++ = static_cast<uint8_t>(code >> 16);
- *p++ = static_cast<uint8_t>(code >> 8);
- *p++ = static_cast<uint8_t>(code);
-
- return slice;
-}
-
+ uint8_t* p = GRPC_SLICE_START_PTR(slice);
+
+ // Frame size.
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = 4;
+ // Frame type.
+ *p++ = GRPC_CHTTP2_FRAME_RST_STREAM;
+ // Flags.
+ *p++ = 0;
+ // Stream ID.
+ *p++ = static_cast<uint8_t>(id >> 24);
+ *p++ = static_cast<uint8_t>(id >> 16);
+ *p++ = static_cast<uint8_t>(id >> 8);
+ *p++ = static_cast<uint8_t>(id);
+ // Error code.
+ *p++ = static_cast<uint8_t>(code >> 24);
+ *p++ = static_cast<uint8_t>(code >> 16);
+ *p++ = static_cast<uint8_t>(code >> 8);
+ *p++ = static_cast<uint8_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) {
@@ -68,54 +68,54 @@ void grpc_chttp2_add_rst_stream_to_next_write(
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) {
+grpc_error* grpc_chttp2_rst_stream_parser_begin_frame(
+ grpc_chttp2_rst_stream_parser* parser, uint32_t length, uint8_t flags) {
+ if (length != 4) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("invalid rst_stream: length=%d, flags=%02x", length,
flags)
.c_str());
- }
- parser->byte = 0;
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_chttp2_rst_stream_parser_parse(void* parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+ }
+ parser->byte = 0;
+ return GRPC_ERROR_NONE;
+}
+
+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;
- grpc_chttp2_rst_stream_parser* p =
- static_cast<grpc_chttp2_rst_stream_parser*>(parser);
-
- while (p->byte != 4 && cur != end) {
- p->reason_bytes[p->byte] = *cur;
- cur++;
- p->byte++;
- }
- s->stats.incoming.framing_bytes += static_cast<uint64_t>(end - cur);
-
- if (p->byte == 4) {
- GPR_ASSERT(is_last);
- uint32_t reason = ((static_cast<uint32_t>(p->reason_bytes[0])) << 24) |
- ((static_cast<uint32_t>(p->reason_bytes[1])) << 16) |
- ((static_cast<uint32_t>(p->reason_bytes[2])) << 8) |
- ((static_cast<uint32_t>(p->reason_bytes[3])));
- grpc_error* error = GRPC_ERROR_NONE;
- if (reason != GRPC_HTTP2_NO_ERROR || s->metadata_buffer[1].size == 0) {
- error = grpc_error_set_int(
+ grpc_chttp2_rst_stream_parser* p =
+ static_cast<grpc_chttp2_rst_stream_parser*>(parser);
+
+ while (p->byte != 4 && cur != end) {
+ p->reason_bytes[p->byte] = *cur;
+ cur++;
+ p->byte++;
+ }
+ s->stats.incoming.framing_bytes += static_cast<uint64_t>(end - cur);
+
+ if (p->byte == 4) {
+ GPR_ASSERT(is_last);
+ uint32_t reason = ((static_cast<uint32_t>(p->reason_bytes[0])) << 24) |
+ ((static_cast<uint32_t>(p->reason_bytes[1])) << 16) |
+ ((static_cast<uint32_t>(p->reason_bytes[2])) << 8) |
+ ((static_cast<uint32_t>(p->reason_bytes[3])));
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (reason != GRPC_HTTP2_NO_ERROR || s->metadata_buffer[1].size == 0) {
+ error = grpc_error_set_int(
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("RST_STREAM"),
GRPC_ERROR_STR_GRPC_MESSAGE,
grpc_slice_from_cpp_string(y_absl::StrCat(
"Received RST_STREAM with error code ", reason))),
- GRPC_ERROR_INT_HTTP2_ERROR, static_cast<intptr_t>(reason));
- }
- grpc_chttp2_mark_stream_closed(t, s, true, true, error);
- }
-
- return GRPC_ERROR_NONE;
-}
+ GRPC_ERROR_INT_HTTP2_ERROR, static_cast<intptr_t>(reason));
+ }
+ grpc_chttp2_mark_stream_closed(t, s, true, true, error);
+ }
+
+ return GRPC_ERROR_NONE;
+}
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 e324ee2cfc3..668c2a015c4 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_FRAME_RST_STREAM_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_RST_STREAM_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
#include "src/core/lib/transport/transport.h"
@@ -30,7 +30,7 @@ struct grpc_chttp2_rst_stream_parser {
uint8_t reason_bytes[4];
};
grpc_slice grpc_chttp2_rst_stream_create(uint32_t stream_id, uint32_t code,
- grpc_transport_one_way_stats* stats);
+ 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
@@ -39,11 +39,11 @@ 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,
+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);
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 9e9a838cc3b..9d9bcf50381 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
@@ -1,241 +1,241 @@
-/*
- *
- * 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/transport/chttp2/transport/frame_settings.h"
-#include "src/core/ext/transport/chttp2/transport/internal.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/transport/chttp2/transport/frame_settings.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/ext/transport/chttp2/transport/frame.h"
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/transport/http2_errors.h"
-
-static uint8_t* fill_header(uint8_t* out, uint32_t length, uint8_t flags) {
- *out++ = static_cast<uint8_t>(length >> 16);
- *out++ = static_cast<uint8_t>(length >> 8);
- *out++ = static_cast<uint8_t>(length);
- *out++ = GRPC_CHTTP2_FRAME_SETTINGS;
- *out++ = flags;
- *out++ = 0;
- *out++ = 0;
- *out++ = 0;
- *out++ = 0;
- return out;
-}
-
-grpc_slice grpc_chttp2_settings_create(uint32_t* old_settings,
- const uint32_t* new_settings,
- uint32_t force_mask, size_t count) {
- size_t i;
- uint32_t n = 0;
- grpc_slice output;
- uint8_t* p;
-
- for (i = 0; i < count; i++) {
- n += (new_settings[i] != old_settings[i] || (force_mask & (1u << i)) != 0);
- }
-
- output = GRPC_SLICE_MALLOC(9 + 6 * n);
- p = fill_header(GRPC_SLICE_START_PTR(output), 6 * n, 0);
-
- for (i = 0; i < count; i++) {
- if (new_settings[i] != old_settings[i] || (force_mask & (1u << i)) != 0) {
- *p++ = static_cast<uint8_t>(grpc_setting_id_to_wire_id[i] >> 8);
- *p++ = static_cast<uint8_t>(grpc_setting_id_to_wire_id[i]);
- *p++ = static_cast<uint8_t>(new_settings[i] >> 24);
- *p++ = static_cast<uint8_t>(new_settings[i] >> 16);
- *p++ = static_cast<uint8_t>(new_settings[i] >> 8);
- *p++ = static_cast<uint8_t>(new_settings[i]);
- old_settings[i] = new_settings[i];
- }
- }
-
- GPR_ASSERT(p == GRPC_SLICE_END_PTR(output));
-
- return output;
-}
-
-grpc_slice grpc_chttp2_settings_ack_create(void) {
- grpc_slice output = GRPC_SLICE_MALLOC(9);
- fill_header(GRPC_SLICE_START_PTR(output), 0, GRPC_CHTTP2_FLAG_ACK);
- return output;
-}
-
-grpc_error* grpc_chttp2_settings_parser_begin_frame(
- grpc_chttp2_settings_parser* parser, uint32_t length, uint8_t flags,
- uint32_t* settings) {
- parser->target_settings = settings;
- memcpy(parser->incoming_settings, settings,
- GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t));
- parser->is_ack = 0;
- parser->state = GRPC_CHTTP2_SPS_ID0;
- if (flags == GRPC_CHTTP2_FLAG_ACK) {
- parser->is_ack = 1;
- if (length != 0) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "non-empty settings ack frame received");
- }
- return GRPC_ERROR_NONE;
- } else if (flags != 0) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "invalid flags on settings frame");
- } else if (length % 6 != 0) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "settings frames must be a multiple of six bytes");
- } else {
- return GRPC_ERROR_NONE;
- }
-}
-
-grpc_error* grpc_chttp2_settings_parser_parse(void* p, grpc_chttp2_transport* t,
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
+#include "src/core/ext/transport/chttp2/transport/frame.h"
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/transport/http2_errors.h"
+
+static uint8_t* fill_header(uint8_t* out, uint32_t length, uint8_t flags) {
+ *out++ = static_cast<uint8_t>(length >> 16);
+ *out++ = static_cast<uint8_t>(length >> 8);
+ *out++ = static_cast<uint8_t>(length);
+ *out++ = GRPC_CHTTP2_FRAME_SETTINGS;
+ *out++ = flags;
+ *out++ = 0;
+ *out++ = 0;
+ *out++ = 0;
+ *out++ = 0;
+ return out;
+}
+
+grpc_slice grpc_chttp2_settings_create(uint32_t* old_settings,
+ const uint32_t* new_settings,
+ uint32_t force_mask, size_t count) {
+ size_t i;
+ uint32_t n = 0;
+ grpc_slice output;
+ uint8_t* p;
+
+ for (i = 0; i < count; i++) {
+ n += (new_settings[i] != old_settings[i] || (force_mask & (1u << i)) != 0);
+ }
+
+ output = GRPC_SLICE_MALLOC(9 + 6 * n);
+ p = fill_header(GRPC_SLICE_START_PTR(output), 6 * n, 0);
+
+ for (i = 0; i < count; i++) {
+ if (new_settings[i] != old_settings[i] || (force_mask & (1u << i)) != 0) {
+ *p++ = static_cast<uint8_t>(grpc_setting_id_to_wire_id[i] >> 8);
+ *p++ = static_cast<uint8_t>(grpc_setting_id_to_wire_id[i]);
+ *p++ = static_cast<uint8_t>(new_settings[i] >> 24);
+ *p++ = static_cast<uint8_t>(new_settings[i] >> 16);
+ *p++ = static_cast<uint8_t>(new_settings[i] >> 8);
+ *p++ = static_cast<uint8_t>(new_settings[i]);
+ old_settings[i] = new_settings[i];
+ }
+ }
+
+ GPR_ASSERT(p == GRPC_SLICE_END_PTR(output));
+
+ return output;
+}
+
+grpc_slice grpc_chttp2_settings_ack_create(void) {
+ grpc_slice output = GRPC_SLICE_MALLOC(9);
+ fill_header(GRPC_SLICE_START_PTR(output), 0, GRPC_CHTTP2_FLAG_ACK);
+ return output;
+}
+
+grpc_error* grpc_chttp2_settings_parser_begin_frame(
+ grpc_chttp2_settings_parser* parser, uint32_t length, uint8_t flags,
+ uint32_t* settings) {
+ parser->target_settings = settings;
+ memcpy(parser->incoming_settings, settings,
+ GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t));
+ parser->is_ack = 0;
+ parser->state = GRPC_CHTTP2_SPS_ID0;
+ if (flags == GRPC_CHTTP2_FLAG_ACK) {
+ parser->is_ack = 1;
+ if (length != 0) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "non-empty settings ack frame received");
+ }
+ return GRPC_ERROR_NONE;
+ } else if (flags != 0) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "invalid flags on settings frame");
+ } else if (length % 6 != 0) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "settings frames must be a multiple of six bytes");
+ } else {
+ return GRPC_ERROR_NONE;
+ }
+}
+
+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_settings_parser* parser =
- static_cast<grpc_chttp2_settings_parser*>(p);
- const uint8_t* cur = GRPC_SLICE_START_PTR(slice);
- const uint8_t* end = GRPC_SLICE_END_PTR(slice);
- grpc_chttp2_setting_id id;
-
- if (parser->is_ack) {
- return GRPC_ERROR_NONE;
- }
-
- for (;;) {
- switch (parser->state) {
- case GRPC_CHTTP2_SPS_ID0:
- if (cur == end) {
- parser->state = GRPC_CHTTP2_SPS_ID0;
- if (is_last) {
- memcpy(parser->target_settings, parser->incoming_settings,
- GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t));
+ grpc_chttp2_settings_parser* parser =
+ static_cast<grpc_chttp2_settings_parser*>(p);
+ const uint8_t* cur = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* end = GRPC_SLICE_END_PTR(slice);
+ grpc_chttp2_setting_id id;
+
+ if (parser->is_ack) {
+ return GRPC_ERROR_NONE;
+ }
+
+ for (;;) {
+ switch (parser->state) {
+ case GRPC_CHTTP2_SPS_ID0:
+ if (cur == end) {
+ parser->state = GRPC_CHTTP2_SPS_ID0;
+ if (is_last) {
+ memcpy(parser->target_settings, parser->incoming_settings,
+ GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t));
t->num_pending_induced_frames++;
- grpc_slice_buffer_add(&t->qbuf, grpc_chttp2_settings_ack_create());
- if (t->notify_on_receive_settings != nullptr) {
+ 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);
- t->notify_on_receive_settings = nullptr;
- }
- }
- return GRPC_ERROR_NONE;
- }
- parser->id = static_cast<uint16_t>((static_cast<uint16_t>(*cur)) << 8);
- cur++;
- /* fallthrough */
- case GRPC_CHTTP2_SPS_ID1:
- if (cur == end) {
- parser->state = GRPC_CHTTP2_SPS_ID1;
- return GRPC_ERROR_NONE;
- }
- parser->id = static_cast<uint16_t>(parser->id | (*cur));
- cur++;
- /* fallthrough */
- case GRPC_CHTTP2_SPS_VAL0:
- if (cur == end) {
- parser->state = GRPC_CHTTP2_SPS_VAL0;
- return GRPC_ERROR_NONE;
- }
- parser->value = (static_cast<uint32_t>(*cur)) << 24;
- cur++;
- /* fallthrough */
- case GRPC_CHTTP2_SPS_VAL1:
- if (cur == end) {
- parser->state = GRPC_CHTTP2_SPS_VAL1;
- return GRPC_ERROR_NONE;
- }
- parser->value |= (static_cast<uint32_t>(*cur)) << 16;
- cur++;
- /* fallthrough */
- case GRPC_CHTTP2_SPS_VAL2:
- if (cur == end) {
- parser->state = GRPC_CHTTP2_SPS_VAL2;
- return GRPC_ERROR_NONE;
- }
- parser->value |= (static_cast<uint32_t>(*cur)) << 8;
- cur++;
- /* fallthrough */
- case GRPC_CHTTP2_SPS_VAL3:
- if (cur == end) {
- parser->state = GRPC_CHTTP2_SPS_VAL3;
- return GRPC_ERROR_NONE;
- } else {
- parser->state = GRPC_CHTTP2_SPS_ID0;
- }
- parser->value |= *cur;
- cur++;
-
- if (grpc_wire_id_to_setting_id(parser->id, &id)) {
- const grpc_chttp2_setting_parameters* sp =
- &grpc_chttp2_settings_parameters[id];
- // If flow control is disabled we skip these.
- if (!t->flow_control->flow_control_enabled() &&
- (id == GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE ||
- id == GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE)) {
- continue;
- }
- if (parser->value < sp->min_value || parser->value > sp->max_value) {
- switch (sp->invalid_value_behavior) {
- case GRPC_CHTTP2_CLAMP_INVALID_VALUE:
- parser->value =
- GPR_CLAMP(parser->value, sp->min_value, sp->max_value);
- break;
- case GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE:
- grpc_chttp2_goaway_append(
- t->last_new_stream_id, sp->error_value,
- grpc_slice_from_static_string("HTTP2 settings error"),
- &t->qbuf);
+ t->notify_on_receive_settings = nullptr;
+ }
+ }
+ return GRPC_ERROR_NONE;
+ }
+ parser->id = static_cast<uint16_t>((static_cast<uint16_t>(*cur)) << 8);
+ cur++;
+ /* fallthrough */
+ case GRPC_CHTTP2_SPS_ID1:
+ if (cur == end) {
+ parser->state = GRPC_CHTTP2_SPS_ID1;
+ return GRPC_ERROR_NONE;
+ }
+ parser->id = static_cast<uint16_t>(parser->id | (*cur));
+ cur++;
+ /* fallthrough */
+ case GRPC_CHTTP2_SPS_VAL0:
+ if (cur == end) {
+ parser->state = GRPC_CHTTP2_SPS_VAL0;
+ return GRPC_ERROR_NONE;
+ }
+ parser->value = (static_cast<uint32_t>(*cur)) << 24;
+ cur++;
+ /* fallthrough */
+ case GRPC_CHTTP2_SPS_VAL1:
+ if (cur == end) {
+ parser->state = GRPC_CHTTP2_SPS_VAL1;
+ return GRPC_ERROR_NONE;
+ }
+ parser->value |= (static_cast<uint32_t>(*cur)) << 16;
+ cur++;
+ /* fallthrough */
+ case GRPC_CHTTP2_SPS_VAL2:
+ if (cur == end) {
+ parser->state = GRPC_CHTTP2_SPS_VAL2;
+ return GRPC_ERROR_NONE;
+ }
+ parser->value |= (static_cast<uint32_t>(*cur)) << 8;
+ cur++;
+ /* fallthrough */
+ case GRPC_CHTTP2_SPS_VAL3:
+ if (cur == end) {
+ parser->state = GRPC_CHTTP2_SPS_VAL3;
+ return GRPC_ERROR_NONE;
+ } else {
+ parser->state = GRPC_CHTTP2_SPS_ID0;
+ }
+ parser->value |= *cur;
+ cur++;
+
+ if (grpc_wire_id_to_setting_id(parser->id, &id)) {
+ const grpc_chttp2_setting_parameters* sp =
+ &grpc_chttp2_settings_parameters[id];
+ // If flow control is disabled we skip these.
+ if (!t->flow_control->flow_control_enabled() &&
+ (id == GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE ||
+ id == GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE)) {
+ continue;
+ }
+ if (parser->value < sp->min_value || parser->value > sp->max_value) {
+ switch (sp->invalid_value_behavior) {
+ case GRPC_CHTTP2_CLAMP_INVALID_VALUE:
+ parser->value =
+ GPR_CLAMP(parser->value, sp->min_value, sp->max_value);
+ break;
+ case GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE:
+ grpc_chttp2_goaway_append(
+ t->last_new_stream_id, sp->error_value,
+ grpc_slice_from_static_string("HTTP2 settings error"),
+ &t->qbuf);
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("invalid value %u passed for %s",
parser->value, sp->name)
.c_str());
- }
- }
- if (id == GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE &&
- parser->incoming_settings[id] != parser->value) {
- t->initial_window_update += static_cast<int64_t>(parser->value) -
- parser->incoming_settings[id];
+ }
+ }
+ if (id == GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE &&
+ 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)) {
- 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;
+ 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)) {
- gpr_log(GPR_INFO, "CHTTP2:%s:%s: got setting %s = %d",
+ 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)) {
- gpr_log(GPR_ERROR, "CHTTP2: Ignoring unknown setting %d (value %d)",
- parser->id, parser->value);
- }
- break;
- }
- }
-}
+ gpr_log(GPR_ERROR, "CHTTP2: Ignoring unknown setting %d (value %d)",
+ parser->id, parser->value);
+ }
+ break;
+ }
+ }
+}
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 181471401cd..808dd97d33a 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
@@ -1,29 +1,29 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_FRAME_SETTINGS_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_SETTINGS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
-#include "src/core/ext/transport/chttp2/transport/http2_settings.h"
+#include "src/core/ext/transport/chttp2/transport/http2_settings.h"
typedef enum {
GRPC_CHTTP2_SPS_ID0,
@@ -36,24 +36,24 @@ typedef enum {
struct grpc_chttp2_settings_parser {
grpc_chttp2_settings_parse_state state;
- uint32_t* target_settings;
+ uint32_t* target_settings;
uint8_t is_ack;
uint16_t id;
uint32_t value;
uint32_t incoming_settings[GRPC_CHTTP2_NUM_SETTINGS];
};
/* Create a settings frame by diffing old & new, and updating old to be new */
-grpc_slice grpc_chttp2_settings_create(uint32_t* old, const uint32_t* newval,
+grpc_slice grpc_chttp2_settings_create(uint32_t* old, const uint32_t* newval,
uint32_t force_mask, size_t count);
/* Create an ack settings frame */
grpc_slice grpc_chttp2_settings_ack_create(void);
-grpc_error* grpc_chttp2_settings_parser_begin_frame(
- grpc_chttp2_settings_parser* parser, uint32_t length, uint8_t flags,
- uint32_t* settings);
-grpc_error* grpc_chttp2_settings_parser_parse(void* parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+grpc_error* grpc_chttp2_settings_parser_begin_frame(
+ grpc_chttp2_settings_parser* parser, uint32_t length, uint8_t flags,
+ uint32_t* settings);
+grpc_error* grpc_chttp2_settings_parser_parse(void* parser,
+ grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
const grpc_slice& slice,
int is_last);
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 20efb09b0d3..f88e652041c 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
@@ -1,120 +1,120 @@
-/*
- *
- * 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/transport/chttp2/transport/frame_window_update.h"
-#include "src/core/ext/transport/chttp2/transport/internal.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/transport/chttp2/transport/frame_window_update.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-grpc_slice grpc_chttp2_window_update_create(
- uint32_t id, uint32_t window_update, grpc_transport_one_way_stats* stats) {
- static const size_t frame_size = 13;
- grpc_slice slice = GRPC_SLICE_MALLOC(frame_size);
- stats->header_bytes += frame_size;
- uint8_t* p = GRPC_SLICE_START_PTR(slice);
-
- GPR_ASSERT(window_update);
-
- *p++ = 0;
- *p++ = 0;
- *p++ = 4;
- *p++ = GRPC_CHTTP2_FRAME_WINDOW_UPDATE;
- *p++ = 0;
- *p++ = static_cast<uint8_t>(id >> 24);
- *p++ = static_cast<uint8_t>(id >> 16);
- *p++ = static_cast<uint8_t>(id >> 8);
- *p++ = static_cast<uint8_t>(id);
- *p++ = static_cast<uint8_t>(window_update >> 24);
- *p++ = static_cast<uint8_t>(window_update >> 16);
- *p++ = static_cast<uint8_t>(window_update >> 8);
- *p++ = static_cast<uint8_t>(window_update);
-
- return slice;
-}
-
-grpc_error* grpc_chttp2_window_update_parser_begin_frame(
- grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags) {
- if (flags || length != 4) {
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+grpc_slice grpc_chttp2_window_update_create(
+ uint32_t id, uint32_t window_update, grpc_transport_one_way_stats* stats) {
+ static const size_t frame_size = 13;
+ grpc_slice slice = GRPC_SLICE_MALLOC(frame_size);
+ stats->header_bytes += frame_size;
+ uint8_t* p = GRPC_SLICE_START_PTR(slice);
+
+ GPR_ASSERT(window_update);
+
+ *p++ = 0;
+ *p++ = 0;
+ *p++ = 4;
+ *p++ = GRPC_CHTTP2_FRAME_WINDOW_UPDATE;
+ *p++ = 0;
+ *p++ = static_cast<uint8_t>(id >> 24);
+ *p++ = static_cast<uint8_t>(id >> 16);
+ *p++ = static_cast<uint8_t>(id >> 8);
+ *p++ = static_cast<uint8_t>(id);
+ *p++ = static_cast<uint8_t>(window_update >> 24);
+ *p++ = static_cast<uint8_t>(window_update >> 16);
+ *p++ = static_cast<uint8_t>(window_update >> 8);
+ *p++ = static_cast<uint8_t>(window_update);
+
+ return slice;
+}
+
+grpc_error* grpc_chttp2_window_update_parser_begin_frame(
+ grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags) {
+ if (flags || length != 4) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("invalid window update: length=%d, flags=%02x", length,
flags)
.c_str());
- }
- parser->byte = 0;
- parser->amount = 0;
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_chttp2_window_update_parser_parse(void* parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+ }
+ parser->byte = 0;
+ parser->amount = 0;
+ return GRPC_ERROR_NONE;
+}
+
+grpc_error* grpc_chttp2_window_update_parser_parse(void* parser,
+ grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
const grpc_slice& slice,
- int is_last) {
+ 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_window_update_parser* p =
- static_cast<grpc_chttp2_window_update_parser*>(parser);
-
- while (p->byte != 4 && cur != end) {
- p->amount |= (static_cast<uint32_t>(*cur)) << (8 * (3 - p->byte));
- cur++;
- p->byte++;
- }
-
- if (s != nullptr) {
- s->stats.incoming.framing_bytes += static_cast<uint32_t>(end - cur);
- }
-
- if (p->byte == 4) {
+ grpc_chttp2_window_update_parser* p =
+ static_cast<grpc_chttp2_window_update_parser*>(parser);
+
+ while (p->byte != 4 && cur != end) {
+ p->amount |= (static_cast<uint32_t>(*cur)) << (8 * (3 - p->byte));
+ cur++;
+ p->byte++;
+ }
+
+ if (s != nullptr) {
+ s->stats.incoming.framing_bytes += static_cast<uint32_t>(end - cur);
+ }
+
+ if (p->byte == 4) {
// top bit is reserved and must be ignored.
uint32_t received_update = p->amount & 0x7fffffffu;
if (received_update == 0) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("invalid window update bytes: ", p->amount).c_str());
- }
- GPR_ASSERT(is_last);
-
- if (t->incoming_stream_id != 0) {
- if (s != nullptr) {
- s->flow_control->RecvUpdate(received_update);
- if (grpc_chttp2_list_remove_stalled_by_stream(t, s)) {
- grpc_chttp2_mark_stream_writable(t, s);
- grpc_chttp2_initiate_write(
- t, GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE);
- }
- }
- } else {
- bool was_zero = t->flow_control->remote_window() <= 0;
- t->flow_control->RecvUpdate(received_update);
- bool is_zero = t->flow_control->remote_window() <= 0;
- if (was_zero && !is_zero) {
- grpc_chttp2_initiate_write(
- t, GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED);
- }
- }
- }
-
- return GRPC_ERROR_NONE;
-}
+ }
+ GPR_ASSERT(is_last);
+
+ if (t->incoming_stream_id != 0) {
+ if (s != nullptr) {
+ s->flow_control->RecvUpdate(received_update);
+ if (grpc_chttp2_list_remove_stalled_by_stream(t, s)) {
+ grpc_chttp2_mark_stream_writable(t, s);
+ grpc_chttp2_initiate_write(
+ t, GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE);
+ }
+ }
+ } else {
+ bool was_zero = t->flow_control->remote_window() <= 0;
+ t->flow_control->RecvUpdate(received_update);
+ bool is_zero = t->flow_control->remote_window() <= 0;
+ if (was_zero && !is_zero) {
+ grpc_chttp2_initiate_write(
+ t, GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED);
+ }
+ }
+ }
+
+ return GRPC_ERROR_NONE;
+}
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 340445d87a4..42b63cd664e 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_FRAME_WINDOW_UPDATE_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_WINDOW_UPDATE_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
#include "src/core/lib/transport/transport.h"
@@ -31,14 +31,14 @@ struct grpc_chttp2_window_update_parser {
uint32_t amount;
};
grpc_slice grpc_chttp2_window_update_create(
- uint32_t id, uint32_t window_delta, grpc_transport_one_way_stats* stats);
+ uint32_t id, uint32_t window_delta, grpc_transport_one_way_stats* stats);
-grpc_error* grpc_chttp2_window_update_parser_begin_frame(
- grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags);
-grpc_error* grpc_chttp2_window_update_parser_parse(void* parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+grpc_error* grpc_chttp2_window_update_parser_begin_frame(
+ grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags);
+grpc_error* grpc_chttp2_window_update_parser_parse(void* parser,
+ grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
const grpc_slice& slice,
- int is_last);
+ 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 4ceaec24b3d..87ad8017b00 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/ext/transport/chttp2/transport/hpack_encoder.h"
-
-#include <assert.h>
-#include <string.h>
-
-/* This is here for grpc_is_binary_header
- * TODO(murgatroid99): Remove this
- */
-#include <grpc/grpc.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
-#include "src/core/ext/transport/chttp2/transport/hpack_table.h"
-#include "src/core/ext/transport/chttp2/transport/varint.h"
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.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/transport/chttp2/transport/hpack_encoder.h"
+
+#include <assert.h>
+#include <string.h>
+
+/* This is here for grpc_is_binary_header
+ * TODO(murgatroid99): Remove this
+ */
+#include <grpc/grpc.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
+#include "src/core/ext/transport/chttp2/transport/hpack_table.h"
+#include "src/core/ext/transport/chttp2/transport/varint.h"
+#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/transport/metadata.h"
-#include "src/core/lib/transport/static_metadata.h"
-#include "src/core/lib/transport/timeout_encoding.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.
@@ -64,14 +64,14 @@ namespace {
(((x) >> (GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS * 2)) & HASH_FRAGMENT_MASK)
#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;
-/* if the probability of this item being seen again is < 1/x then don't add
- it to the table */
+/* 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
@@ -81,7 +81,7 @@ constexpr uint8_t kMaxFilterValue = 255;
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; }
@@ -100,8 +100,8 @@ struct SliceRefComparator {
GPR_DEBUG_ASSERT(sref != nullptr);
sref->Unref();
}
-};
-
+};
+
struct MetadataComparator {
typedef grpc_mdelem Type;
static const grpc_mdelem Null() { return {0}; }
@@ -260,29 +260,29 @@ static bool CanAddToHashtable(grpc_chttp2_hpack_compressor* hpack_compressor,
} /* namespace */
struct framer_state {
- int is_first_frame;
- /* number of bytes in 'output' when we started the frame - used to calculate
- frame length */
- size_t output_length_at_start_of_frame;
- /* index (in output) of the header for the current frame */
- size_t header_idx;
+ int is_first_frame;
+ /* number of bytes in 'output' when we started the frame - used to calculate
+ frame length */
+ size_t output_length_at_start_of_frame;
+ /* index (in output) of the header for the current frame */
+ size_t header_idx;
#ifndef NDEBUG
- /* have we seen a regular (non-colon-prefixed) header yet? */
- uint8_t seen_regular_header;
+ /* have we seen a regular (non-colon-prefixed) header yet? */
+ uint8_t seen_regular_header;
#endif
- /* output stream id */
- uint32_t stream_id;
- grpc_slice_buffer* output;
- grpc_transport_one_way_stats* stats;
- /* maximum size of a frame */
- size_t max_frame_size;
- bool use_true_binary_metadata;
+ /* output stream id */
+ uint32_t stream_id;
+ grpc_slice_buffer* output;
+ grpc_transport_one_way_stats* stats;
+ /* maximum size of a frame */
+ size_t max_frame_size;
+ 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 */
-static void fill_header(uint8_t* p, uint8_t type, uint32_t id, size_t len,
- uint8_t flags) {
+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
@@ -296,17 +296,17 @@ static void fill_header(uint8_t* p, uint8_t type, uint32_t id, size_t len,
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);
- *p++ = type;
- *p++ = flags;
- *p++ = static_cast<uint8_t>(id >> 24);
- *p++ = static_cast<uint8_t>(id >> 16);
- *p++ = static_cast<uint8_t>(id >> 8);
- *p++ = static_cast<uint8_t>(id);
-}
-
+ *p++ = static_cast<uint8_t>(len >> 16);
+ *p++ = static_cast<uint8_t>(len >> 8);
+ *p++ = static_cast<uint8_t>(len);
+ *p++ = type;
+ *p++ = flags;
+ *p++ = static_cast<uint8_t>(id >> 24);
+ *p++ = static_cast<uint8_t>(id >> 16);
+ *p++ = static_cast<uint8_t>(id >> 8);
+ *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;
@@ -314,9 +314,9 @@ static size_t current_frame_size(framer_state* st) {
return frame_size;
}
-/* finish a frame - fill in the previously reserved header */
+/* finish a frame - fill in the previously reserved header */
static void finish_frame(framer_state* st, int is_header_boundary) {
- uint8_t type = 0xff;
+ uint8_t type = 0xff;
type =
static_cast<uint8_t>(st->is_first_frame ? GRPC_CHTTP2_FRAME_HEADER
: GRPC_CHTTP2_FRAME_CONTINUATION);
@@ -339,106 +339,106 @@ static void finish_frame(framer_state* st, int is_header_boundary) {
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->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) {
+ 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);
- st->output_length_at_start_of_frame = st->output->length;
-}
-
-/* make sure that the current frame is of the type desired, and has sufficient
- 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) {
+ st->output_length_at_start_of_frame = st->output->length;
+}
+
+/* make sure that the current frame is of the type desired, and has sufficient
+ 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)) {
- return;
- }
+ return;
+ }
finish_frame(st, 0);
- begin_frame(st);
-}
-
-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;
+ begin_frame(st);
+}
+
+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);
- if (len <= remaining) {
- st->stats->header_bytes += len;
- grpc_slice_buffer_add(st->output, slice);
- } else {
- st->stats->header_bytes += remaining;
- grpc_slice_buffer_add(st->output, grpc_slice_split_head(&slice, remaining));
+ if (len <= remaining) {
+ st->stats->header_bytes += len;
+ grpc_slice_buffer_add(st->output, slice);
+ } else {
+ st->stats->header_bytes += remaining;
+ grpc_slice_buffer_add(st->output, grpc_slice_split_head(&slice, remaining));
finish_frame(st, 0);
- begin_frame(st);
- add_header_data(st, slice);
- }
-}
-
-static uint8_t* add_tiny_header_data(framer_state* st, size_t len) {
- ensure_space(st, len);
- st->stats->header_bytes += len;
- return grpc_slice_buffer_tiny_add(st->output, len);
-}
-
-static void evict_entry(grpc_chttp2_hpack_compressor* c) {
- c->tail_remote_index++;
- GPR_ASSERT(c->tail_remote_index > 0);
- GPR_ASSERT(c->table_size >=
- c->table_elem_size[c->tail_remote_index % c->cap_table_elems]);
- GPR_ASSERT(c->table_elems > 0);
- c->table_size = static_cast<uint16_t>(
- c->table_size -
- c->table_elem_size[c->tail_remote_index % c->cap_table_elems]);
- c->table_elems--;
-}
-
-// Reserve space in table for the new element, evict entries if needed.
-// Return the new index of the element. Return 0 to indicate not adding to
-// table.
-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;
+ begin_frame(st);
+ add_header_data(st, slice);
+ }
+}
+
+static uint8_t* add_tiny_header_data(framer_state* st, size_t len) {
+ ensure_space(st, len);
+ st->stats->header_bytes += len;
+ return grpc_slice_buffer_tiny_add(st->output, len);
+}
+
+static void evict_entry(grpc_chttp2_hpack_compressor* c) {
+ c->tail_remote_index++;
+ GPR_ASSERT(c->tail_remote_index > 0);
+ GPR_ASSERT(c->table_size >=
+ c->table_elem_size[c->tail_remote_index % c->cap_table_elems]);
+ GPR_ASSERT(c->table_elems > 0);
+ c->table_size = static_cast<uint16_t>(
+ c->table_size -
+ c->table_elem_size[c->tail_remote_index % c->cap_table_elems]);
+ c->table_elems--;
+}
+
+// Reserve space in table for the new element, evict entries if needed.
+// Return the new index of the element. Return 0 to indicate not adding to
+// table.
+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);
-
+
// TODO(arjunroy): Re-examine semantics
- if (elem_size > c->max_table_size) {
- while (c->table_size > 0) {
- evict_entry(c);
- }
- return 0;
- }
-
- /* Reserve space for this element in the remote table: if this overflows
- the current table, drop elements until it fits, matching the decompressor
- algorithm */
- while (c->table_size + elem_size > c->max_table_size) {
- evict_entry(c);
- }
- GPR_ASSERT(c->table_elems < c->max_table_size);
- c->table_elem_size[new_index % c->cap_table_elems] =
- static_cast<uint16_t>(elem_size);
- c->table_size = static_cast<uint16_t>(c->table_size + elem_size);
- c->table_elems++;
-
- return new_index;
-}
-
-// Add a key to the dynamic table. Both key and value will be added to table at
-// the decoder.
+ if (elem_size > c->max_table_size) {
+ while (c->table_size > 0) {
+ evict_entry(c);
+ }
+ return 0;
+ }
+
+ /* Reserve space for this element in the remote table: if this overflows
+ the current table, drop elements until it fits, matching the decompressor
+ algorithm */
+ while (c->table_size + elem_size > c->max_table_size) {
+ evict_entry(c);
+ }
+ GPR_ASSERT(c->table_elems < c->max_table_size);
+ c->table_elem_size[new_index % c->cap_table_elems] =
+ static_cast<uint16_t>(elem_size);
+ c->table_size = static_cast<uint16_t>(c->table_size + elem_size);
+ c->table_elems++;
+
+ return new_index;
+}
+
+// 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);
-}
-
-/* add an element to the decoder table */
+}
+
+/* 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) {
@@ -446,32 +446,32 @@ static void AddElemWithIndex(grpc_chttp2_hpack_compressor* c, grpc_mdelem 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,
+}
+
+static void add_elem(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
size_t elem_size, uint32_t elem_hash, uint32_t key_hash) {
- uint32_t new_index = prepare_space_for_new_elem(c, elem_size);
+ 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);
}
-}
-
-static void add_key(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
+}
+
+static void add_key(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
size_t elem_size, uint32_t key_hash) {
- uint32_t new_index = prepare_space_for_new_elem(c, elem_size);
+ 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);
}
-}
-
+}
+
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);
-}
-
+ 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)
@@ -487,41 +487,41 @@ struct wire_value {
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) {
+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) {
- if (true_binary_enabled) {
- GRPC_STATS_INC_HPACK_SEND_BINARY();
+ if (true_binary_enabled) {
+ GRPC_STATS_INC_HPACK_SEND_BINARY();
return wire_value(0x00, true, grpc_slice_ref_internal(value));
- } else {
- GRPC_STATS_INC_HPACK_SEND_BINARY_BASE64();
+ } else {
+ GRPC_STATS_INC_HPACK_SEND_BINARY_BASE64();
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();
+ }
+ } 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) {
@@ -558,8 +558,8 @@ static void emit_lithdr(grpc_chttp2_hpack_compressor* /*c*/, uint32_t key_index,
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) {
@@ -571,7 +571,7 @@ static void emit_lithdr_v(grpc_chttp2_hpack_compressor* /*c*/, grpc_mdelem elem,
GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V();
break;
}
- GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED();
+ 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 =
@@ -586,7 +586,7 @@ static void emit_lithdr_v(grpc_chttp2_hpack_compressor* /*c*/, grpc_mdelem elem,
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)));
+ 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,
@@ -595,16 +595,16 @@ static void emit_lithdr_v(grpc_chttp2_hpack_compressor* /*c*/, grpc_mdelem elem,
value_buf[len_val_len] = 0;
}
add_header_data(st, value.data);
-}
-
-static void emit_advertise_table_size_change(grpc_chttp2_hpack_compressor* c,
- framer_state* st) {
- uint32_t len = GRPC_CHTTP2_VARINT_LENGTH(c->max_table_size, 3);
- GRPC_CHTTP2_WRITE_VARINT(c->max_table_size, 3, 0x20,
- add_tiny_header_data(st, len), len);
- c->advertise_table_size_change = 0;
-}
-
+}
+
+static void emit_advertise_table_size_change(grpc_chttp2_hpack_compressor* c,
+ framer_state* st) {
+ uint32_t len = GRPC_CHTTP2_VARINT_LENGTH(c->max_table_size, 3);
+ GRPC_CHTTP2_WRITE_VARINT(c->max_table_size, 3, 0x20,
+ add_tiny_header_data(st, len), len);
+ 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;
@@ -623,11 +623,11 @@ static void GPR_ATTRIBUTE_NOINLINE hpack_enc_log(grpc_mdelem elem) {
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;
-}
-
+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)
@@ -674,9 +674,9 @@ static void emit_maybe_add(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
}
}
-/* encode an mdelem */
-static void hpack_enc(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
- framer_state* 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);
@@ -686,30 +686,30 @@ static void hpack_enc(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
* 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 {
+ st->seen_regular_header = 1;
+ } else {
GPR_DEBUG_ASSERT(
- st->seen_regular_header == 0 &&
- "Reserved header (colon-prefixed) happening after regular ones.");
- }
+ 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);
- }
+ }
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) {
+ if (!key_interned) {
emit_lithdr_v<EmitLitHdrVType::NO_IDX_V>(c, elem, st);
- return;
- }
+ 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? */
+ }
+ /* 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 =
@@ -717,17 +717,17 @@ static void hpack_enc(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
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? */
+ /* 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) &&
- indices_key > c->tail_remote_index) {
+ indices_key > c->tail_remote_index) {
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 */
+ return;
+ }
+ /* no elem, key in the table... fall back to literal emission */
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);
@@ -739,131 +739,131 @@ static void hpack_enc(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem,
} else if (should_add_key) {
add_key(c, elem, decoder_space_usage, key_hash);
}
-}
-
-#define STRLEN_LIT(x) (sizeof(x) - 1)
-#define TIMEOUT_KEY "grpc-timeout"
-
-static void deadline_enc(grpc_chttp2_hpack_compressor* c, grpc_millis deadline,
- framer_state* st) {
- char timeout_str[GRPC_HTTP2_TIMEOUT_ENCODE_MIN_BUFSIZE];
- grpc_mdelem mdelem;
- grpc_http2_encode_timeout(deadline - grpc_core::ExecCtx::Get()->Now(),
- timeout_str);
+}
+
+#define STRLEN_LIT(x) (sizeof(x) - 1)
+#define TIMEOUT_KEY "grpc-timeout"
+
+static void deadline_enc(grpc_chttp2_hpack_compressor* c, grpc_millis deadline,
+ framer_state* st) {
+ char timeout_str[GRPC_HTTP2_TIMEOUT_ENCODE_MIN_BUFSIZE];
+ 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));
- hpack_enc(c, mdelem, st);
- GRPC_MDELEM_UNREF(mdelem);
-}
-
-static uint32_t elems_for_bytes(uint32_t bytes) { return (bytes + 31) / 32; }
-
-void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor* c) {
- memset(c, 0, sizeof(*c));
- c->max_table_size = GRPC_CHTTP2_HPACKC_INITIAL_TABLE_SIZE;
- 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;
+ hpack_enc(c, mdelem, st);
+ GRPC_MDELEM_UNREF(mdelem);
+}
+
+static uint32_t elems_for_bytes(uint32_t bytes) { return (bytes + 31) / 32; }
+
+void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor* c) {
+ memset(c, 0, sizeof(*c));
+ c->max_table_size = GRPC_CHTTP2_HPACKC_INITIAL_TABLE_SIZE;
+ 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);
-}
-
-void grpc_chttp2_hpack_compressor_destroy(grpc_chttp2_hpack_compressor* c) {
+}
+
+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();
- }
+ }
GRPC_MDELEM_UNREF(GetEntry<grpc_mdelem>(c->elem_table.entries, i));
- }
- gpr_free(c->table_elem_size);
-}
-
-void grpc_chttp2_hpack_compressor_set_max_usable_size(
- grpc_chttp2_hpack_compressor* c, uint32_t max_table_size) {
- c->max_usable_size = max_table_size;
- grpc_chttp2_hpack_compressor_set_max_table_size(
- c, GPR_MIN(c->max_table_size, max_table_size));
-}
-
-static void rebuild_elems(grpc_chttp2_hpack_compressor* c, uint32_t new_cap) {
- uint16_t* table_elem_size =
- static_cast<uint16_t*>(gpr_malloc(sizeof(*table_elem_size) * new_cap));
- uint32_t i;
-
- memset(table_elem_size, 0, sizeof(*table_elem_size) * new_cap);
- GPR_ASSERT(c->table_elems <= new_cap);
-
- for (i = 0; i < c->table_elems; i++) {
- uint32_t ofs = c->tail_remote_index + i + 1;
- table_elem_size[ofs % new_cap] =
- c->table_elem_size[ofs % c->cap_table_elems];
- }
-
- c->cap_table_elems = new_cap;
- gpr_free(c->table_elem_size);
- c->table_elem_size = table_elem_size;
-}
-
-void grpc_chttp2_hpack_compressor_set_max_table_size(
- grpc_chttp2_hpack_compressor* c, uint32_t max_table_size) {
- max_table_size = GPR_MIN(max_table_size, c->max_usable_size);
- if (max_table_size == c->max_table_size) {
- return;
- }
- while (c->table_size > 0 && c->table_size > max_table_size) {
- evict_entry(c);
- }
- c->max_table_size = max_table_size;
- c->max_table_elems = elems_for_bytes(max_table_size);
- if (c->max_table_elems > c->cap_table_elems) {
- rebuild_elems(c, GPR_MAX(c->max_table_elems, 2 * c->cap_table_elems));
- } else if (c->max_table_elems < c->cap_table_elems / 3) {
- uint32_t new_cap = GPR_MAX(c->max_table_elems, 16);
- if (new_cap != c->cap_table_elems) {
- rebuild_elems(c, new_cap);
- }
- }
- c->advertise_table_size_change = 1;
+ }
+ gpr_free(c->table_elem_size);
+}
+
+void grpc_chttp2_hpack_compressor_set_max_usable_size(
+ grpc_chttp2_hpack_compressor* c, uint32_t max_table_size) {
+ c->max_usable_size = max_table_size;
+ grpc_chttp2_hpack_compressor_set_max_table_size(
+ c, GPR_MIN(c->max_table_size, max_table_size));
+}
+
+static void rebuild_elems(grpc_chttp2_hpack_compressor* c, uint32_t new_cap) {
+ uint16_t* table_elem_size =
+ static_cast<uint16_t*>(gpr_malloc(sizeof(*table_elem_size) * new_cap));
+ uint32_t i;
+
+ memset(table_elem_size, 0, sizeof(*table_elem_size) * new_cap);
+ GPR_ASSERT(c->table_elems <= new_cap);
+
+ for (i = 0; i < c->table_elems; i++) {
+ uint32_t ofs = c->tail_remote_index + i + 1;
+ table_elem_size[ofs % new_cap] =
+ c->table_elem_size[ofs % c->cap_table_elems];
+ }
+
+ c->cap_table_elems = new_cap;
+ gpr_free(c->table_elem_size);
+ c->table_elem_size = table_elem_size;
+}
+
+void grpc_chttp2_hpack_compressor_set_max_table_size(
+ grpc_chttp2_hpack_compressor* c, uint32_t max_table_size) {
+ max_table_size = GPR_MIN(max_table_size, c->max_usable_size);
+ if (max_table_size == c->max_table_size) {
+ return;
+ }
+ while (c->table_size > 0 && c->table_size > max_table_size) {
+ evict_entry(c);
+ }
+ c->max_table_size = max_table_size;
+ c->max_table_elems = elems_for_bytes(max_table_size);
+ if (c->max_table_elems > c->cap_table_elems) {
+ rebuild_elems(c, GPR_MAX(c->max_table_elems, 2 * c->cap_table_elems));
+ } else if (c->max_table_elems < c->cap_table_elems / 3) {
+ uint32_t new_cap = GPR_MAX(c->max_table_elems, 16);
+ if (new_cap != c->cap_table_elems) {
+ rebuild_elems(c, new_cap);
+ }
+ }
+ c->advertise_table_size_change = 1;
if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
- gpr_log(GPR_INFO, "set max table size from encoder to %d", max_table_size);
- }
-}
-
-void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
- grpc_mdelem** extra_headers,
- size_t extra_headers_size,
- grpc_metadata_batch* metadata,
- const grpc_encode_header_options* options,
- grpc_slice_buffer* outbuf) {
+ gpr_log(GPR_INFO, "set max table size from encoder to %d", max_table_size);
+ }
+}
+
+void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
+ grpc_mdelem** extra_headers,
+ size_t extra_headers_size,
+ 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);
- framer_state st;
+ framer_state st;
#ifndef NDEBUG
- st.seen_regular_header = 0;
+ st.seen_regular_header = 0;
#endif
- st.stream_id = options->stream_id;
- st.output = outbuf;
- st.is_first_frame = 1;
- st.stats = options->stats;
- st.max_frame_size = options->max_frame_size;
- st.use_true_binary_metadata = options->use_true_binary_metadata;
+ st.stream_id = options->stream_id;
+ st.output = outbuf;
+ st.is_first_frame = 1;
+ st.stats = options->stats;
+ st.max_frame_size = options->max_frame_size;
+ st.use_true_binary_metadata = options->use_true_binary_metadata;
st.is_end_of_stream = options->is_eof;
-
- /* Encode a metadata batch; store the returned values, representing
- a metadata element that needs to be unreffed back into the metadata
- slot. THIS MAY NOT BE THE SAME ELEMENT (if a decoder table slot got
- updated). After this loop, we'll do a batch unref of elements. */
- begin_frame(&st);
- if (c->advertise_table_size_change != 0) {
- emit_advertise_table_size_change(c, &st);
- }
- for (size_t i = 0; i < extra_headers_size; ++i) {
+
+ /* Encode a metadata batch; store the returned values, representing
+ a metadata element that needs to be unreffed back into the metadata
+ slot. THIS MAY NOT BE THE SAME ELEMENT (if a decoder table slot got
+ updated). After this loop, we'll do a batch unref of elements. */
+ begin_frame(&st);
+ if (c->advertise_table_size_change != 0) {
+ emit_advertise_table_size_change(c, &st);
+ }
+ 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;
@@ -876,9 +876,9 @@ void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
} else {
hpack_enc(c, md, &st);
}
- }
- grpc_metadata_batch_assert_ok(metadata);
- for (grpc_linked_mdelem* l = metadata->list.head; l; l = l->next) {
+ }
+ 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;
@@ -890,11 +890,11 @@ void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
} else {
hpack_enc(c, l->md, &st);
}
- }
- grpc_millis deadline = metadata->deadline;
- if (deadline != GRPC_MILLIS_INF_FUTURE) {
- deadline_enc(c, deadline, &st);
- }
-
+ }
+ grpc_millis deadline = metadata->deadline;
+ if (deadline != GRPC_MILLIS_INF_FUTURE) {
+ deadline_enc(c, deadline, &st);
+ }
+
finish_frame(&st, 1);
-}
+}
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 5093f80ae2b..97c085fba2f 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_HPACK_ENCODER_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_ENCODER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include <grpc/slice_buffer.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
@@ -36,8 +36,8 @@
/* maximum table size we'll actually use */
#define GRPC_CHTTP2_HPACKC_MAX_TABLE_SIZE (1024 * 1024)
-extern grpc_core::TraceFlag grpc_http_trace;
-
+extern grpc_core::TraceFlag grpc_http_trace;
+
struct grpc_chttp2_hpack_compressor {
uint32_t max_table_size;
uint32_t max_table_elems;
@@ -83,25 +83,25 @@ struct grpc_chttp2_hpack_compressor {
} 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);
+void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor* c);
+void grpc_chttp2_hpack_compressor_destroy(grpc_chttp2_hpack_compressor* c);
void grpc_chttp2_hpack_compressor_set_max_table_size(
- grpc_chttp2_hpack_compressor* c, uint32_t max_table_size);
+ grpc_chttp2_hpack_compressor* c, uint32_t max_table_size);
void grpc_chttp2_hpack_compressor_set_max_usable_size(
- grpc_chttp2_hpack_compressor* c, uint32_t max_table_size);
+ grpc_chttp2_hpack_compressor* c, uint32_t max_table_size);
struct grpc_encode_header_options {
- uint32_t stream_id;
- bool is_eof;
- bool use_true_binary_metadata;
- size_t max_frame_size;
- grpc_transport_one_way_stats* stats;
+ uint32_t stream_id;
+ bool is_eof;
+ bool use_true_binary_metadata;
+ size_t max_frame_size;
+ grpc_transport_one_way_stats* stats;
};
-void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
- grpc_mdelem** extra_headers,
- size_t extra_headers_size,
- grpc_metadata_batch* metadata,
- const grpc_encode_header_options* options,
- grpc_slice_buffer* outbuf);
-
+void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c,
+ grpc_mdelem** extra_headers,
+ size_t extra_headers_size,
+ grpc_metadata_batch* metadata,
+ const grpc_encode_header_options* options,
+ grpc_slice_buffer* outbuf);
+
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_ENCODER_H */
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 a325439ad59..840401d98cd 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
@@ -1,632 +1,632 @@
-/*
- *
- * 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/transport/chttp2/transport/hpack_parser.h"
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-
-#include <assert.h>
-#include <stddef.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/transport/chttp2/transport/hpack_parser.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
+#include <assert.h>
+#include <stddef.h>
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gpr/string.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 <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gpr/string.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/validate_metadata.h"
-#include "src/core/lib/transport/http2_errors.h"
-
+#include "src/core/lib/transport/http2_errors.h"
+
grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_hpack_parser(
false, "chttp2_hpack_parser");
-typedef enum {
- NOT_BINARY,
- BINARY_BEGIN,
- B64_BYTE0,
- B64_BYTE1,
- B64_BYTE2,
- B64_BYTE3
-} binary_state;
-
-/* How parsing works:
-
- The parser object keeps track of a function pointer which represents the
- current parse state.
-
- Each time new bytes are presented, we call into the current state, which
- recursively parses until all bytes in the given chunk are exhausted.
-
- The parse state that terminates then saves its function pointer to be the
- current state so that it can resume when more bytes are available.
-
- It's expected that most optimizing compilers will turn this code into
- a set of indirect jumps, and so not waste stack space. */
-
-/* forward declarations for parsing states */
-static grpc_error* parse_begin(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_error(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end, grpc_error* error);
-static grpc_error* still_parse_error(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_illegal_op(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-
-static grpc_error* parse_string_prefix(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_key_string(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_value_string_with_indexed_key(
- grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_value_string_with_literal_key(
- grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end);
-
-static grpc_error* parse_value0(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_value1(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_value2(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_value3(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_value4(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_value5up(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-
-static grpc_error* parse_indexed_field(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_indexed_field_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_lithdr_incidx(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_lithdr_incidx_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_lithdr_incidx_v(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_lithdr_notidx(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_lithdr_notidx_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_lithdr_notidx_v(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_lithdr_nvridx(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_lithdr_nvridx_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_lithdr_nvridx_v(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end);
-static grpc_error* parse_max_tbl_size(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-static grpc_error* parse_max_tbl_size_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end);
-
-/* we translate the first byte of a hpack field into one of these decoding
- cases, then use a lookup table to jump directly to the appropriate parser.
-
- _X => the integer index is all ones, meaning we need to do varint decoding
- _V => the integer index is all zeros, meaning we need to decode an additional
- string value */
-typedef enum {
- INDEXED_FIELD,
- INDEXED_FIELD_X,
- LITHDR_INCIDX,
- LITHDR_INCIDX_X,
- LITHDR_INCIDX_V,
- LITHDR_NOTIDX,
- LITHDR_NOTIDX_X,
- LITHDR_NOTIDX_V,
- LITHDR_NVRIDX,
- LITHDR_NVRIDX_X,
- LITHDR_NVRIDX_V,
- MAX_TBL_SIZE,
- MAX_TBL_SIZE_X,
- ILLEGAL
-} first_byte_type;
-
-/* jump table of parse state functions -- order must match first_byte_type
- above */
-static const grpc_chttp2_hpack_parser_state first_byte_action[] = {
- parse_indexed_field, parse_indexed_field_x, parse_lithdr_incidx,
- parse_lithdr_incidx_x, parse_lithdr_incidx_v, parse_lithdr_notidx,
- parse_lithdr_notidx_x, parse_lithdr_notidx_v, parse_lithdr_nvridx,
- parse_lithdr_nvridx_x, parse_lithdr_nvridx_v, parse_max_tbl_size,
- parse_max_tbl_size_x, parse_illegal_op};
-
-/* indexes the first byte to a parse state function - generated by
- gen_hpack_tables.c */
-static const uint8_t first_byte_lut[256] = {
- LITHDR_NOTIDX_V, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX,
- LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX,
- LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX,
- LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX_X,
- LITHDR_NVRIDX_V, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX,
- LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX,
- LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX,
- LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX_X,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
- MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE_X,
- LITHDR_INCIDX_V, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
- LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX_X,
- ILLEGAL, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
- INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD_X,
-};
-
-/* state table for huffman decoding: given a state, gives an index/16 into
- next_sub_tbl. Taking that index and adding the value of the nibble being
- considered returns the next state.
-
- generated by gen_hpack_tables.c */
-static const uint8_t next_tbl[256] = {
- 0, 1, 2, 3, 4, 1, 2, 5, 6, 1, 7, 8, 1, 3, 3, 9, 10, 11, 1, 1,
- 1, 12, 1, 2, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
- 14, 1, 15, 16, 1, 17, 1, 15, 2, 7, 3, 18, 19, 1, 1, 1, 1, 20, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 15, 2, 2, 7, 21, 1, 22, 1, 1, 1, 1, 1,
- 1, 1, 1, 15, 2, 2, 2, 2, 2, 2, 23, 24, 25, 1, 1, 1, 1, 2, 2, 2,
- 26, 3, 3, 27, 10, 28, 1, 1, 1, 1, 1, 1, 2, 3, 29, 10, 30, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 31, 1, 1, 1, 1, 1, 1, 1, 2,
- 2, 2, 2, 2, 2, 2, 2, 32, 1, 1, 15, 33, 1, 34, 35, 9, 36, 1, 1, 1,
- 1, 1, 1, 1, 37, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 26, 9,
- 38, 1, 1, 1, 1, 1, 1, 1, 15, 2, 2, 2, 2, 26, 3, 3, 39, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 7, 3, 3, 3, 40, 2,
- 41, 1, 1, 1, 42, 43, 1, 1, 44, 1, 1, 1, 1, 15, 2, 2, 2, 2, 2, 2,
- 3, 3, 3, 45, 46, 1, 1, 2, 2, 2, 35, 3, 3, 18, 47, 2,
-};
-
-/* next state, based upon current state and the current nibble: see above.
- generated by gen_hpack_tables.c */
-static const int16_t next_sub_tbl[48 * 16] = {
- 1, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217,
- 218, 2, 6, 10, 13, 14, 15, 16, 17, 2, 6, 10, 13, 14, 15,
- 16, 17, 3, 7, 11, 24, 3, 7, 11, 24, 3, 7, 11, 24, 3,
- 7, 11, 24, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8,
- 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
- 199, 200, 201, 202, 203, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 9, 133, 134, 135, 136, 137, 138, 139, 140,
- 141, 142, 143, 144, 145, 146, 147, 3, 7, 11, 24, 3, 7, 11, 24,
- 4, 8, 4, 8, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 12, 132, 4, 8, 4, 8, 4, 8,
- 4, 8, 4, 8, 4, 8, 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, 18, 19, 20, 21, 4, 8, 4,
- 8, 4, 8, 4, 8, 4, 8, 0, 0, 0, 22, 23, 91, 25, 26,
- 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 3,
- 7, 11, 24, 3, 7, 11, 24, 0, 0, 0, 0, 0, 41, 42, 43,
- 2, 6, 10, 13, 14, 15, 16, 17, 3, 7, 11, 24, 3, 7, 11,
- 24, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 0, 0,
- 44, 45, 2, 6, 10, 13, 14, 15, 16, 17, 46, 47, 48, 49, 50,
- 51, 52, 57, 4, 8, 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, 53, 54, 55, 56, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
- 68, 69, 70, 71, 72, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 73, 75, 76, 77, 78, 79, 80, 81, 82,
- 83, 84, 85, 86, 87, 88, 89, 90, 3, 7, 11, 24, 3, 7, 11,
- 24, 3, 7, 11, 24, 0, 0, 0, 0, 3, 7, 11, 24, 3, 7,
- 11, 24, 4, 8, 4, 8, 0, 0, 0, 92, 0, 0, 0, 93, 94,
- 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 3, 7, 11, 24,
- 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4,
- 8, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 4,
- 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 0, 0,
- 0, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
- 131, 2, 6, 10, 13, 14, 15, 16, 17, 4, 8, 4, 8, 4, 8,
- 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 148,
- 149, 150, 151, 3, 7, 11, 24, 4, 8, 4, 8, 0, 0, 0, 0,
- 0, 0, 152, 153, 3, 7, 11, 24, 3, 7, 11, 24, 3, 7, 11,
- 24, 154, 155, 156, 164, 3, 7, 11, 24, 3, 7, 11, 24, 3, 7,
- 11, 24, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 157, 158, 159, 160, 161, 162, 163, 165, 166, 167, 168, 169, 170, 171, 172,
- 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187,
- 188, 189, 190, 191, 192, 193, 194, 195, 196, 4, 8, 4, 8, 4, 8,
- 4, 8, 4, 8, 4, 8, 4, 8, 197, 198, 4, 8, 4, 8, 4,
- 8, 4, 8, 0, 0, 0, 0, 0, 0, 219, 220, 3, 7, 11, 24,
- 4, 8, 4, 8, 4, 8, 0, 0, 221, 222, 223, 224, 3, 7, 11,
- 24, 3, 7, 11, 24, 4, 8, 4, 8, 4, 8, 225, 228, 4, 8,
- 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 226, 227, 229,
- 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244,
- 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 245, 246, 247, 248, 249, 250, 251, 252,
- 253, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 255,
-};
-
-/* emission table: indexed like next_tbl, ultimately gives the byte to be
- emitted, or -1 for no byte, or 256 for end of stream
-
- generated by gen_hpack_tables.c */
-static const uint16_t emit_tbl[256] = {
- 0, 1, 2, 3, 4, 5, 6, 7, 0, 8, 9, 10, 11, 12, 13,
- 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 23, 24, 25, 26, 27,
- 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 0, 55, 56,
- 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 0,
- 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,
- 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
- 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
- 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
- 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,
- 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 0,
- 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
- 0, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188,
- 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203,
- 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
- 219, 220, 221, 0, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,
- 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
- 248,
-};
-
-/* generated by gen_hpack_tables.c */
-static const int16_t emit_sub_tbl[249 * 16] = {
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, 49, 49,
- 49, 49, 48, 48, 48, 48, 49, 49, 49, 49, 50, 50, 50, 50, 97,
- 97, 97, 97, 48, 48, 49, 49, 50, 50, 97, 97, 99, 99, 101, 101,
- 105, 105, 111, 111, 48, 49, 50, 97, 99, 101, 105, 111, 115, 116, -1,
- -1, -1, -1, -1, -1, 32, 32, 32, 32, 32, 32, 32, 32, 37, 37,
- 37, 37, 37, 37, 37, 37, 99, 99, 99, 99, 101, 101, 101, 101, 105,
- 105, 105, 105, 111, 111, 111, 111, 115, 115, 116, 116, 32, 37, 45, 46,
- 47, 51, 52, 53, 54, 55, 56, 57, 61, 61, 61, 61, 61, 61, 61,
- 61, 65, 65, 65, 65, 65, 65, 65, 65, 115, 115, 115, 115, 116, 116,
- 116, 116, 32, 32, 37, 37, 45, 45, 46, 46, 61, 65, 95, 98, 100,
- 102, 103, 104, 108, 109, 110, 112, 114, 117, -1, -1, 58, 58, 58, 58,
- 58, 58, 58, 58, 66, 66, 66, 66, 66, 66, 66, 66, 47, 47, 51,
- 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 61, 61,
- 65, 65, 95, 95, 98, 98, 100, 100, 102, 102, 103, 103, 104, 104, 108,
- 108, 109, 109, 110, 110, 112, 112, 114, 114, 117, 117, 58, 66, 67, 68,
- 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
- 84, 85, 86, 87, 89, 106, 107, 113, 118, 119, 120, 121, 122, -1, -1,
- -1, -1, 38, 38, 38, 38, 38, 38, 38, 38, 42, 42, 42, 42, 42,
- 42, 42, 42, 44, 44, 44, 44, 44, 44, 44, 44, 59, 59, 59, 59,
- 59, 59, 59, 59, 88, 88, 88, 88, 88, 88, 88, 88, 90, 90, 90,
- 90, 90, 90, 90, 90, 33, 33, 34, 34, 40, 40, 41, 41, 63, 63,
- 39, 43, 124, -1, -1, -1, 35, 35, 35, 35, 35, 35, 35, 35, 62,
- 62, 62, 62, 62, 62, 62, 62, 0, 0, 0, 0, 36, 36, 36, 36,
- 64, 64, 64, 64, 91, 91, 91, 91, 69, 69, 69, 69, 69, 69, 69,
- 69, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71,
- 71, 71, 72, 72, 72, 72, 72, 72, 72, 72, 73, 73, 73, 73, 73,
- 73, 73, 73, 74, 74, 74, 74, 74, 74, 74, 74, 75, 75, 75, 75,
- 75, 75, 75, 75, 76, 76, 76, 76, 76, 76, 76, 76, 77, 77, 77,
- 77, 77, 77, 77, 77, 78, 78, 78, 78, 78, 78, 78, 78, 79, 79,
- 79, 79, 79, 79, 79, 79, 80, 80, 80, 80, 80, 80, 80, 80, 81,
- 81, 81, 81, 81, 81, 81, 81, 82, 82, 82, 82, 82, 82, 82, 82,
- 83, 83, 83, 83, 83, 83, 83, 83, 84, 84, 84, 84, 84, 84, 84,
- 84, 85, 85, 85, 85, 85, 85, 85, 85, 86, 86, 86, 86, 86, 86,
- 86, 86, 87, 87, 87, 87, 87, 87, 87, 87, 89, 89, 89, 89, 89,
- 89, 89, 89, 106, 106, 106, 106, 106, 106, 106, 106, 107, 107, 107, 107,
- 107, 107, 107, 107, 113, 113, 113, 113, 113, 113, 113, 113, 118, 118, 118,
- 118, 118, 118, 118, 118, 119, 119, 119, 119, 119, 119, 119, 119, 120, 120,
- 120, 120, 120, 120, 120, 120, 121, 121, 121, 121, 121, 121, 121, 121, 122,
- 122, 122, 122, 122, 122, 122, 122, 38, 38, 38, 38, 42, 42, 42, 42,
- 44, 44, 44, 44, 59, 59, 59, 59, 88, 88, 88, 88, 90, 90, 90,
- 90, 33, 34, 40, 41, 63, -1, -1, -1, 39, 39, 39, 39, 39, 39,
- 39, 39, 43, 43, 43, 43, 43, 43, 43, 43, 124, 124, 124, 124, 124,
- 124, 124, 124, 35, 35, 35, 35, 62, 62, 62, 62, 0, 0, 36, 36,
- 64, 64, 91, 91, 93, 93, 126, 126, 94, 125, -1, -1, 60, 60, 60,
- 60, 60, 60, 60, 60, 96, 96, 96, 96, 96, 96, 96, 96, 123, 123,
- 123, 123, 123, 123, 123, 123, -1, -1, -1, -1, -1, -1, -1, -1, 92,
- 92, 92, 92, 92, 92, 92, 92, 195, 195, 195, 195, 195, 195, 195, 195,
- 208, 208, 208, 208, 208, 208, 208, 208, 128, 128, 128, 128, 130, 130, 130,
- 130, 131, 131, 131, 131, 162, 162, 162, 162, 184, 184, 184, 184, 194, 194,
- 194, 194, 224, 224, 224, 224, 226, 226, 226, 226, 153, 153, 161, 161, 167,
- 167, 172, 172, 176, 176, 177, 177, 179, 179, 209, 209, 216, 216, 217, 217,
- 227, 227, 229, 229, 230, 230, 129, 132, 133, 134, 136, 146, 154, 156, 160,
- 163, 164, 169, 170, 173, 178, 181, 185, 186, 187, 189, 190, 196, 198, 228,
- 232, 233, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 135,
- 135, 135, 135, 135, 135, 135, 135, 137, 137, 137, 137, 137, 137, 137, 137,
- 138, 138, 138, 138, 138, 138, 138, 138, 139, 139, 139, 139, 139, 139, 139,
- 139, 140, 140, 140, 140, 140, 140, 140, 140, 141, 141, 141, 141, 141, 141,
- 141, 141, 143, 143, 143, 143, 143, 143, 143, 143, 147, 147, 147, 147, 147,
- 147, 147, 147, 149, 149, 149, 149, 149, 149, 149, 149, 150, 150, 150, 150,
- 150, 150, 150, 150, 151, 151, 151, 151, 151, 151, 151, 151, 152, 152, 152,
- 152, 152, 152, 152, 152, 155, 155, 155, 155, 155, 155, 155, 155, 157, 157,
- 157, 157, 157, 157, 157, 157, 158, 158, 158, 158, 158, 158, 158, 158, 165,
- 165, 165, 165, 165, 165, 165, 165, 166, 166, 166, 166, 166, 166, 166, 166,
- 168, 168, 168, 168, 168, 168, 168, 168, 174, 174, 174, 174, 174, 174, 174,
- 174, 175, 175, 175, 175, 175, 175, 175, 175, 180, 180, 180, 180, 180, 180,
- 180, 180, 182, 182, 182, 182, 182, 182, 182, 182, 183, 183, 183, 183, 183,
- 183, 183, 183, 188, 188, 188, 188, 188, 188, 188, 188, 191, 191, 191, 191,
- 191, 191, 191, 191, 197, 197, 197, 197, 197, 197, 197, 197, 231, 231, 231,
- 231, 231, 231, 231, 231, 239, 239, 239, 239, 239, 239, 239, 239, 9, 9,
- 9, 9, 142, 142, 142, 142, 144, 144, 144, 144, 145, 145, 145, 145, 148,
- 148, 148, 148, 159, 159, 159, 159, 171, 171, 171, 171, 206, 206, 206, 206,
- 215, 215, 215, 215, 225, 225, 225, 225, 236, 236, 236, 236, 237, 237, 237,
- 237, 199, 199, 207, 207, 234, 234, 235, 235, 192, 193, 200, 201, 202, 205,
- 210, 213, 218, 219, 238, 240, 242, 243, 255, -1, 203, 203, 203, 203, 203,
- 203, 203, 203, 204, 204, 204, 204, 204, 204, 204, 204, 211, 211, 211, 211,
- 211, 211, 211, 211, 212, 212, 212, 212, 212, 212, 212, 212, 214, 214, 214,
- 214, 214, 214, 214, 214, 221, 221, 221, 221, 221, 221, 221, 221, 222, 222,
- 222, 222, 222, 222, 222, 222, 223, 223, 223, 223, 223, 223, 223, 223, 241,
- 241, 241, 241, 241, 241, 241, 241, 244, 244, 244, 244, 244, 244, 244, 244,
- 245, 245, 245, 245, 245, 245, 245, 245, 246, 246, 246, 246, 246, 246, 246,
- 246, 247, 247, 247, 247, 247, 247, 247, 247, 248, 248, 248, 248, 248, 248,
- 248, 248, 250, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251,
- 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253,
- 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 2, 2, 2,
- 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
- 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 11, 11, 11, 11, 12,
- 12, 12, 12, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
- 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20,
- 20, 21, 21, 21, 21, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25,
- 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29,
- 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31, 127, 127, 127, 127,
- 220, 220, 220, 220, 249, 249, 249, 249, 10, 13, 22, 256, 93, 93, 93,
- 93, 126, 126, 126, 126, 94, 94, 125, 125, 60, 96, 123, -1, 92, 195,
- 208, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 128,
- 128, 128, 128, 128, 128, 128, 128, 130, 130, 130, 130, 130, 130, 130, 130,
- 131, 131, 131, 131, 131, 131, 131, 131, 162, 162, 162, 162, 162, 162, 162,
- 162, 184, 184, 184, 184, 184, 184, 184, 184, 194, 194, 194, 194, 194, 194,
- 194, 194, 224, 224, 224, 224, 224, 224, 224, 224, 226, 226, 226, 226, 226,
- 226, 226, 226, 153, 153, 153, 153, 161, 161, 161, 161, 167, 167, 167, 167,
- 172, 172, 172, 172, 176, 176, 176, 176, 177, 177, 177, 177, 179, 179, 179,
- 179, 209, 209, 209, 209, 216, 216, 216, 216, 217, 217, 217, 217, 227, 227,
- 227, 227, 229, 229, 229, 229, 230, 230, 230, 230, 129, 129, 132, 132, 133,
- 133, 134, 134, 136, 136, 146, 146, 154, 154, 156, 156, 160, 160, 163, 163,
- 164, 164, 169, 169, 170, 170, 173, 173, 178, 178, 181, 181, 185, 185, 186,
- 186, 187, 187, 189, 189, 190, 190, 196, 196, 198, 198, 228, 228, 232, 232,
- 233, 233, 1, 135, 137, 138, 139, 140, 141, 143, 147, 149, 150, 151, 152,
- 155, 157, 158, 165, 166, 168, 174, 175, 180, 182, 183, 188, 191, 197, 231,
- 239, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 9, 9,
- 9, 9, 9, 9, 9, 142, 142, 142, 142, 142, 142, 142, 142, 144, 144,
- 144, 144, 144, 144, 144, 144, 145, 145, 145, 145, 145, 145, 145, 145, 148,
- 148, 148, 148, 148, 148, 148, 148, 159, 159, 159, 159, 159, 159, 159, 159,
- 171, 171, 171, 171, 171, 171, 171, 171, 206, 206, 206, 206, 206, 206, 206,
- 206, 215, 215, 215, 215, 215, 215, 215, 215, 225, 225, 225, 225, 225, 225,
- 225, 225, 236, 236, 236, 236, 236, 236, 236, 236, 237, 237, 237, 237, 237,
- 237, 237, 237, 199, 199, 199, 199, 207, 207, 207, 207, 234, 234, 234, 234,
- 235, 235, 235, 235, 192, 192, 193, 193, 200, 200, 201, 201, 202, 202, 205,
- 205, 210, 210, 213, 213, 218, 218, 219, 219, 238, 238, 240, 240, 242, 242,
- 243, 243, 255, 255, 203, 204, 211, 212, 214, 221, 222, 223, 241, 244, 245,
- 246, 247, 248, 250, 251, 252, 253, 254, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 2, 2,
- 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,
- 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6,
- 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
- 8, 8, 8, 8, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12,
- 12, 12, 12, 12, 12, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15,
- 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17,
- 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18,
- 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20,
- 20, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 23, 23, 23, 23,
- 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25,
- 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27,
- 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29,
- 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31,
- 31, 31, 31, 31, 31, 31, 127, 127, 127, 127, 127, 127, 127, 127, 220,
- 220, 220, 220, 220, 220, 220, 220, 249, 249, 249, 249, 249, 249, 249, 249,
- 10, 10, 13, 13, 22, 22, 256, 256, 67, 67, 67, 67, 67, 67, 67,
- 67, 68, 68, 68, 68, 68, 68, 68, 68, 95, 95, 95, 95, 95, 95,
- 95, 95, 98, 98, 98, 98, 98, 98, 98, 98, 100, 100, 100, 100, 100,
- 100, 100, 100, 102, 102, 102, 102, 102, 102, 102, 102, 103, 103, 103, 103,
- 103, 103, 103, 103, 104, 104, 104, 104, 104, 104, 104, 104, 108, 108, 108,
- 108, 108, 108, 108, 108, 109, 109, 109, 109, 109, 109, 109, 109, 110, 110,
- 110, 110, 110, 110, 110, 110, 112, 112, 112, 112, 112, 112, 112, 112, 114,
- 114, 114, 114, 114, 114, 114, 114, 117, 117, 117, 117, 117, 117, 117, 117,
- 58, 58, 58, 58, 66, 66, 66, 66, 67, 67, 67, 67, 68, 68, 68,
- 68, 69, 69, 69, 69, 70, 70, 70, 70, 71, 71, 71, 71, 72, 72,
- 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 75, 75, 75, 75, 76,
- 76, 76, 76, 77, 77, 77, 77, 78, 78, 78, 78, 79, 79, 79, 79,
- 80, 80, 80, 80, 81, 81, 81, 81, 82, 82, 82, 82, 83, 83, 83,
- 83, 84, 84, 84, 84, 85, 85, 85, 85, 86, 86, 86, 86, 87, 87,
- 87, 87, 89, 89, 89, 89, 106, 106, 106, 106, 107, 107, 107, 107, 113,
- 113, 113, 113, 118, 118, 118, 118, 119, 119, 119, 119, 120, 120, 120, 120,
- 121, 121, 121, 121, 122, 122, 122, 122, 38, 38, 42, 42, 44, 44, 59,
- 59, 88, 88, 90, 90, -1, -1, -1, -1, 33, 33, 33, 33, 33, 33,
- 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 40, 40, 40, 40, 40,
- 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 63, 63, 63, 63,
- 63, 63, 63, 63, 39, 39, 39, 39, 43, 43, 43, 43, 124, 124, 124,
- 124, 35, 35, 62, 62, 0, 36, 64, 91, 93, 126, -1, -1, 94, 94,
- 94, 94, 94, 94, 94, 94, 125, 125, 125, 125, 125, 125, 125, 125, 60,
- 60, 60, 60, 96, 96, 96, 96, 123, 123, 123, 123, -1, -1, -1, -1,
- 92, 92, 92, 92, 195, 195, 195, 195, 208, 208, 208, 208, 128, 128, 130,
- 130, 131, 131, 162, 162, 184, 184, 194, 194, 224, 224, 226, 226, 153, 161,
- 167, 172, 176, 177, 179, 209, 216, 217, 227, 229, 230, -1, -1, -1, -1,
- -1, -1, -1, 129, 129, 129, 129, 129, 129, 129, 129, 132, 132, 132, 132,
- 132, 132, 132, 132, 133, 133, 133, 133, 133, 133, 133, 133, 134, 134, 134,
- 134, 134, 134, 134, 134, 136, 136, 136, 136, 136, 136, 136, 136, 146, 146,
- 146, 146, 146, 146, 146, 146, 154, 154, 154, 154, 154, 154, 154, 154, 156,
- 156, 156, 156, 156, 156, 156, 156, 160, 160, 160, 160, 160, 160, 160, 160,
- 163, 163, 163, 163, 163, 163, 163, 163, 164, 164, 164, 164, 164, 164, 164,
- 164, 169, 169, 169, 169, 169, 169, 169, 169, 170, 170, 170, 170, 170, 170,
- 170, 170, 173, 173, 173, 173, 173, 173, 173, 173, 178, 178, 178, 178, 178,
- 178, 178, 178, 181, 181, 181, 181, 181, 181, 181, 181, 185, 185, 185, 185,
- 185, 185, 185, 185, 186, 186, 186, 186, 186, 186, 186, 186, 187, 187, 187,
- 187, 187, 187, 187, 187, 189, 189, 189, 189, 189, 189, 189, 189, 190, 190,
- 190, 190, 190, 190, 190, 190, 196, 196, 196, 196, 196, 196, 196, 196, 198,
- 198, 198, 198, 198, 198, 198, 198, 228, 228, 228, 228, 228, 228, 228, 228,
- 232, 232, 232, 232, 232, 232, 232, 232, 233, 233, 233, 233, 233, 233, 233,
- 233, 1, 1, 1, 1, 135, 135, 135, 135, 137, 137, 137, 137, 138, 138,
- 138, 138, 139, 139, 139, 139, 140, 140, 140, 140, 141, 141, 141, 141, 143,
- 143, 143, 143, 147, 147, 147, 147, 149, 149, 149, 149, 150, 150, 150, 150,
- 151, 151, 151, 151, 152, 152, 152, 152, 155, 155, 155, 155, 157, 157, 157,
- 157, 158, 158, 158, 158, 165, 165, 165, 165, 166, 166, 166, 166, 168, 168,
- 168, 168, 174, 174, 174, 174, 175, 175, 175, 175, 180, 180, 180, 180, 182,
- 182, 182, 182, 183, 183, 183, 183, 188, 188, 188, 188, 191, 191, 191, 191,
- 197, 197, 197, 197, 231, 231, 231, 231, 239, 239, 239, 239, 9, 9, 142,
- 142, 144, 144, 145, 145, 148, 148, 159, 159, 171, 171, 206, 206, 215, 215,
- 225, 225, 236, 236, 237, 237, 199, 207, 234, 235, 192, 192, 192, 192, 192,
- 192, 192, 192, 193, 193, 193, 193, 193, 193, 193, 193, 200, 200, 200, 200,
- 200, 200, 200, 200, 201, 201, 201, 201, 201, 201, 201, 201, 202, 202, 202,
- 202, 202, 202, 202, 202, 205, 205, 205, 205, 205, 205, 205, 205, 210, 210,
- 210, 210, 210, 210, 210, 210, 213, 213, 213, 213, 213, 213, 213, 213, 218,
- 218, 218, 218, 218, 218, 218, 218, 219, 219, 219, 219, 219, 219, 219, 219,
- 238, 238, 238, 238, 238, 238, 238, 238, 240, 240, 240, 240, 240, 240, 240,
- 240, 242, 242, 242, 242, 242, 242, 242, 242, 243, 243, 243, 243, 243, 243,
- 243, 243, 255, 255, 255, 255, 255, 255, 255, 255, 203, 203, 203, 203, 204,
- 204, 204, 204, 211, 211, 211, 211, 212, 212, 212, 212, 214, 214, 214, 214,
- 221, 221, 221, 221, 222, 222, 222, 222, 223, 223, 223, 223, 241, 241, 241,
- 241, 244, 244, 244, 244, 245, 245, 245, 245, 246, 246, 246, 246, 247, 247,
- 247, 247, 248, 248, 248, 248, 250, 250, 250, 250, 251, 251, 251, 251, 252,
- 252, 252, 252, 253, 253, 253, 253, 254, 254, 254, 254, 2, 2, 3, 3,
- 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 11, 11, 12, 12, 14,
- 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21,
- 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30,
- 30, 31, 31, 127, 127, 220, 220, 249, 249, -1, -1, 10, 10, 10, 10,
- 10, 10, 10, 10, 13, 13, 13, 13, 13, 13, 13, 13, 22, 22, 22,
- 22, 22, 22, 22, 22, 256, 256, 256, 256, 256, 256, 256, 256, 45, 45,
- 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 46, 46, 46, 47,
- 47, 47, 47, 47, 47, 47, 47, 51, 51, 51, 51, 51, 51, 51, 51,
- 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 53,
- 53, 54, 54, 54, 54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55,
- 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57,
- 57, 57, 57, 50, 50, 50, 50, 50, 50, 50, 50, 97, 97, 97, 97,
- 97, 97, 97, 97, 99, 99, 99, 99, 99, 99, 99, 99, 101, 101, 101,
- 101, 101, 101, 101, 101, 105, 105, 105, 105, 105, 105, 105, 105, 111, 111,
- 111, 111, 111, 111, 111, 111, 115, 115, 115, 115, 115, 115, 115, 115, 116,
- 116, 116, 116, 116, 116, 116, 116, 32, 32, 32, 32, 37, 37, 37, 37,
- 45, 45, 45, 45, 46, 46, 46, 46, 47, 47, 47, 47, 51, 51, 51,
- 51, 52, 52, 52, 52, 53, 53, 53, 53, 54, 54, 54, 54, 55, 55,
- 55, 55, 56, 56, 56, 56, 57, 57, 57, 57, 61, 61, 61, 61, 65,
- 65, 65, 65, 95, 95, 95, 95, 98, 98, 98, 98, 100, 100, 100, 100,
- 102, 102, 102, 102, 103, 103, 103, 103, 104, 104, 104, 104, 108, 108, 108,
- 108, 109, 109, 109, 109, 110, 110, 110, 110, 112, 112, 112, 112, 114, 114,
- 114, 114, 117, 117, 117, 117, 58, 58, 66, 66, 67, 67, 68, 68, 69,
- 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 75, 76, 76,
- 77, 77, 78, 78, 79, 79, 80, 80, 81, 81, 82, 82, 83, 83, 84,
- 84, 85, 85, 86, 86, 87, 87, 89, 89, 106, 106, 107, 107, 113, 113,
- 118, 118, 119, 119, 120, 120, 121, 121, 122, 122, 38, 42, 44, 59, 88,
- 90, -1, -1, 33, 33, 33, 33, 34, 34, 34, 34, 40, 40, 40, 40,
- 41, 41, 41, 41, 63, 63, 63, 63, 39, 39, 43, 43, 124, 124, 35,
- 62, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 36, 36,
- 36, 36, 36, 36, 36, 36, 64, 64, 64, 64, 64, 64, 64, 64, 91,
- 91, 91, 91, 91, 91, 91, 91, 93, 93, 93, 93, 93, 93, 93, 93,
- 126, 126, 126, 126, 126, 126, 126, 126, 94, 94, 94, 94, 125, 125, 125,
- 125, 60, 60, 96, 96, 123, 123, -1, -1, 92, 92, 195, 195, 208, 208,
- 128, 130, 131, 162, 184, 194, 224, 226, -1, -1, 153, 153, 153, 153, 153,
- 153, 153, 153, 161, 161, 161, 161, 161, 161, 161, 161, 167, 167, 167, 167,
- 167, 167, 167, 167, 172, 172, 172, 172, 172, 172, 172, 172, 176, 176, 176,
- 176, 176, 176, 176, 176, 177, 177, 177, 177, 177, 177, 177, 177, 179, 179,
- 179, 179, 179, 179, 179, 179, 209, 209, 209, 209, 209, 209, 209, 209, 216,
- 216, 216, 216, 216, 216, 216, 216, 217, 217, 217, 217, 217, 217, 217, 217,
- 227, 227, 227, 227, 227, 227, 227, 227, 229, 229, 229, 229, 229, 229, 229,
- 229, 230, 230, 230, 230, 230, 230, 230, 230, 129, 129, 129, 129, 132, 132,
- 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 136, 136, 136, 136, 146,
- 146, 146, 146, 154, 154, 154, 154, 156, 156, 156, 156, 160, 160, 160, 160,
- 163, 163, 163, 163, 164, 164, 164, 164, 169, 169, 169, 169, 170, 170, 170,
- 170, 173, 173, 173, 173, 178, 178, 178, 178, 181, 181, 181, 181, 185, 185,
- 185, 185, 186, 186, 186, 186, 187, 187, 187, 187, 189, 189, 189, 189, 190,
- 190, 190, 190, 196, 196, 196, 196, 198, 198, 198, 198, 228, 228, 228, 228,
- 232, 232, 232, 232, 233, 233, 233, 233, 1, 1, 135, 135, 137, 137, 138,
- 138, 139, 139, 140, 140, 141, 141, 143, 143, 147, 147, 149, 149, 150, 150,
- 151, 151, 152, 152, 155, 155, 157, 157, 158, 158, 165, 165, 166, 166, 168,
- 168, 174, 174, 175, 175, 180, 180, 182, 182, 183, 183, 188, 188, 191, 191,
- 197, 197, 231, 231, 239, 239, 9, 142, 144, 145, 148, 159, 171, 206, 215,
- 225, 236, 237, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 199, 199,
- 199, 199, 199, 199, 199, 199, 207, 207, 207, 207, 207, 207, 207, 207, 234,
- 234, 234, 234, 234, 234, 234, 234, 235, 235, 235, 235, 235, 235, 235, 235,
- 192, 192, 192, 192, 193, 193, 193, 193, 200, 200, 200, 200, 201, 201, 201,
- 201, 202, 202, 202, 202, 205, 205, 205, 205, 210, 210, 210, 210, 213, 213,
- 213, 213, 218, 218, 218, 218, 219, 219, 219, 219, 238, 238, 238, 238, 240,
- 240, 240, 240, 242, 242, 242, 242, 243, 243, 243, 243, 255, 255, 255, 255,
- 203, 203, 204, 204, 211, 211, 212, 212, 214, 214, 221, 221, 222, 222, 223,
- 223, 241, 241, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 250, 250,
- 251, 251, 252, 252, 253, 253, 254, 254, 2, 3, 4, 5, 6, 7, 8,
- 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27,
- 28, 29, 30, 31, 127, 220, 249, -1, 10, 10, 10, 10, 13, 13, 13,
- 13, 22, 22, 22, 22, 256, 256, 256, 256,
-};
-
-static const uint8_t inverse_base64[256] = {
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255,
- 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
- 255, 64, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
- 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
- 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33,
- 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
- 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
- 255,
-};
-
+typedef enum {
+ NOT_BINARY,
+ BINARY_BEGIN,
+ B64_BYTE0,
+ B64_BYTE1,
+ B64_BYTE2,
+ B64_BYTE3
+} binary_state;
+
+/* How parsing works:
+
+ The parser object keeps track of a function pointer which represents the
+ current parse state.
+
+ Each time new bytes are presented, we call into the current state, which
+ recursively parses until all bytes in the given chunk are exhausted.
+
+ The parse state that terminates then saves its function pointer to be the
+ current state so that it can resume when more bytes are available.
+
+ It's expected that most optimizing compilers will turn this code into
+ a set of indirect jumps, and so not waste stack space. */
+
+/* forward declarations for parsing states */
+static grpc_error* parse_begin(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_error(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end, grpc_error* error);
+static grpc_error* still_parse_error(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_illegal_op(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+
+static grpc_error* parse_string_prefix(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_key_string(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_value_string_with_indexed_key(
+ grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_value_string_with_literal_key(
+ grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end);
+
+static grpc_error* parse_value0(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_value1(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_value2(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_value3(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_value4(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_value5up(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+
+static grpc_error* parse_indexed_field(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_indexed_field_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_lithdr_incidx(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_lithdr_incidx_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_lithdr_incidx_v(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_lithdr_notidx(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_lithdr_notidx_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_lithdr_notidx_v(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_lithdr_nvridx(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_lithdr_nvridx_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_lithdr_nvridx_v(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end);
+static grpc_error* parse_max_tbl_size(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+static grpc_error* parse_max_tbl_size_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end);
+
+/* we translate the first byte of a hpack field into one of these decoding
+ cases, then use a lookup table to jump directly to the appropriate parser.
+
+ _X => the integer index is all ones, meaning we need to do varint decoding
+ _V => the integer index is all zeros, meaning we need to decode an additional
+ string value */
+typedef enum {
+ INDEXED_FIELD,
+ INDEXED_FIELD_X,
+ LITHDR_INCIDX,
+ LITHDR_INCIDX_X,
+ LITHDR_INCIDX_V,
+ LITHDR_NOTIDX,
+ LITHDR_NOTIDX_X,
+ LITHDR_NOTIDX_V,
+ LITHDR_NVRIDX,
+ LITHDR_NVRIDX_X,
+ LITHDR_NVRIDX_V,
+ MAX_TBL_SIZE,
+ MAX_TBL_SIZE_X,
+ ILLEGAL
+} first_byte_type;
+
+/* jump table of parse state functions -- order must match first_byte_type
+ above */
+static const grpc_chttp2_hpack_parser_state first_byte_action[] = {
+ parse_indexed_field, parse_indexed_field_x, parse_lithdr_incidx,
+ parse_lithdr_incidx_x, parse_lithdr_incidx_v, parse_lithdr_notidx,
+ parse_lithdr_notidx_x, parse_lithdr_notidx_v, parse_lithdr_nvridx,
+ parse_lithdr_nvridx_x, parse_lithdr_nvridx_v, parse_max_tbl_size,
+ parse_max_tbl_size_x, parse_illegal_op};
+
+/* indexes the first byte to a parse state function - generated by
+ gen_hpack_tables.c */
+static const uint8_t first_byte_lut[256] = {
+ LITHDR_NOTIDX_V, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX,
+ LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX,
+ LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX,
+ LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX, LITHDR_NOTIDX_X,
+ LITHDR_NVRIDX_V, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX,
+ LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX,
+ LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX,
+ LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX, LITHDR_NVRIDX_X,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE,
+ MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE, MAX_TBL_SIZE_X,
+ LITHDR_INCIDX_V, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX,
+ LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX, LITHDR_INCIDX_X,
+ ILLEGAL, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD,
+ INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD, INDEXED_FIELD_X,
+};
+
+/* state table for huffman decoding: given a state, gives an index/16 into
+ next_sub_tbl. Taking that index and adding the value of the nibble being
+ considered returns the next state.
+
+ generated by gen_hpack_tables.c */
+static const uint8_t next_tbl[256] = {
+ 0, 1, 2, 3, 4, 1, 2, 5, 6, 1, 7, 8, 1, 3, 3, 9, 10, 11, 1, 1,
+ 1, 12, 1, 2, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
+ 14, 1, 15, 16, 1, 17, 1, 15, 2, 7, 3, 18, 19, 1, 1, 1, 1, 20, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 15, 2, 2, 7, 21, 1, 22, 1, 1, 1, 1, 1,
+ 1, 1, 1, 15, 2, 2, 2, 2, 2, 2, 23, 24, 25, 1, 1, 1, 1, 2, 2, 2,
+ 26, 3, 3, 27, 10, 28, 1, 1, 1, 1, 1, 1, 2, 3, 29, 10, 30, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 31, 1, 1, 1, 1, 1, 1, 1, 2,
+ 2, 2, 2, 2, 2, 2, 2, 32, 1, 1, 15, 33, 1, 34, 35, 9, 36, 1, 1, 1,
+ 1, 1, 1, 1, 37, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 26, 9,
+ 38, 1, 1, 1, 1, 1, 1, 1, 15, 2, 2, 2, 2, 26, 3, 3, 39, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 7, 3, 3, 3, 40, 2,
+ 41, 1, 1, 1, 42, 43, 1, 1, 44, 1, 1, 1, 1, 15, 2, 2, 2, 2, 2, 2,
+ 3, 3, 3, 45, 46, 1, 1, 2, 2, 2, 35, 3, 3, 18, 47, 2,
+};
+
+/* next state, based upon current state and the current nibble: see above.
+ generated by gen_hpack_tables.c */
+static const int16_t next_sub_tbl[48 * 16] = {
+ 1, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217,
+ 218, 2, 6, 10, 13, 14, 15, 16, 17, 2, 6, 10, 13, 14, 15,
+ 16, 17, 3, 7, 11, 24, 3, 7, 11, 24, 3, 7, 11, 24, 3,
+ 7, 11, 24, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8,
+ 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
+ 199, 200, 201, 202, 203, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 9, 133, 134, 135, 136, 137, 138, 139, 140,
+ 141, 142, 143, 144, 145, 146, 147, 3, 7, 11, 24, 3, 7, 11, 24,
+ 4, 8, 4, 8, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 12, 132, 4, 8, 4, 8, 4, 8,
+ 4, 8, 4, 8, 4, 8, 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, 18, 19, 20, 21, 4, 8, 4,
+ 8, 4, 8, 4, 8, 4, 8, 0, 0, 0, 22, 23, 91, 25, 26,
+ 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 3,
+ 7, 11, 24, 3, 7, 11, 24, 0, 0, 0, 0, 0, 41, 42, 43,
+ 2, 6, 10, 13, 14, 15, 16, 17, 3, 7, 11, 24, 3, 7, 11,
+ 24, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 0, 0,
+ 44, 45, 2, 6, 10, 13, 14, 15, 16, 17, 46, 47, 48, 49, 50,
+ 51, 52, 57, 4, 8, 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, 53, 54, 55, 56, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
+ 68, 69, 70, 71, 72, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 73, 75, 76, 77, 78, 79, 80, 81, 82,
+ 83, 84, 85, 86, 87, 88, 89, 90, 3, 7, 11, 24, 3, 7, 11,
+ 24, 3, 7, 11, 24, 0, 0, 0, 0, 3, 7, 11, 24, 3, 7,
+ 11, 24, 4, 8, 4, 8, 0, 0, 0, 92, 0, 0, 0, 93, 94,
+ 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 3, 7, 11, 24,
+ 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4,
+ 8, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 4,
+ 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 0, 0,
+ 0, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
+ 131, 2, 6, 10, 13, 14, 15, 16, 17, 4, 8, 4, 8, 4, 8,
+ 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 148,
+ 149, 150, 151, 3, 7, 11, 24, 4, 8, 4, 8, 0, 0, 0, 0,
+ 0, 0, 152, 153, 3, 7, 11, 24, 3, 7, 11, 24, 3, 7, 11,
+ 24, 154, 155, 156, 164, 3, 7, 11, 24, 3, 7, 11, 24, 3, 7,
+ 11, 24, 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 157, 158, 159, 160, 161, 162, 163, 165, 166, 167, 168, 169, 170, 171, 172,
+ 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187,
+ 188, 189, 190, 191, 192, 193, 194, 195, 196, 4, 8, 4, 8, 4, 8,
+ 4, 8, 4, 8, 4, 8, 4, 8, 197, 198, 4, 8, 4, 8, 4,
+ 8, 4, 8, 0, 0, 0, 0, 0, 0, 219, 220, 3, 7, 11, 24,
+ 4, 8, 4, 8, 4, 8, 0, 0, 221, 222, 223, 224, 3, 7, 11,
+ 24, 3, 7, 11, 24, 4, 8, 4, 8, 4, 8, 225, 228, 4, 8,
+ 4, 8, 4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 226, 227, 229,
+ 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244,
+ 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 245, 246, 247, 248, 249, 250, 251, 252,
+ 253, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 255,
+};
+
+/* emission table: indexed like next_tbl, ultimately gives the byte to be
+ emitted, or -1 for no byte, or 256 for end of stream
+
+ generated by gen_hpack_tables.c */
+static const uint16_t emit_tbl[256] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 0, 8, 9, 10, 11, 12, 13,
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 0, 23, 24, 25, 26, 27,
+ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 0, 55, 56,
+ 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 0,
+ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,
+ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
+ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
+ 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,
+ 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145,
+ 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 0,
+ 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
+ 0, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188,
+ 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203,
+ 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
+ 219, 220, 221, 0, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,
+ 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
+ 248,
+};
+
+/* generated by gen_hpack_tables.c */
+static const int16_t emit_sub_tbl[249 * 16] = {
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, 49, 49,
+ 49, 49, 48, 48, 48, 48, 49, 49, 49, 49, 50, 50, 50, 50, 97,
+ 97, 97, 97, 48, 48, 49, 49, 50, 50, 97, 97, 99, 99, 101, 101,
+ 105, 105, 111, 111, 48, 49, 50, 97, 99, 101, 105, 111, 115, 116, -1,
+ -1, -1, -1, -1, -1, 32, 32, 32, 32, 32, 32, 32, 32, 37, 37,
+ 37, 37, 37, 37, 37, 37, 99, 99, 99, 99, 101, 101, 101, 101, 105,
+ 105, 105, 105, 111, 111, 111, 111, 115, 115, 116, 116, 32, 37, 45, 46,
+ 47, 51, 52, 53, 54, 55, 56, 57, 61, 61, 61, 61, 61, 61, 61,
+ 61, 65, 65, 65, 65, 65, 65, 65, 65, 115, 115, 115, 115, 116, 116,
+ 116, 116, 32, 32, 37, 37, 45, 45, 46, 46, 61, 65, 95, 98, 100,
+ 102, 103, 104, 108, 109, 110, 112, 114, 117, -1, -1, 58, 58, 58, 58,
+ 58, 58, 58, 58, 66, 66, 66, 66, 66, 66, 66, 66, 47, 47, 51,
+ 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 61, 61,
+ 65, 65, 95, 95, 98, 98, 100, 100, 102, 102, 103, 103, 104, 104, 108,
+ 108, 109, 109, 110, 110, 112, 112, 114, 114, 117, 117, 58, 66, 67, 68,
+ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
+ 84, 85, 86, 87, 89, 106, 107, 113, 118, 119, 120, 121, 122, -1, -1,
+ -1, -1, 38, 38, 38, 38, 38, 38, 38, 38, 42, 42, 42, 42, 42,
+ 42, 42, 42, 44, 44, 44, 44, 44, 44, 44, 44, 59, 59, 59, 59,
+ 59, 59, 59, 59, 88, 88, 88, 88, 88, 88, 88, 88, 90, 90, 90,
+ 90, 90, 90, 90, 90, 33, 33, 34, 34, 40, 40, 41, 41, 63, 63,
+ 39, 43, 124, -1, -1, -1, 35, 35, 35, 35, 35, 35, 35, 35, 62,
+ 62, 62, 62, 62, 62, 62, 62, 0, 0, 0, 0, 36, 36, 36, 36,
+ 64, 64, 64, 64, 91, 91, 91, 91, 69, 69, 69, 69, 69, 69, 69,
+ 69, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71,
+ 71, 71, 72, 72, 72, 72, 72, 72, 72, 72, 73, 73, 73, 73, 73,
+ 73, 73, 73, 74, 74, 74, 74, 74, 74, 74, 74, 75, 75, 75, 75,
+ 75, 75, 75, 75, 76, 76, 76, 76, 76, 76, 76, 76, 77, 77, 77,
+ 77, 77, 77, 77, 77, 78, 78, 78, 78, 78, 78, 78, 78, 79, 79,
+ 79, 79, 79, 79, 79, 79, 80, 80, 80, 80, 80, 80, 80, 80, 81,
+ 81, 81, 81, 81, 81, 81, 81, 82, 82, 82, 82, 82, 82, 82, 82,
+ 83, 83, 83, 83, 83, 83, 83, 83, 84, 84, 84, 84, 84, 84, 84,
+ 84, 85, 85, 85, 85, 85, 85, 85, 85, 86, 86, 86, 86, 86, 86,
+ 86, 86, 87, 87, 87, 87, 87, 87, 87, 87, 89, 89, 89, 89, 89,
+ 89, 89, 89, 106, 106, 106, 106, 106, 106, 106, 106, 107, 107, 107, 107,
+ 107, 107, 107, 107, 113, 113, 113, 113, 113, 113, 113, 113, 118, 118, 118,
+ 118, 118, 118, 118, 118, 119, 119, 119, 119, 119, 119, 119, 119, 120, 120,
+ 120, 120, 120, 120, 120, 120, 121, 121, 121, 121, 121, 121, 121, 121, 122,
+ 122, 122, 122, 122, 122, 122, 122, 38, 38, 38, 38, 42, 42, 42, 42,
+ 44, 44, 44, 44, 59, 59, 59, 59, 88, 88, 88, 88, 90, 90, 90,
+ 90, 33, 34, 40, 41, 63, -1, -1, -1, 39, 39, 39, 39, 39, 39,
+ 39, 39, 43, 43, 43, 43, 43, 43, 43, 43, 124, 124, 124, 124, 124,
+ 124, 124, 124, 35, 35, 35, 35, 62, 62, 62, 62, 0, 0, 36, 36,
+ 64, 64, 91, 91, 93, 93, 126, 126, 94, 125, -1, -1, 60, 60, 60,
+ 60, 60, 60, 60, 60, 96, 96, 96, 96, 96, 96, 96, 96, 123, 123,
+ 123, 123, 123, 123, 123, 123, -1, -1, -1, -1, -1, -1, -1, -1, 92,
+ 92, 92, 92, 92, 92, 92, 92, 195, 195, 195, 195, 195, 195, 195, 195,
+ 208, 208, 208, 208, 208, 208, 208, 208, 128, 128, 128, 128, 130, 130, 130,
+ 130, 131, 131, 131, 131, 162, 162, 162, 162, 184, 184, 184, 184, 194, 194,
+ 194, 194, 224, 224, 224, 224, 226, 226, 226, 226, 153, 153, 161, 161, 167,
+ 167, 172, 172, 176, 176, 177, 177, 179, 179, 209, 209, 216, 216, 217, 217,
+ 227, 227, 229, 229, 230, 230, 129, 132, 133, 134, 136, 146, 154, 156, 160,
+ 163, 164, 169, 170, 173, 178, 181, 185, 186, 187, 189, 190, 196, 198, 228,
+ 232, 233, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 135,
+ 135, 135, 135, 135, 135, 135, 135, 137, 137, 137, 137, 137, 137, 137, 137,
+ 138, 138, 138, 138, 138, 138, 138, 138, 139, 139, 139, 139, 139, 139, 139,
+ 139, 140, 140, 140, 140, 140, 140, 140, 140, 141, 141, 141, 141, 141, 141,
+ 141, 141, 143, 143, 143, 143, 143, 143, 143, 143, 147, 147, 147, 147, 147,
+ 147, 147, 147, 149, 149, 149, 149, 149, 149, 149, 149, 150, 150, 150, 150,
+ 150, 150, 150, 150, 151, 151, 151, 151, 151, 151, 151, 151, 152, 152, 152,
+ 152, 152, 152, 152, 152, 155, 155, 155, 155, 155, 155, 155, 155, 157, 157,
+ 157, 157, 157, 157, 157, 157, 158, 158, 158, 158, 158, 158, 158, 158, 165,
+ 165, 165, 165, 165, 165, 165, 165, 166, 166, 166, 166, 166, 166, 166, 166,
+ 168, 168, 168, 168, 168, 168, 168, 168, 174, 174, 174, 174, 174, 174, 174,
+ 174, 175, 175, 175, 175, 175, 175, 175, 175, 180, 180, 180, 180, 180, 180,
+ 180, 180, 182, 182, 182, 182, 182, 182, 182, 182, 183, 183, 183, 183, 183,
+ 183, 183, 183, 188, 188, 188, 188, 188, 188, 188, 188, 191, 191, 191, 191,
+ 191, 191, 191, 191, 197, 197, 197, 197, 197, 197, 197, 197, 231, 231, 231,
+ 231, 231, 231, 231, 231, 239, 239, 239, 239, 239, 239, 239, 239, 9, 9,
+ 9, 9, 142, 142, 142, 142, 144, 144, 144, 144, 145, 145, 145, 145, 148,
+ 148, 148, 148, 159, 159, 159, 159, 171, 171, 171, 171, 206, 206, 206, 206,
+ 215, 215, 215, 215, 225, 225, 225, 225, 236, 236, 236, 236, 237, 237, 237,
+ 237, 199, 199, 207, 207, 234, 234, 235, 235, 192, 193, 200, 201, 202, 205,
+ 210, 213, 218, 219, 238, 240, 242, 243, 255, -1, 203, 203, 203, 203, 203,
+ 203, 203, 203, 204, 204, 204, 204, 204, 204, 204, 204, 211, 211, 211, 211,
+ 211, 211, 211, 211, 212, 212, 212, 212, 212, 212, 212, 212, 214, 214, 214,
+ 214, 214, 214, 214, 214, 221, 221, 221, 221, 221, 221, 221, 221, 222, 222,
+ 222, 222, 222, 222, 222, 222, 223, 223, 223, 223, 223, 223, 223, 223, 241,
+ 241, 241, 241, 241, 241, 241, 241, 244, 244, 244, 244, 244, 244, 244, 244,
+ 245, 245, 245, 245, 245, 245, 245, 245, 246, 246, 246, 246, 246, 246, 246,
+ 246, 247, 247, 247, 247, 247, 247, 247, 247, 248, 248, 248, 248, 248, 248,
+ 248, 248, 250, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251,
+ 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253,
+ 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 2, 2, 2,
+ 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
+ 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 11, 11, 11, 11, 12,
+ 12, 12, 12, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
+ 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20,
+ 20, 21, 21, 21, 21, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25,
+ 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29,
+ 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31, 127, 127, 127, 127,
+ 220, 220, 220, 220, 249, 249, 249, 249, 10, 13, 22, 256, 93, 93, 93,
+ 93, 126, 126, 126, 126, 94, 94, 125, 125, 60, 96, 123, -1, 92, 195,
+ 208, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 128,
+ 128, 128, 128, 128, 128, 128, 128, 130, 130, 130, 130, 130, 130, 130, 130,
+ 131, 131, 131, 131, 131, 131, 131, 131, 162, 162, 162, 162, 162, 162, 162,
+ 162, 184, 184, 184, 184, 184, 184, 184, 184, 194, 194, 194, 194, 194, 194,
+ 194, 194, 224, 224, 224, 224, 224, 224, 224, 224, 226, 226, 226, 226, 226,
+ 226, 226, 226, 153, 153, 153, 153, 161, 161, 161, 161, 167, 167, 167, 167,
+ 172, 172, 172, 172, 176, 176, 176, 176, 177, 177, 177, 177, 179, 179, 179,
+ 179, 209, 209, 209, 209, 216, 216, 216, 216, 217, 217, 217, 217, 227, 227,
+ 227, 227, 229, 229, 229, 229, 230, 230, 230, 230, 129, 129, 132, 132, 133,
+ 133, 134, 134, 136, 136, 146, 146, 154, 154, 156, 156, 160, 160, 163, 163,
+ 164, 164, 169, 169, 170, 170, 173, 173, 178, 178, 181, 181, 185, 185, 186,
+ 186, 187, 187, 189, 189, 190, 190, 196, 196, 198, 198, 228, 228, 232, 232,
+ 233, 233, 1, 135, 137, 138, 139, 140, 141, 143, 147, 149, 150, 151, 152,
+ 155, 157, 158, 165, 166, 168, 174, 175, 180, 182, 183, 188, 191, 197, 231,
+ 239, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 9, 9,
+ 9, 9, 9, 9, 9, 142, 142, 142, 142, 142, 142, 142, 142, 144, 144,
+ 144, 144, 144, 144, 144, 144, 145, 145, 145, 145, 145, 145, 145, 145, 148,
+ 148, 148, 148, 148, 148, 148, 148, 159, 159, 159, 159, 159, 159, 159, 159,
+ 171, 171, 171, 171, 171, 171, 171, 171, 206, 206, 206, 206, 206, 206, 206,
+ 206, 215, 215, 215, 215, 215, 215, 215, 215, 225, 225, 225, 225, 225, 225,
+ 225, 225, 236, 236, 236, 236, 236, 236, 236, 236, 237, 237, 237, 237, 237,
+ 237, 237, 237, 199, 199, 199, 199, 207, 207, 207, 207, 234, 234, 234, 234,
+ 235, 235, 235, 235, 192, 192, 193, 193, 200, 200, 201, 201, 202, 202, 205,
+ 205, 210, 210, 213, 213, 218, 218, 219, 219, 238, 238, 240, 240, 242, 242,
+ 243, 243, 255, 255, 203, 204, 211, 212, 214, 221, 222, 223, 241, 244, 245,
+ 246, 247, 248, 250, 251, 252, 253, 254, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 2, 2,
+ 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,
+ 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6,
+ 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
+ 8, 8, 8, 8, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12,
+ 12, 12, 12, 12, 12, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15,
+ 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17,
+ 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18,
+ 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20,
+ 20, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 23, 23, 23, 23,
+ 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25,
+ 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27,
+ 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29,
+ 29, 29, 29, 29, 29, 30, 30, 30, 30, 30, 30, 30, 30, 31, 31,
+ 31, 31, 31, 31, 31, 31, 127, 127, 127, 127, 127, 127, 127, 127, 220,
+ 220, 220, 220, 220, 220, 220, 220, 249, 249, 249, 249, 249, 249, 249, 249,
+ 10, 10, 13, 13, 22, 22, 256, 256, 67, 67, 67, 67, 67, 67, 67,
+ 67, 68, 68, 68, 68, 68, 68, 68, 68, 95, 95, 95, 95, 95, 95,
+ 95, 95, 98, 98, 98, 98, 98, 98, 98, 98, 100, 100, 100, 100, 100,
+ 100, 100, 100, 102, 102, 102, 102, 102, 102, 102, 102, 103, 103, 103, 103,
+ 103, 103, 103, 103, 104, 104, 104, 104, 104, 104, 104, 104, 108, 108, 108,
+ 108, 108, 108, 108, 108, 109, 109, 109, 109, 109, 109, 109, 109, 110, 110,
+ 110, 110, 110, 110, 110, 110, 112, 112, 112, 112, 112, 112, 112, 112, 114,
+ 114, 114, 114, 114, 114, 114, 114, 117, 117, 117, 117, 117, 117, 117, 117,
+ 58, 58, 58, 58, 66, 66, 66, 66, 67, 67, 67, 67, 68, 68, 68,
+ 68, 69, 69, 69, 69, 70, 70, 70, 70, 71, 71, 71, 71, 72, 72,
+ 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 75, 75, 75, 75, 76,
+ 76, 76, 76, 77, 77, 77, 77, 78, 78, 78, 78, 79, 79, 79, 79,
+ 80, 80, 80, 80, 81, 81, 81, 81, 82, 82, 82, 82, 83, 83, 83,
+ 83, 84, 84, 84, 84, 85, 85, 85, 85, 86, 86, 86, 86, 87, 87,
+ 87, 87, 89, 89, 89, 89, 106, 106, 106, 106, 107, 107, 107, 107, 113,
+ 113, 113, 113, 118, 118, 118, 118, 119, 119, 119, 119, 120, 120, 120, 120,
+ 121, 121, 121, 121, 122, 122, 122, 122, 38, 38, 42, 42, 44, 44, 59,
+ 59, 88, 88, 90, 90, -1, -1, -1, -1, 33, 33, 33, 33, 33, 33,
+ 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 40, 40, 40, 40, 40,
+ 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 63, 63, 63, 63,
+ 63, 63, 63, 63, 39, 39, 39, 39, 43, 43, 43, 43, 124, 124, 124,
+ 124, 35, 35, 62, 62, 0, 36, 64, 91, 93, 126, -1, -1, 94, 94,
+ 94, 94, 94, 94, 94, 94, 125, 125, 125, 125, 125, 125, 125, 125, 60,
+ 60, 60, 60, 96, 96, 96, 96, 123, 123, 123, 123, -1, -1, -1, -1,
+ 92, 92, 92, 92, 195, 195, 195, 195, 208, 208, 208, 208, 128, 128, 130,
+ 130, 131, 131, 162, 162, 184, 184, 194, 194, 224, 224, 226, 226, 153, 161,
+ 167, 172, 176, 177, 179, 209, 216, 217, 227, 229, 230, -1, -1, -1, -1,
+ -1, -1, -1, 129, 129, 129, 129, 129, 129, 129, 129, 132, 132, 132, 132,
+ 132, 132, 132, 132, 133, 133, 133, 133, 133, 133, 133, 133, 134, 134, 134,
+ 134, 134, 134, 134, 134, 136, 136, 136, 136, 136, 136, 136, 136, 146, 146,
+ 146, 146, 146, 146, 146, 146, 154, 154, 154, 154, 154, 154, 154, 154, 156,
+ 156, 156, 156, 156, 156, 156, 156, 160, 160, 160, 160, 160, 160, 160, 160,
+ 163, 163, 163, 163, 163, 163, 163, 163, 164, 164, 164, 164, 164, 164, 164,
+ 164, 169, 169, 169, 169, 169, 169, 169, 169, 170, 170, 170, 170, 170, 170,
+ 170, 170, 173, 173, 173, 173, 173, 173, 173, 173, 178, 178, 178, 178, 178,
+ 178, 178, 178, 181, 181, 181, 181, 181, 181, 181, 181, 185, 185, 185, 185,
+ 185, 185, 185, 185, 186, 186, 186, 186, 186, 186, 186, 186, 187, 187, 187,
+ 187, 187, 187, 187, 187, 189, 189, 189, 189, 189, 189, 189, 189, 190, 190,
+ 190, 190, 190, 190, 190, 190, 196, 196, 196, 196, 196, 196, 196, 196, 198,
+ 198, 198, 198, 198, 198, 198, 198, 228, 228, 228, 228, 228, 228, 228, 228,
+ 232, 232, 232, 232, 232, 232, 232, 232, 233, 233, 233, 233, 233, 233, 233,
+ 233, 1, 1, 1, 1, 135, 135, 135, 135, 137, 137, 137, 137, 138, 138,
+ 138, 138, 139, 139, 139, 139, 140, 140, 140, 140, 141, 141, 141, 141, 143,
+ 143, 143, 143, 147, 147, 147, 147, 149, 149, 149, 149, 150, 150, 150, 150,
+ 151, 151, 151, 151, 152, 152, 152, 152, 155, 155, 155, 155, 157, 157, 157,
+ 157, 158, 158, 158, 158, 165, 165, 165, 165, 166, 166, 166, 166, 168, 168,
+ 168, 168, 174, 174, 174, 174, 175, 175, 175, 175, 180, 180, 180, 180, 182,
+ 182, 182, 182, 183, 183, 183, 183, 188, 188, 188, 188, 191, 191, 191, 191,
+ 197, 197, 197, 197, 231, 231, 231, 231, 239, 239, 239, 239, 9, 9, 142,
+ 142, 144, 144, 145, 145, 148, 148, 159, 159, 171, 171, 206, 206, 215, 215,
+ 225, 225, 236, 236, 237, 237, 199, 207, 234, 235, 192, 192, 192, 192, 192,
+ 192, 192, 192, 193, 193, 193, 193, 193, 193, 193, 193, 200, 200, 200, 200,
+ 200, 200, 200, 200, 201, 201, 201, 201, 201, 201, 201, 201, 202, 202, 202,
+ 202, 202, 202, 202, 202, 205, 205, 205, 205, 205, 205, 205, 205, 210, 210,
+ 210, 210, 210, 210, 210, 210, 213, 213, 213, 213, 213, 213, 213, 213, 218,
+ 218, 218, 218, 218, 218, 218, 218, 219, 219, 219, 219, 219, 219, 219, 219,
+ 238, 238, 238, 238, 238, 238, 238, 238, 240, 240, 240, 240, 240, 240, 240,
+ 240, 242, 242, 242, 242, 242, 242, 242, 242, 243, 243, 243, 243, 243, 243,
+ 243, 243, 255, 255, 255, 255, 255, 255, 255, 255, 203, 203, 203, 203, 204,
+ 204, 204, 204, 211, 211, 211, 211, 212, 212, 212, 212, 214, 214, 214, 214,
+ 221, 221, 221, 221, 222, 222, 222, 222, 223, 223, 223, 223, 241, 241, 241,
+ 241, 244, 244, 244, 244, 245, 245, 245, 245, 246, 246, 246, 246, 247, 247,
+ 247, 247, 248, 248, 248, 248, 250, 250, 250, 250, 251, 251, 251, 251, 252,
+ 252, 252, 252, 253, 253, 253, 253, 254, 254, 254, 254, 2, 2, 3, 3,
+ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 11, 11, 12, 12, 14,
+ 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21,
+ 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30,
+ 30, 31, 31, 127, 127, 220, 220, 249, 249, -1, -1, 10, 10, 10, 10,
+ 10, 10, 10, 10, 13, 13, 13, 13, 13, 13, 13, 13, 22, 22, 22,
+ 22, 22, 22, 22, 22, 256, 256, 256, 256, 256, 256, 256, 256, 45, 45,
+ 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 46, 46, 46, 47,
+ 47, 47, 47, 47, 47, 47, 47, 51, 51, 51, 51, 51, 51, 51, 51,
+ 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 53,
+ 53, 54, 54, 54, 54, 54, 54, 54, 54, 55, 55, 55, 55, 55, 55,
+ 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57,
+ 57, 57, 57, 50, 50, 50, 50, 50, 50, 50, 50, 97, 97, 97, 97,
+ 97, 97, 97, 97, 99, 99, 99, 99, 99, 99, 99, 99, 101, 101, 101,
+ 101, 101, 101, 101, 101, 105, 105, 105, 105, 105, 105, 105, 105, 111, 111,
+ 111, 111, 111, 111, 111, 111, 115, 115, 115, 115, 115, 115, 115, 115, 116,
+ 116, 116, 116, 116, 116, 116, 116, 32, 32, 32, 32, 37, 37, 37, 37,
+ 45, 45, 45, 45, 46, 46, 46, 46, 47, 47, 47, 47, 51, 51, 51,
+ 51, 52, 52, 52, 52, 53, 53, 53, 53, 54, 54, 54, 54, 55, 55,
+ 55, 55, 56, 56, 56, 56, 57, 57, 57, 57, 61, 61, 61, 61, 65,
+ 65, 65, 65, 95, 95, 95, 95, 98, 98, 98, 98, 100, 100, 100, 100,
+ 102, 102, 102, 102, 103, 103, 103, 103, 104, 104, 104, 104, 108, 108, 108,
+ 108, 109, 109, 109, 109, 110, 110, 110, 110, 112, 112, 112, 112, 114, 114,
+ 114, 114, 117, 117, 117, 117, 58, 58, 66, 66, 67, 67, 68, 68, 69,
+ 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 75, 76, 76,
+ 77, 77, 78, 78, 79, 79, 80, 80, 81, 81, 82, 82, 83, 83, 84,
+ 84, 85, 85, 86, 86, 87, 87, 89, 89, 106, 106, 107, 107, 113, 113,
+ 118, 118, 119, 119, 120, 120, 121, 121, 122, 122, 38, 42, 44, 59, 88,
+ 90, -1, -1, 33, 33, 33, 33, 34, 34, 34, 34, 40, 40, 40, 40,
+ 41, 41, 41, 41, 63, 63, 63, 63, 39, 39, 43, 43, 124, 124, 35,
+ 62, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 36, 36,
+ 36, 36, 36, 36, 36, 36, 64, 64, 64, 64, 64, 64, 64, 64, 91,
+ 91, 91, 91, 91, 91, 91, 91, 93, 93, 93, 93, 93, 93, 93, 93,
+ 126, 126, 126, 126, 126, 126, 126, 126, 94, 94, 94, 94, 125, 125, 125,
+ 125, 60, 60, 96, 96, 123, 123, -1, -1, 92, 92, 195, 195, 208, 208,
+ 128, 130, 131, 162, 184, 194, 224, 226, -1, -1, 153, 153, 153, 153, 153,
+ 153, 153, 153, 161, 161, 161, 161, 161, 161, 161, 161, 167, 167, 167, 167,
+ 167, 167, 167, 167, 172, 172, 172, 172, 172, 172, 172, 172, 176, 176, 176,
+ 176, 176, 176, 176, 176, 177, 177, 177, 177, 177, 177, 177, 177, 179, 179,
+ 179, 179, 179, 179, 179, 179, 209, 209, 209, 209, 209, 209, 209, 209, 216,
+ 216, 216, 216, 216, 216, 216, 216, 217, 217, 217, 217, 217, 217, 217, 217,
+ 227, 227, 227, 227, 227, 227, 227, 227, 229, 229, 229, 229, 229, 229, 229,
+ 229, 230, 230, 230, 230, 230, 230, 230, 230, 129, 129, 129, 129, 132, 132,
+ 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 136, 136, 136, 136, 146,
+ 146, 146, 146, 154, 154, 154, 154, 156, 156, 156, 156, 160, 160, 160, 160,
+ 163, 163, 163, 163, 164, 164, 164, 164, 169, 169, 169, 169, 170, 170, 170,
+ 170, 173, 173, 173, 173, 178, 178, 178, 178, 181, 181, 181, 181, 185, 185,
+ 185, 185, 186, 186, 186, 186, 187, 187, 187, 187, 189, 189, 189, 189, 190,
+ 190, 190, 190, 196, 196, 196, 196, 198, 198, 198, 198, 228, 228, 228, 228,
+ 232, 232, 232, 232, 233, 233, 233, 233, 1, 1, 135, 135, 137, 137, 138,
+ 138, 139, 139, 140, 140, 141, 141, 143, 143, 147, 147, 149, 149, 150, 150,
+ 151, 151, 152, 152, 155, 155, 157, 157, 158, 158, 165, 165, 166, 166, 168,
+ 168, 174, 174, 175, 175, 180, 180, 182, 182, 183, 183, 188, 188, 191, 191,
+ 197, 197, 231, 231, 239, 239, 9, 142, 144, 145, 148, 159, 171, 206, 215,
+ 225, 236, 237, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 199, 199,
+ 199, 199, 199, 199, 199, 199, 207, 207, 207, 207, 207, 207, 207, 207, 234,
+ 234, 234, 234, 234, 234, 234, 234, 235, 235, 235, 235, 235, 235, 235, 235,
+ 192, 192, 192, 192, 193, 193, 193, 193, 200, 200, 200, 200, 201, 201, 201,
+ 201, 202, 202, 202, 202, 205, 205, 205, 205, 210, 210, 210, 210, 213, 213,
+ 213, 213, 218, 218, 218, 218, 219, 219, 219, 219, 238, 238, 238, 238, 240,
+ 240, 240, 240, 242, 242, 242, 242, 243, 243, 243, 243, 255, 255, 255, 255,
+ 203, 203, 204, 204, 211, 211, 212, 212, 214, 214, 221, 221, 222, 222, 223,
+ 223, 241, 241, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 250, 250,
+ 251, 251, 252, 252, 253, 253, 254, 254, 2, 3, 4, 5, 6, 7, 8,
+ 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27,
+ 28, 29, 30, 31, 127, 220, 249, -1, 10, 10, 10, 10, 13, 13, 13,
+ 13, 22, 22, 22, 22, 256, 256, 256, 256,
+};
+
+static const uint8_t inverse_base64[256] = {
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255,
+ 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
+ 255, 64, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33,
+ 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
+ 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 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;
@@ -645,18 +645,18 @@ static void GPR_ATTRIBUTE_NOINLINE on_hdr_log(grpc_mdelem md) {
gpr_free(v);
}
-/* emission helpers */
+/* 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);
- }
+ }
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);
+ grpc_error* err = grpc_chttp2_hptbl_add(&p->table, md);
if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) return err;
- }
+ }
return p->on_header(p->on_header_user_data, md);
}
@@ -671,97 +671,97 @@ static grpc_core::UnmanagedMemorySlice take_string_extern(
} else {
s = grpc_core::UnmanagedMemorySlice(str->data.copied.str,
str->data.copied.length);
- }
+ }
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;
- if (!str->copied) {
+ if (!str->copied) {
s = grpc_core::ManagedMemorySlice(&str->data.referenced);
grpc_slice_unref_internal(str->data.referenced);
- str->copied = true;
- str->data.referenced = grpc_empty_slice();
- } else {
+ str->copied = true;
+ str->data.referenced = grpc_empty_slice();
+ } else {
s = grpc_core::ManagedMemorySlice(str->data.copied.str,
- str->data.copied.length);
- }
- str->data.copied.length = 0;
- return s;
-}
-
-/* jump to the next state */
-static grpc_error* parse_next(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- p->state = *p->next_state++;
- return p->state(p, cur, end);
-}
-
-/* begin parsing a header: all functionality is encoded into lookup tables
- above */
-static grpc_error* parse_begin(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- if (cur == end) {
- p->state = parse_begin;
- return GRPC_ERROR_NONE;
- }
-
- return first_byte_action[first_byte_lut[*cur]](p, cur, end);
-}
-
-/* stream dependency and prioritization data: we just skip it */
-static grpc_error* parse_stream_weight(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (cur == end) {
- p->state = parse_stream_weight;
- return GRPC_ERROR_NONE;
- }
-
- return p->after_prioritization(p, cur + 1, end);
-}
-
-static grpc_error* parse_stream_dep3(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (cur == end) {
- p->state = parse_stream_dep3;
- return GRPC_ERROR_NONE;
- }
-
- return parse_stream_weight(p, cur + 1, end);
-}
-
-static grpc_error* parse_stream_dep2(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (cur == end) {
- p->state = parse_stream_dep2;
- return GRPC_ERROR_NONE;
- }
-
- return parse_stream_dep3(p, cur + 1, end);
-}
-
-static grpc_error* parse_stream_dep1(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (cur == end) {
- p->state = parse_stream_dep1;
- return GRPC_ERROR_NONE;
- }
-
- return parse_stream_dep2(p, cur + 1, end);
-}
-
-static grpc_error* parse_stream_dep0(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (cur == end) {
- p->state = parse_stream_dep0;
- return GRPC_ERROR_NONE;
- }
-
- return parse_stream_dep1(p, cur + 1, end);
-}
-
+ str->data.copied.length);
+ }
+ str->data.copied.length = 0;
+ return s;
+}
+
+/* jump to the next state */
+static grpc_error* parse_next(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ p->state = *p->next_state++;
+ return p->state(p, cur, end);
+}
+
+/* begin parsing a header: all functionality is encoded into lookup tables
+ above */
+static grpc_error* parse_begin(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_begin;
+ return GRPC_ERROR_NONE;
+ }
+
+ return first_byte_action[first_byte_lut[*cur]](p, cur, end);
+}
+
+/* stream dependency and prioritization data: we just skip it */
+static grpc_error* parse_stream_weight(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_stream_weight;
+ return GRPC_ERROR_NONE;
+ }
+
+ return p->after_prioritization(p, cur + 1, end);
+}
+
+static grpc_error* parse_stream_dep3(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_stream_dep3;
+ return GRPC_ERROR_NONE;
+ }
+
+ return parse_stream_weight(p, cur + 1, end);
+}
+
+static grpc_error* parse_stream_dep2(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_stream_dep2;
+ return GRPC_ERROR_NONE;
+ }
+
+ return parse_stream_dep3(p, cur + 1, end);
+}
+
+static grpc_error* parse_stream_dep1(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_stream_dep1;
+ return GRPC_ERROR_NONE;
+ }
+
+ return parse_stream_dep2(p, cur + 1, end);
+}
+
+static grpc_error* parse_stream_dep0(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_stream_dep0;
+ return GRPC_ERROR_NONE;
+ }
+
+ 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(
@@ -771,43 +771,43 @@ on_invalid_hpack_idx(grpc_chttp2_hpack_parser* p) {
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) {
+/* 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_STATS_INC_HPACK_RECV_INDEXED();
+ }
+ GRPC_STATS_INC_HPACK_RECV_INDEXED();
grpc_error* err = on_hdr<false>(p, md);
if (GPR_UNLIKELY(err != GRPC_ERROR_NONE)) return err;
- return parse_begin(p, cur, end);
-}
-
-/* parse an indexed field with index < 127 */
-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;
+ return parse_begin(p, cur, end);
+}
+
+/* parse an indexed field with index < 127 */
+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. */
- return finish_indexed_field(p, cur + 1, end);
-}
-
-/* parse an indexed field with index >= 127 */
-static grpc_error* parse_indexed_field_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- finish_indexed_field};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- p->index = 0x7f;
+ return finish_indexed_field(p, cur + 1, end);
+}
+
+/* parse an indexed field with index >= 127 */
+static grpc_error* parse_indexed_field_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ finish_indexed_field};
+ 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->parsing.value = &p->index;
- return parse_value0(p, cur + 1, end);
-}
-
+ 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. */
@@ -829,699 +829,699 @@ static const grpc_core::ManagedMemorySlice& get_indexed_key(grpc_mdelem md) {
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();
+/* 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)));
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_begin(p, cur, end);
-}
-
-/* finish a literal header with incremental indexing with no index */
-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();
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_begin(p, cur, end);
+}
+
+/* finish a literal header with incremental indexing with no index */
+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)));
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_begin(p, cur, end);
-}
-
-/* parse a literal header with incremental indexing; index < 63 */
-static grpc_error* parse_lithdr_incidx(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_value_string_with_indexed_key, finish_lithdr_incidx};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- p->index = (*cur) & 0x3f;
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_begin(p, cur, end);
+}
+
+/* parse a literal header with incremental indexing; index < 63 */
+static grpc_error* parse_lithdr_incidx(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_value_string_with_indexed_key, finish_lithdr_incidx};
+ 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. */
- return parse_string_prefix(p, cur + 1, end);
-}
-
-/* parse a literal header with incremental indexing; index >= 63 */
-static grpc_error* parse_lithdr_incidx_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_string_prefix, parse_value_string_with_indexed_key,
- finish_lithdr_incidx};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- p->index = 0x3f;
+ return parse_string_prefix(p, cur + 1, end);
+}
+
+/* parse a literal header with incremental indexing; index >= 63 */
+static grpc_error* parse_lithdr_incidx_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_string_prefix, parse_value_string_with_indexed_key,
+ finish_lithdr_incidx};
+ 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->parsing.value = &p->index;
- return parse_value0(p, cur + 1, end);
-}
-
-/* parse a literal header with incremental indexing; index = 0 */
-static grpc_error* parse_lithdr_incidx_v(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_key_string, parse_string_prefix,
- parse_value_string_with_literal_key, finish_lithdr_incidx_v};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- return parse_string_prefix(p, cur + 1, end);
-}
-
-/* finish a literal header without incremental indexing */
-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();
+ p->parsing.value = &p->index;
+ return parse_value0(p, cur + 1, end);
+}
+
+/* parse a literal header with incremental indexing; index = 0 */
+static grpc_error* parse_lithdr_incidx_v(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_key_string, parse_string_prefix,
+ parse_value_string_with_literal_key, finish_lithdr_incidx_v};
+ p->dynamic_table_update_allowed = 0;
+ p->next_state = and_then;
+ return parse_string_prefix(p, cur + 1, end);
+}
+
+/* finish a literal header without incremental indexing */
+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)));
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_begin(p, cur, end);
-}
-
-/* finish a literal header without incremental indexing with index = 0 */
-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();
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_begin(p, cur, end);
+}
+
+/* finish a literal header without incremental indexing with index = 0 */
+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)));
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_begin(p, cur, end);
-}
-
-/* parse a literal header without incremental indexing; index < 15 */
-static grpc_error* parse_lithdr_notidx(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_value_string_with_indexed_key, finish_lithdr_notidx};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- p->index = (*cur) & 0xf;
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_begin(p, cur, end);
+}
+
+/* parse a literal header without incremental indexing; index < 15 */
+static grpc_error* parse_lithdr_notidx(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_value_string_with_indexed_key, finish_lithdr_notidx};
+ 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. */
- return parse_string_prefix(p, cur + 1, end);
-}
-
-/* parse a literal header without incremental indexing; index >= 15 */
-static grpc_error* parse_lithdr_notidx_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_string_prefix, parse_value_string_with_indexed_key,
- finish_lithdr_notidx};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- p->index = 0xf;
+ return parse_string_prefix(p, cur + 1, end);
+}
+
+/* parse a literal header without incremental indexing; index >= 15 */
+static grpc_error* parse_lithdr_notidx_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_string_prefix, parse_value_string_with_indexed_key,
+ finish_lithdr_notidx};
+ 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->parsing.value = &p->index;
- return parse_value0(p, cur + 1, end);
-}
-
-/* parse a literal header without incremental indexing; index == 0 */
-static grpc_error* parse_lithdr_notidx_v(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_key_string, parse_string_prefix,
- parse_value_string_with_literal_key, finish_lithdr_notidx_v};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- return parse_string_prefix(p, cur + 1, end);
-}
-
-/* finish a literal header that is never indexed */
-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();
+ p->parsing.value = &p->index;
+ return parse_value0(p, cur + 1, end);
+}
+
+/* parse a literal header without incremental indexing; index == 0 */
+static grpc_error* parse_lithdr_notidx_v(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_key_string, parse_string_prefix,
+ parse_value_string_with_literal_key, finish_lithdr_notidx_v};
+ p->dynamic_table_update_allowed = 0;
+ p->next_state = and_then;
+ return parse_string_prefix(p, cur + 1, end);
+}
+
+/* finish a literal header that is never indexed */
+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)));
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_begin(p, cur, end);
-}
-
-/* finish a literal header that is never indexed with an extra value */
-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();
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_begin(p, cur, end);
+}
+
+/* finish a literal header that is never indexed with an extra value */
+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)));
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_begin(p, cur, end);
-}
-
-/* parse a literal header that is never indexed; index < 15 */
-static grpc_error* parse_lithdr_nvridx(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_value_string_with_indexed_key, finish_lithdr_nvridx};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- p->index = (*cur) & 0xf;
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_begin(p, cur, end);
+}
+
+/* parse a literal header that is never indexed; index < 15 */
+static grpc_error* parse_lithdr_nvridx(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_value_string_with_indexed_key, finish_lithdr_nvridx};
+ 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. */
- return parse_string_prefix(p, cur + 1, end);
-}
-
-/* parse a literal header that is never indexed; index >= 15 */
-static grpc_error* parse_lithdr_nvridx_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_string_prefix, parse_value_string_with_indexed_key,
- finish_lithdr_nvridx};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- p->index = 0xf;
+ return parse_string_prefix(p, cur + 1, end);
+}
+
+/* parse a literal header that is never indexed; index >= 15 */
+static grpc_error* parse_lithdr_nvridx_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_string_prefix, parse_value_string_with_indexed_key,
+ finish_lithdr_nvridx};
+ 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->parsing.value = &p->index;
- return parse_value0(p, cur + 1, end);
-}
-
-/* parse a literal header that is never indexed; index == 0 */
-static grpc_error* parse_lithdr_nvridx_v(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- parse_key_string, parse_string_prefix,
- parse_value_string_with_literal_key, finish_lithdr_nvridx_v};
- p->dynamic_table_update_allowed = 0;
- p->next_state = and_then;
- return parse_string_prefix(p, cur + 1, end);
-}
-
-/* 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) {
+ p->parsing.value = &p->index;
+ return parse_value0(p, cur + 1, end);
+}
+
+/* parse a literal header that is never indexed; index == 0 */
+static grpc_error* parse_lithdr_nvridx_v(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ parse_key_string, parse_string_prefix,
+ parse_value_string_with_literal_key, finish_lithdr_nvridx_v};
+ p->dynamic_table_update_allowed = 0;
+ p->next_state = and_then;
+ return parse_string_prefix(p, cur + 1, end);
+}
+
+/* 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)) {
- gpr_log(GPR_INFO, "MAX TABLE SIZE: %d", p->index);
- }
- grpc_error* err =
- grpc_chttp2_hptbl_set_current_table_size(&p->table, p->index);
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_begin(p, cur, end);
-}
-
-/* parse a max table size change, max size < 15 */
-static grpc_error* parse_max_tbl_size(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (p->dynamic_table_update_allowed == 0) {
- return parse_error(
- p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "More than two max table size changes in a single frame"));
- }
- p->dynamic_table_update_allowed--;
- p->index = (*cur) & 0x1f;
+ gpr_log(GPR_INFO, "MAX TABLE SIZE: %d", p->index);
+ }
+ grpc_error* err =
+ grpc_chttp2_hptbl_set_current_table_size(&p->table, p->index);
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_begin(p, cur, end);
+}
+
+/* parse a max table size change, max size < 15 */
+static grpc_error* parse_max_tbl_size(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (p->dynamic_table_update_allowed == 0) {
+ return parse_error(
+ p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "More than two max table size changes in a single frame"));
+ }
+ p->dynamic_table_update_allowed--;
+ p->index = (*cur) & 0x1f;
p->md_for_index.payload = 0; /* Invalidate cached md when index changes. */
- return finish_max_tbl_size(p, cur + 1, end);
-}
-
-/* parse a max table size change, max size >= 15 */
-static grpc_error* parse_max_tbl_size_x(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur,
- const uint8_t* end) {
- static const grpc_chttp2_hpack_parser_state and_then[] = {
- finish_max_tbl_size};
- if (p->dynamic_table_update_allowed == 0) {
- return parse_error(
- p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "More than two max table size changes in a single frame"));
- }
- p->dynamic_table_update_allowed--;
- p->next_state = and_then;
- p->index = 0x1f;
+ return finish_max_tbl_size(p, cur + 1, end);
+}
+
+/* parse a max table size change, max size >= 15 */
+static grpc_error* parse_max_tbl_size_x(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur,
+ const uint8_t* end) {
+ static const grpc_chttp2_hpack_parser_state and_then[] = {
+ finish_max_tbl_size};
+ if (p->dynamic_table_update_allowed == 0) {
+ return parse_error(
+ p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "More than two max table size changes in a single frame"));
+ }
+ 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->parsing.value = &p->index;
- return parse_value0(p, cur + 1, end);
-}
-
-/* a parse error: jam the parse state into parse_error, and return error */
+ 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) {
- GPR_ASSERT(err != GRPC_ERROR_NONE);
- if (p->last_error == GRPC_ERROR_NONE) {
- p->last_error = GRPC_ERROR_REF(err);
- }
- p->state = still_parse_error;
- return err;
-}
-
-static grpc_error* still_parse_error(grpc_chttp2_hpack_parser* p,
+ GPR_ASSERT(err != GRPC_ERROR_NONE);
+ if (p->last_error == GRPC_ERROR_NONE) {
+ p->last_error = GRPC_ERROR_REF(err);
+ }
+ p->state = still_parse_error;
+ return err;
+}
+
+static grpc_error* still_parse_error(grpc_chttp2_hpack_parser* p,
const uint8_t* /*cur*/,
const uint8_t* /*end*/) {
- return GRPC_ERROR_REF(p->last_error);
-}
-
-static grpc_error* parse_illegal_op(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- GPR_ASSERT(cur != end);
+ return GRPC_ERROR_REF(p->last_error);
+}
+
+static grpc_error* parse_illegal_op(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ GPR_ASSERT(cur != end);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Illegal hpack op code ", *cur).c_str());
- return parse_error(p, cur, end, err);
-}
-
-/* parse the 1st byte of a varint into p->parsing.value
- no overflow is possible */
-static grpc_error* parse_value0(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- if (cur == end) {
- p->state = parse_value0;
- return GRPC_ERROR_NONE;
- }
-
- *p->parsing.value += (*cur) & 0x7f;
-
- if ((*cur) & 0x80) {
- return parse_value1(p, cur + 1, end);
- } else {
- return parse_next(p, cur + 1, end);
- }
-}
-
-/* parse the 2nd byte of a varint into p->parsing.value
- no overflow is possible */
-static grpc_error* parse_value1(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- if (cur == end) {
- p->state = parse_value1;
- return GRPC_ERROR_NONE;
- }
-
- *p->parsing.value += ((static_cast<uint32_t>(*cur)) & 0x7f) << 7;
-
- if ((*cur) & 0x80) {
- return parse_value2(p, cur + 1, end);
- } else {
- return parse_next(p, cur + 1, end);
- }
-}
-
-/* parse the 3rd byte of a varint into p->parsing.value
- no overflow is possible */
-static grpc_error* parse_value2(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- if (cur == end) {
- p->state = parse_value2;
- return GRPC_ERROR_NONE;
- }
-
- *p->parsing.value += ((static_cast<uint32_t>(*cur)) & 0x7f) << 14;
-
- if ((*cur) & 0x80) {
- return parse_value3(p, cur + 1, end);
- } else {
- return parse_next(p, cur + 1, end);
- }
-}
-
-/* parse the 4th byte of a varint into p->parsing.value
- no overflow is possible */
-static grpc_error* parse_value3(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- if (cur == end) {
- p->state = parse_value3;
- return GRPC_ERROR_NONE;
- }
-
- *p->parsing.value += ((static_cast<uint32_t>(*cur)) & 0x7f) << 21;
-
- if ((*cur) & 0x80) {
- return parse_value4(p, cur + 1, end);
- } else {
- return parse_next(p, cur + 1, end);
- }
-}
-
-/* parse the 5th byte of a varint into p->parsing.value
- depending on the byte, we may overflow, and care must be taken */
-static grpc_error* parse_value4(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- uint8_t c;
- uint32_t cur_value;
- uint32_t add_value;
-
- if (cur == end) {
- p->state = parse_value4;
- return GRPC_ERROR_NONE;
- }
-
- c = (*cur) & 0x7f;
- if (c > 0xf) {
- goto error;
- }
-
- cur_value = *p->parsing.value;
- add_value = (static_cast<uint32_t>(c)) << 28;
- if (add_value > 0xffffffffu - cur_value) {
- goto error;
- }
-
- *p->parsing.value = cur_value + add_value;
-
- if ((*cur) & 0x80) {
- return parse_value5up(p, cur + 1, end);
- } else {
- return parse_next(p, cur + 1, end);
- }
-
-error:
+ return parse_error(p, cur, end, err);
+}
+
+/* parse the 1st byte of a varint into p->parsing.value
+ no overflow is possible */
+static grpc_error* parse_value0(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_value0;
+ return GRPC_ERROR_NONE;
+ }
+
+ *p->parsing.value += (*cur) & 0x7f;
+
+ if ((*cur) & 0x80) {
+ return parse_value1(p, cur + 1, end);
+ } else {
+ return parse_next(p, cur + 1, end);
+ }
+}
+
+/* parse the 2nd byte of a varint into p->parsing.value
+ no overflow is possible */
+static grpc_error* parse_value1(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_value1;
+ return GRPC_ERROR_NONE;
+ }
+
+ *p->parsing.value += ((static_cast<uint32_t>(*cur)) & 0x7f) << 7;
+
+ if ((*cur) & 0x80) {
+ return parse_value2(p, cur + 1, end);
+ } else {
+ return parse_next(p, cur + 1, end);
+ }
+}
+
+/* parse the 3rd byte of a varint into p->parsing.value
+ no overflow is possible */
+static grpc_error* parse_value2(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_value2;
+ return GRPC_ERROR_NONE;
+ }
+
+ *p->parsing.value += ((static_cast<uint32_t>(*cur)) & 0x7f) << 14;
+
+ if ((*cur) & 0x80) {
+ return parse_value3(p, cur + 1, end);
+ } else {
+ return parse_next(p, cur + 1, end);
+ }
+}
+
+/* parse the 4th byte of a varint into p->parsing.value
+ no overflow is possible */
+static grpc_error* parse_value3(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_value3;
+ return GRPC_ERROR_NONE;
+ }
+
+ *p->parsing.value += ((static_cast<uint32_t>(*cur)) & 0x7f) << 21;
+
+ if ((*cur) & 0x80) {
+ return parse_value4(p, cur + 1, end);
+ } else {
+ return parse_next(p, cur + 1, end);
+ }
+}
+
+/* parse the 5th byte of a varint into p->parsing.value
+ depending on the byte, we may overflow, and care must be taken */
+static grpc_error* parse_value4(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ uint8_t c;
+ uint32_t cur_value;
+ uint32_t add_value;
+
+ if (cur == end) {
+ p->state = parse_value4;
+ return GRPC_ERROR_NONE;
+ }
+
+ c = (*cur) & 0x7f;
+ if (c > 0xf) {
+ goto error;
+ }
+
+ cur_value = *p->parsing.value;
+ add_value = (static_cast<uint32_t>(c)) << 28;
+ if (add_value > 0xffffffffu - cur_value) {
+ goto error;
+ }
+
+ *p->parsing.value = cur_value + add_value;
+
+ if ((*cur) & 0x80) {
+ return parse_value5up(p, cur + 1, end);
+ } else {
+ return parse_next(p, cur + 1, end);
+ }
+
+error:
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat(
"integer overflow in hpack integer decoding: have 0x%08x, "
"got byte 0x%02x on byte 5",
*p->parsing.value, *cur)
.c_str());
- return parse_error(p, cur, end, err);
-}
-
-/* parse any trailing bytes in a varint: it's possible to append an arbitrary
- number of 0x80's and not affect the value - a zero will terminate - and
- anything else will overflow */
-static grpc_error* parse_value5up(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- while (cur != end && *cur == 0x80) {
- ++cur;
- }
-
- if (cur == end) {
- p->state = parse_value5up;
- return GRPC_ERROR_NONE;
- }
-
- if (*cur == 0) {
- return parse_next(p, cur + 1, end);
- }
-
+ return parse_error(p, cur, end, err);
+}
+
+/* parse any trailing bytes in a varint: it's possible to append an arbitrary
+ number of 0x80's and not affect the value - a zero will terminate - and
+ anything else will overflow */
+static grpc_error* parse_value5up(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ while (cur != end && *cur == 0x80) {
+ ++cur;
+ }
+
+ if (cur == end) {
+ p->state = parse_value5up;
+ return GRPC_ERROR_NONE;
+ }
+
+ if (*cur == 0) {
+ return parse_next(p, cur + 1, end);
+ }
+
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat(
"integer overflow in hpack integer decoding: have 0x%08x, "
"got byte 0x%02x sometime after byte 5",
*p->parsing.value, *cur)
.c_str());
- return parse_error(p, cur, end, err);
-}
-
-/* parse a string prefix */
-static grpc_error* parse_string_prefix(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (cur == end) {
- p->state = parse_string_prefix;
- return GRPC_ERROR_NONE;
- }
-
- p->strlen = (*cur) & 0x7f;
- p->huff = (*cur) >> 7;
- if (p->strlen == 0x7f) {
- p->parsing.value = &p->strlen;
- return parse_value0(p, cur + 1, end);
- } else {
- return parse_next(p, cur + 1, end);
- }
-}
-
-/* append some bytes to a string */
-static void append_bytes(grpc_chttp2_hpack_parser_string* str,
- const uint8_t* data, size_t length) {
- if (length == 0) return;
- if (length + str->data.copied.length > str->data.copied.capacity) {
- GPR_ASSERT(str->data.copied.length + length <= UINT32_MAX);
- str->data.copied.capacity =
- static_cast<uint32_t>(str->data.copied.length + length);
- str->data.copied.str = static_cast<char*>(
- gpr_realloc(str->data.copied.str, str->data.copied.capacity));
- }
- memcpy(str->data.copied.str + str->data.copied.length, data, length);
- GPR_ASSERT(length <= UINT32_MAX - str->data.copied.length);
- str->data.copied.length += static_cast<uint32_t>(length);
-}
-
-static grpc_error* append_string(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- grpc_chttp2_hpack_parser_string* str = p->parsing.str;
- uint32_t bits;
- uint8_t decoded[3];
- switch (static_cast<binary_state>(p->binary)) {
- case NOT_BINARY:
- append_bytes(str, cur, static_cast<size_t>(end - cur));
- return GRPC_ERROR_NONE;
- case BINARY_BEGIN:
- if (cur == end) {
- p->binary = BINARY_BEGIN;
- return GRPC_ERROR_NONE;
- }
- if (*cur == 0) {
- /* 'true-binary' case */
- ++cur;
- p->binary = NOT_BINARY;
- GRPC_STATS_INC_HPACK_RECV_BINARY();
- append_bytes(str, cur, static_cast<size_t>(end - cur));
- return GRPC_ERROR_NONE;
- }
- GRPC_STATS_INC_HPACK_RECV_BINARY_BASE64();
- /* fallthrough */
- b64_byte0:
- case B64_BYTE0:
- if (cur == end) {
- p->binary = B64_BYTE0;
- return GRPC_ERROR_NONE;
- }
- bits = inverse_base64[*cur];
- ++cur;
- if (bits == 255)
- return parse_error(
- p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
- else if (bits == 64)
- goto b64_byte0;
- p->base64_buffer = bits << 18;
- /* fallthrough */
- b64_byte1:
- case B64_BYTE1:
- if (cur == end) {
- p->binary = B64_BYTE1;
- return GRPC_ERROR_NONE;
- }
- bits = inverse_base64[*cur];
- ++cur;
- if (bits == 255)
- return parse_error(
- p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
- else if (bits == 64)
- goto b64_byte1;
- p->base64_buffer |= bits << 12;
- /* fallthrough */
- b64_byte2:
- case B64_BYTE2:
- if (cur == end) {
- p->binary = B64_BYTE2;
- return GRPC_ERROR_NONE;
- }
- bits = inverse_base64[*cur];
- ++cur;
- if (bits == 255)
- return parse_error(
- p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
- else if (bits == 64)
- goto b64_byte2;
- p->base64_buffer |= bits << 6;
- /* fallthrough */
- b64_byte3:
- case B64_BYTE3:
- if (cur == end) {
- p->binary = B64_BYTE3;
- return GRPC_ERROR_NONE;
- }
- bits = inverse_base64[*cur];
- ++cur;
- if (bits == 255)
- return parse_error(
- p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
- else if (bits == 64)
- goto b64_byte3;
- p->base64_buffer |= bits;
- bits = p->base64_buffer;
- decoded[0] = static_cast<uint8_t>(bits >> 16);
- decoded[1] = static_cast<uint8_t>(bits >> 8);
- decoded[2] = static_cast<uint8_t>(bits);
- append_bytes(str, decoded, 3);
- goto b64_byte0;
- }
- GPR_UNREACHABLE_CODE(return parse_error(
- p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here")));
-}
-
-static grpc_error* finish_str(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- uint8_t decoded[2];
- uint32_t bits;
- grpc_chttp2_hpack_parser_string* str = p->parsing.str;
- switch (static_cast<binary_state>(p->binary)) {
- case NOT_BINARY:
- break;
- case BINARY_BEGIN:
- break;
- case B64_BYTE0:
- break;
- case B64_BYTE1:
- return parse_error(p, cur, end,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "illegal base64 encoding")); /* illegal encoding */
- case B64_BYTE2:
- bits = p->base64_buffer;
- if (bits & 0xffff) {
+ return parse_error(p, cur, end, err);
+}
+
+/* parse a string prefix */
+static grpc_error* parse_string_prefix(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (cur == end) {
+ p->state = parse_string_prefix;
+ return GRPC_ERROR_NONE;
+ }
+
+ p->strlen = (*cur) & 0x7f;
+ p->huff = (*cur) >> 7;
+ if (p->strlen == 0x7f) {
+ p->parsing.value = &p->strlen;
+ return parse_value0(p, cur + 1, end);
+ } else {
+ return parse_next(p, cur + 1, end);
+ }
+}
+
+/* append some bytes to a string */
+static void append_bytes(grpc_chttp2_hpack_parser_string* str,
+ const uint8_t* data, size_t length) {
+ if (length == 0) return;
+ if (length + str->data.copied.length > str->data.copied.capacity) {
+ GPR_ASSERT(str->data.copied.length + length <= UINT32_MAX);
+ str->data.copied.capacity =
+ static_cast<uint32_t>(str->data.copied.length + length);
+ str->data.copied.str = static_cast<char*>(
+ gpr_realloc(str->data.copied.str, str->data.copied.capacity));
+ }
+ memcpy(str->data.copied.str + str->data.copied.length, data, length);
+ GPR_ASSERT(length <= UINT32_MAX - str->data.copied.length);
+ str->data.copied.length += static_cast<uint32_t>(length);
+}
+
+static grpc_error* append_string(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ grpc_chttp2_hpack_parser_string* str = p->parsing.str;
+ uint32_t bits;
+ uint8_t decoded[3];
+ switch (static_cast<binary_state>(p->binary)) {
+ case NOT_BINARY:
+ append_bytes(str, cur, static_cast<size_t>(end - cur));
+ return GRPC_ERROR_NONE;
+ case BINARY_BEGIN:
+ if (cur == end) {
+ p->binary = BINARY_BEGIN;
+ return GRPC_ERROR_NONE;
+ }
+ if (*cur == 0) {
+ /* 'true-binary' case */
+ ++cur;
+ p->binary = NOT_BINARY;
+ GRPC_STATS_INC_HPACK_RECV_BINARY();
+ append_bytes(str, cur, static_cast<size_t>(end - cur));
+ return GRPC_ERROR_NONE;
+ }
+ GRPC_STATS_INC_HPACK_RECV_BINARY_BASE64();
+ /* fallthrough */
+ b64_byte0:
+ case B64_BYTE0:
+ if (cur == end) {
+ p->binary = B64_BYTE0;
+ return GRPC_ERROR_NONE;
+ }
+ bits = inverse_base64[*cur];
+ ++cur;
+ if (bits == 255)
+ return parse_error(
+ p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
+ else if (bits == 64)
+ goto b64_byte0;
+ p->base64_buffer = bits << 18;
+ /* fallthrough */
+ b64_byte1:
+ case B64_BYTE1:
+ if (cur == end) {
+ p->binary = B64_BYTE1;
+ return GRPC_ERROR_NONE;
+ }
+ bits = inverse_base64[*cur];
+ ++cur;
+ if (bits == 255)
+ return parse_error(
+ p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
+ else if (bits == 64)
+ goto b64_byte1;
+ p->base64_buffer |= bits << 12;
+ /* fallthrough */
+ b64_byte2:
+ case B64_BYTE2:
+ if (cur == end) {
+ p->binary = B64_BYTE2;
+ return GRPC_ERROR_NONE;
+ }
+ bits = inverse_base64[*cur];
+ ++cur;
+ if (bits == 255)
+ return parse_error(
+ p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
+ else if (bits == 64)
+ goto b64_byte2;
+ p->base64_buffer |= bits << 6;
+ /* fallthrough */
+ b64_byte3:
+ case B64_BYTE3:
+ if (cur == end) {
+ p->binary = B64_BYTE3;
+ return GRPC_ERROR_NONE;
+ }
+ bits = inverse_base64[*cur];
+ ++cur;
+ if (bits == 255)
+ return parse_error(
+ p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal base64 character"));
+ else if (bits == 64)
+ goto b64_byte3;
+ p->base64_buffer |= bits;
+ bits = p->base64_buffer;
+ decoded[0] = static_cast<uint8_t>(bits >> 16);
+ decoded[1] = static_cast<uint8_t>(bits >> 8);
+ decoded[2] = static_cast<uint8_t>(bits);
+ append_bytes(str, decoded, 3);
+ goto b64_byte0;
+ }
+ GPR_UNREACHABLE_CODE(return parse_error(
+ p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here")));
+}
+
+static grpc_error* finish_str(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ uint8_t decoded[2];
+ uint32_t bits;
+ grpc_chttp2_hpack_parser_string* str = p->parsing.str;
+ switch (static_cast<binary_state>(p->binary)) {
+ case NOT_BINARY:
+ break;
+ case BINARY_BEGIN:
+ break;
+ case B64_BYTE0:
+ break;
+ case B64_BYTE1:
+ return parse_error(p, cur, end,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "illegal base64 encoding")); /* illegal encoding */
+ case B64_BYTE2:
+ bits = p->base64_buffer;
+ if (bits & 0xffff) {
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("trailing bits in base64 encoding: 0x%04x",
bits & 0xffff)
.c_str());
- return parse_error(p, cur, end, err);
- }
- decoded[0] = static_cast<uint8_t>(bits >> 16);
- append_bytes(str, decoded, 1);
- break;
- case B64_BYTE3:
- bits = p->base64_buffer;
- if (bits & 0xff) {
+ return parse_error(p, cur, end, err);
+ }
+ decoded[0] = static_cast<uint8_t>(bits >> 16);
+ append_bytes(str, decoded, 1);
+ break;
+ case B64_BYTE3:
+ bits = p->base64_buffer;
+ if (bits & 0xff) {
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("trailing bits in base64 encoding: 0x%02x",
bits & 0xff)
.c_str());
- return parse_error(p, cur, end, err);
- }
- decoded[0] = static_cast<uint8_t>(bits >> 16);
- decoded[1] = static_cast<uint8_t>(bits >> 8);
- append_bytes(str, decoded, 2);
- break;
- }
- return GRPC_ERROR_NONE;
-}
-
-/* decode a nibble from a huffman encoded stream */
-static grpc_error* huff_nibble(grpc_chttp2_hpack_parser* p, uint8_t nibble) {
- int16_t emit = emit_sub_tbl[16 * emit_tbl[p->huff_state] + nibble];
- int16_t next = next_sub_tbl[16 * next_tbl[p->huff_state] + nibble];
- if (emit != -1) {
- if (emit >= 0 && emit < 256) {
- uint8_t c = static_cast<uint8_t>(emit);
- grpc_error* err = append_string(p, &c, (&c) + 1);
- if (err != GRPC_ERROR_NONE) return err;
- } else {
- assert(emit == 256);
- }
- }
- p->huff_state = next;
- return GRPC_ERROR_NONE;
-}
-
-/* decode full bytes from a huffman encoded stream */
-static grpc_error* add_huff_bytes(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- for (; cur != end; ++cur) {
- grpc_error* err = huff_nibble(p, *cur >> 4);
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- err = huff_nibble(p, *cur & 0xf);
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- }
- return GRPC_ERROR_NONE;
-}
-
-/* decode some string bytes based on the current decoding mode
- (huffman or not) */
-static grpc_error* add_str_bytes(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- if (p->huff) {
- return add_huff_bytes(p, cur, end);
- } else {
- return append_string(p, cur, end);
- }
-}
-
-/* parse a string - tries to do large chunks at a time */
-static grpc_error* parse_string(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
- const uint8_t* end) {
- size_t remaining = p->strlen - p->strgot;
- size_t given = static_cast<size_t>(end - cur);
- if (remaining <= given) {
- grpc_error* err = add_str_bytes(p, cur, cur + remaining);
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- err = finish_str(p, cur + remaining, end);
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_next(p, cur + remaining, end);
- } else {
- grpc_error* err = add_str_bytes(p, cur, cur + given);
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- GPR_ASSERT(given <= UINT32_MAX - p->strgot);
- p->strgot += static_cast<uint32_t>(given);
- p->state = parse_string;
- return GRPC_ERROR_NONE;
- }
-}
-
-/* begin parsing a string - performs setup, calls parse_string */
-static grpc_error* begin_parse_string(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end,
- uint8_t binary,
- grpc_chttp2_hpack_parser_string* str) {
- if (!p->huff && binary == NOT_BINARY &&
+ return parse_error(p, cur, end, err);
+ }
+ decoded[0] = static_cast<uint8_t>(bits >> 16);
+ decoded[1] = static_cast<uint8_t>(bits >> 8);
+ append_bytes(str, decoded, 2);
+ break;
+ }
+ return GRPC_ERROR_NONE;
+}
+
+/* decode a nibble from a huffman encoded stream */
+static grpc_error* huff_nibble(grpc_chttp2_hpack_parser* p, uint8_t nibble) {
+ int16_t emit = emit_sub_tbl[16 * emit_tbl[p->huff_state] + nibble];
+ int16_t next = next_sub_tbl[16 * next_tbl[p->huff_state] + nibble];
+ if (emit != -1) {
+ if (emit >= 0 && emit < 256) {
+ uint8_t c = static_cast<uint8_t>(emit);
+ grpc_error* err = append_string(p, &c, (&c) + 1);
+ if (err != GRPC_ERROR_NONE) return err;
+ } else {
+ assert(emit == 256);
+ }
+ }
+ p->huff_state = next;
+ return GRPC_ERROR_NONE;
+}
+
+/* decode full bytes from a huffman encoded stream */
+static grpc_error* add_huff_bytes(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ for (; cur != end; ++cur) {
+ grpc_error* err = huff_nibble(p, *cur >> 4);
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ err = huff_nibble(p, *cur & 0xf);
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ }
+ return GRPC_ERROR_NONE;
+}
+
+/* decode some string bytes based on the current decoding mode
+ (huffman or not) */
+static grpc_error* add_str_bytes(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ if (p->huff) {
+ return add_huff_bytes(p, cur, end);
+ } else {
+ return append_string(p, cur, end);
+ }
+}
+
+/* parse a string - tries to do large chunks at a time */
+static grpc_error* parse_string(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
+ const uint8_t* end) {
+ size_t remaining = p->strlen - p->strgot;
+ size_t given = static_cast<size_t>(end - cur);
+ if (remaining <= given) {
+ grpc_error* err = add_str_bytes(p, cur, cur + remaining);
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ err = finish_str(p, cur + remaining, end);
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_next(p, cur + remaining, end);
+ } else {
+ grpc_error* err = add_str_bytes(p, cur, cur + given);
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ GPR_ASSERT(given <= UINT32_MAX - p->strgot);
+ p->strgot += static_cast<uint32_t>(given);
+ p->state = parse_string;
+ return GRPC_ERROR_NONE;
+ }
+}
+
+/* begin parsing a string - performs setup, calls parse_string */
+static grpc_error* begin_parse_string(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end,
+ uint8_t binary,
+ grpc_chttp2_hpack_parser_string* str) {
+ if (!p->huff && binary == NOT_BINARY &&
static_cast<uint32_t>(end - cur) >= p->strlen &&
- p->current_slice_refcount != nullptr) {
- GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED();
- str->copied = false;
- str->data.referenced.refcount = p->current_slice_refcount;
- str->data.referenced.data.refcounted.bytes = const_cast<uint8_t*>(cur);
- str->data.referenced.data.refcounted.length = p->strlen;
- grpc_slice_ref_internal(str->data.referenced);
- return parse_next(p, cur + p->strlen, end);
- }
- p->strgot = 0;
- str->copied = true;
- str->data.copied.length = 0;
- p->parsing.str = str;
- p->huff_state = 0;
- p->binary = binary;
- switch (p->binary) {
- case NOT_BINARY:
- if (p->huff) {
- GRPC_STATS_INC_HPACK_RECV_HUFFMAN();
- } else {
- GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED();
- }
- break;
- case BINARY_BEGIN:
- /* stats incremented later: don't know true binary or not */
- break;
- default:
- abort();
- }
- return parse_string(p, cur, end);
-}
-
-/* parse the key string */
-static grpc_error* parse_key_string(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end) {
- return begin_parse_string(p, cur, end, NOT_BINARY, &p->key);
-}
-
-/* check if a key represents a binary header or not */
-
-static bool is_binary_literal_header(grpc_chttp2_hpack_parser* p) {
+ p->current_slice_refcount != nullptr) {
+ GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED();
+ str->copied = false;
+ str->data.referenced.refcount = p->current_slice_refcount;
+ str->data.referenced.data.refcounted.bytes = const_cast<uint8_t*>(cur);
+ str->data.referenced.data.refcounted.length = p->strlen;
+ grpc_slice_ref_internal(str->data.referenced);
+ return parse_next(p, cur + p->strlen, end);
+ }
+ p->strgot = 0;
+ str->copied = true;
+ str->data.copied.length = 0;
+ p->parsing.str = str;
+ p->huff_state = 0;
+ p->binary = binary;
+ switch (p->binary) {
+ case NOT_BINARY:
+ if (p->huff) {
+ GRPC_STATS_INC_HPACK_RECV_HUFFMAN();
+ } else {
+ GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED();
+ }
+ break;
+ case BINARY_BEGIN:
+ /* stats incremented later: don't know true binary or not */
+ break;
+ default:
+ abort();
+ }
+ return parse_string(p, cur, end);
+}
+
+/* parse the key string */
+static grpc_error* parse_key_string(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end) {
+ return begin_parse_string(p, cur, end, NOT_BINARY, &p->key);
+}
+
+/* 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,
@@ -1530,9 +1530,9 @@ static bool is_binary_literal_header(grpc_chttp2_hpack_parser* p) {
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);
-}
-
+ : 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(). */
@@ -1550,12 +1550,12 @@ static void set_precomputed_md_idx(grpc_chttp2_hpack_parser* p,
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);
+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);
- }
+ }
/* 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
@@ -1566,30 +1566,30 @@ static grpc_error* is_binary_indexed_header(grpc_chttp2_hpack_parser* p,
* 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;
-}
-
-/* parse the value string */
-static grpc_error* parse_value_string(grpc_chttp2_hpack_parser* p,
- const uint8_t* cur, const uint8_t* end,
- bool is_binary) {
- return begin_parse_string(p, cur, end, is_binary ? BINARY_BEGIN : NOT_BINARY,
- &p->value);
-}
-
-static grpc_error* parse_value_string_with_indexed_key(
- grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end) {
- bool is_binary = false;
- grpc_error* err = is_binary_indexed_header(p, &is_binary);
- if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
- return parse_value_string(p, cur, end, is_binary);
-}
-
-static grpc_error* parse_value_string_with_literal_key(
- grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end) {
- return parse_value_string(p, cur, end, is_binary_literal_header(p));
-}
-
+ return GRPC_ERROR_NONE;
+}
+
+/* parse the value string */
+static grpc_error* parse_value_string(grpc_chttp2_hpack_parser* p,
+ const uint8_t* cur, const uint8_t* end,
+ bool is_binary) {
+ return begin_parse_string(p, cur, end, is_binary ? BINARY_BEGIN : NOT_BINARY,
+ &p->value);
+}
+
+static grpc_error* parse_value_string_with_indexed_key(
+ grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end) {
+ bool is_binary = false;
+ grpc_error* err = is_binary_indexed_header(p, &is_binary);
+ if (err != GRPC_ERROR_NONE) return parse_error(p, cur, end, err);
+ return parse_value_string(p, cur, end, is_binary);
+}
+
+static grpc_error* parse_value_string_with_literal_key(
+ grpc_chttp2_hpack_parser* p, const uint8_t* cur, const uint8_t* end) {
+ 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) {
@@ -1597,20 +1597,20 @@ static grpc_error* on_header_uninitialized(void* /*user_data*/,
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) {
+/* PUBLIC INTERFACE */
+
+void grpc_chttp2_hpack_parser_init(grpc_chttp2_hpack_parser* p) {
p->on_header = on_header_uninitialized;
- p->on_header_user_data = nullptr;
- p->state = parse_begin;
- p->key.data.referenced = grpc_empty_slice();
- p->key.data.copied.str = nullptr;
- p->key.data.copied.capacity = 0;
- p->key.data.copied.length = 0;
- p->value.data.referenced = grpc_empty_slice();
- p->value.data.copied.str = nullptr;
- p->value.data.copied.capacity = 0;
- p->value.data.copied.length = 0;
+ p->on_header_user_data = nullptr;
+ p->state = parse_begin;
+ p->key.data.referenced = grpc_empty_slice();
+ p->key.data.copied.str = nullptr;
+ p->key.data.copied.capacity = 0;
+ p->key.data.copied.length = 0;
+ p->value.data.referenced = grpc_empty_slice();
+ 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,
@@ -1623,135 +1623,135 @@ void grpc_chttp2_hpack_parser_init(grpc_chttp2_hpack_parser* p) {
* 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;
-}
-
-void grpc_chttp2_hpack_parser_set_has_priority(grpc_chttp2_hpack_parser* p) {
- p->after_prioritization = p->state;
- p->state = parse_stream_dep0;
-}
-
-void grpc_chttp2_hpack_parser_destroy(grpc_chttp2_hpack_parser* p) {
- grpc_chttp2_hptbl_destroy(&p->table);
- GRPC_ERROR_UNREF(p->last_error);
- grpc_slice_unref_internal(p->key.data.referenced);
- grpc_slice_unref_internal(p->value.data.referenced);
- gpr_free(p->key.data.copied.str);
- gpr_free(p->value.data.copied.str);
-}
-
-grpc_error* grpc_chttp2_hpack_parser_parse(grpc_chttp2_hpack_parser* p,
+ p->dynamic_table_update_allowed = 2;
+ p->last_error = GRPC_ERROR_NONE;
+}
+
+void grpc_chttp2_hpack_parser_set_has_priority(grpc_chttp2_hpack_parser* p) {
+ p->after_prioritization = p->state;
+ p->state = parse_stream_dep0;
+}
+
+void grpc_chttp2_hpack_parser_destroy(grpc_chttp2_hpack_parser* p) {
+ grpc_chttp2_hptbl_destroy(&p->table);
+ GRPC_ERROR_UNREF(p->last_error);
+ grpc_slice_unref_internal(p->key.data.referenced);
+ grpc_slice_unref_internal(p->value.data.referenced);
+ gpr_free(p->key.data.copied.str);
+ gpr_free(p->value.data.copied.str);
+}
+
+grpc_error* grpc_chttp2_hpack_parser_parse(grpc_chttp2_hpack_parser* p,
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;
+/* 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);
- grpc_error* error = GRPC_ERROR_NONE;
- while (start != end && error == GRPC_ERROR_NONE) {
+ 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);
- error = p->state(p, start, target);
- start = target;
- }
- p->current_slice_refcount = nullptr;
- return error;
-}
-
-typedef void (*maybe_complete_func_type)(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-static const maybe_complete_func_type maybe_complete_funcs[] = {
- grpc_chttp2_maybe_complete_recv_initial_metadata,
- grpc_chttp2_maybe_complete_recv_trailing_metadata};
-
+ error = p->state(p, start, target);
+ start = target;
+ }
+ p->current_slice_refcount = nullptr;
+ return error;
+}
+
+typedef void (*maybe_complete_func_type)(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+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*/) {
- grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(sp);
- grpc_chttp2_transport* t = s->t;
- if (!s->write_closed) {
+ 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_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");
-}
-
+ 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*/,
- grpc_chttp2_stream* s,
- grpc_metadata_batch* initial_metadata) {
- if (initial_metadata->idx.named.content_encoding == nullptr ||
- grpc_stream_compression_method_parse(
- GRPC_MDVALUE(initial_metadata->idx.named.content_encoding->md), false,
- &s->stream_decompression_method) == 0) {
- s->stream_decompression_method =
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS;
- }
+ grpc_chttp2_stream* s,
+ grpc_metadata_batch* initial_metadata) {
+ if (initial_metadata->idx.named.content_encoding == nullptr ||
+ grpc_stream_compression_method_parse(
+ GRPC_MDVALUE(initial_metadata->idx.named.content_encoding->md), false,
+ &s->stream_decompression_method) == 0) {
+ 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);
}
-}
-
-grpc_error* grpc_chttp2_header_parser_parse(void* hpack_parser,
- grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
+}
+
+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) {
GPR_TIMER_SCOPE("grpc_chttp2_header_parser_parse", 0);
- grpc_chttp2_hpack_parser* parser =
- static_cast<grpc_chttp2_hpack_parser*>(hpack_parser);
- if (s != nullptr) {
- s->stats.incoming.header_bytes += GRPC_SLICE_LENGTH(slice);
- }
- grpc_error* error = grpc_chttp2_hpack_parser_parse(parser, slice);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
- if (is_last) {
- if (parser->is_boundary && parser->state != parse_begin) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "end of header frame not aligned with a hpack record boundary");
- }
- /* need to check for null stream: this can occur if we receive an invalid
- stream id on a header */
- if (s != nullptr) {
- if (parser->is_boundary) {
- if (s->header_frames_received == GPR_ARRAY_SIZE(s->metadata_buffer)) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Too many trailer frames");
- }
- /* Process stream compression md element if it exists */
- if (s->header_frames_received ==
- 0) { /* Only acts on initial metadata */
- parse_stream_compression_md(t, s, &s->metadata_buffer[0].batch);
- }
- s->published_metadata[s->header_frames_received] =
- GRPC_METADATA_PUBLISHED_FROM_WIRE;
- maybe_complete_funcs[s->header_frames_received](t, s);
- s->header_frames_received++;
- }
- if (parser->is_eof) {
- if (t->is_client && !s->write_closed) {
- /* server eof ==> complete closure; we may need to forcefully close
- the stream. Wait until the combiner lock is ready to be released
- 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");
+ grpc_chttp2_hpack_parser* parser =
+ static_cast<grpc_chttp2_hpack_parser*>(hpack_parser);
+ if (s != nullptr) {
+ s->stats.incoming.header_bytes += GRPC_SLICE_LENGTH(slice);
+ }
+ grpc_error* error = grpc_chttp2_hpack_parser_parse(parser, slice);
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+ if (is_last) {
+ if (parser->is_boundary && parser->state != parse_begin) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "end of header frame not aligned with a hpack record boundary");
+ }
+ /* need to check for null stream: this can occur if we receive an invalid
+ stream id on a header */
+ if (s != nullptr) {
+ if (parser->is_boundary) {
+ if (s->header_frames_received == GPR_ARRAY_SIZE(s->metadata_buffer)) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Too many trailer frames");
+ }
+ /* Process stream compression md element if it exists */
+ if (s->header_frames_received ==
+ 0) { /* Only acts on initial metadata */
+ parse_stream_compression_md(t, s, &s->metadata_buffer[0].batch);
+ }
+ s->published_metadata[s->header_frames_received] =
+ GRPC_METADATA_PUBLISHED_FROM_WIRE;
+ maybe_complete_funcs[s->header_frames_received](t, s);
+ s->header_frames_received++;
+ }
+ if (parser->is_eof) {
+ if (t->is_client && !s->write_closed) {
+ /* server eof ==> complete closure; we may need to forcefully close
+ the stream. Wait until the combiner lock is ready to be released
+ 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),
- GRPC_ERROR_NONE);
- }
- grpc_chttp2_mark_stream_closed(t, s, true, false, GRPC_ERROR_NONE);
- }
- }
+ GRPC_ERROR_NONE);
+ }
+ grpc_chttp2_mark_stream_closed(t, s, true, false, GRPC_ERROR_NONE);
+ }
+ }
parser->on_header = on_header_uninitialized;
- parser->on_header_user_data = nullptr;
- parser->is_boundary = 0xde;
- parser->is_eof = 0xde;
- parser->dynamic_table_update_allowed = 2;
- }
- return GRPC_ERROR_NONE;
-}
+ parser->on_header_user_data = nullptr;
+ parser->is_boundary = 0xde;
+ parser->is_eof = 0xde;
+ parser->dynamic_table_update_allowed = 2;
+ }
+ return GRPC_ERROR_NONE;
+}
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 1b859c4d7c6..62f7045dd5b 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_HPACK_PARSER_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_PARSER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stddef.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
@@ -29,39 +29,39 @@
typedef struct grpc_chttp2_hpack_parser grpc_chttp2_hpack_parser;
-typedef grpc_error* (*grpc_chttp2_hpack_parser_state)(
- grpc_chttp2_hpack_parser* p, const uint8_t* beg, const uint8_t* end);
+typedef grpc_error* (*grpc_chttp2_hpack_parser_state)(
+ grpc_chttp2_hpack_parser* p, const uint8_t* beg, const uint8_t* end);
struct grpc_chttp2_hpack_parser_string {
- bool copied;
- struct {
- grpc_slice referenced;
- struct {
- char* str;
- uint32_t length;
- uint32_t capacity;
- } copied;
- } data;
+ bool copied;
+ struct {
+ grpc_slice referenced;
+ struct {
+ char* str;
+ uint32_t length;
+ uint32_t capacity;
+ } copied;
+ } data;
};
struct grpc_chttp2_hpack_parser {
/* user specified callback for each header output */
grpc_error* (*on_header)(void* user_data, grpc_mdelem md);
- void* on_header_user_data;
+ void* on_header_user_data;
- grpc_error* last_error;
+ grpc_error* last_error;
/* current parse state - or a function that implements it */
grpc_chttp2_hpack_parser_state state;
/* future states dependent on the opening op code */
- const grpc_chttp2_hpack_parser_state* next_state;
+ const grpc_chttp2_hpack_parser_state* next_state;
/* what to do after skipping prioritization data */
grpc_chttp2_hpack_parser_state after_prioritization;
- /* the refcount of the slice that we're currently parsing */
- grpc_slice_refcount* current_slice_refcount;
+ /* the refcount of the slice that we're currently parsing */
+ grpc_slice_refcount* current_slice_refcount;
/* the value we're currently parsing */
union {
- uint32_t* value;
- grpc_chttp2_hpack_parser_string* str;
+ uint32_t* value;
+ grpc_chttp2_hpack_parser_string* str;
} parsing;
/* string parameters for each chunk */
grpc_chttp2_hpack_parser_string key;
@@ -98,19 +98,19 @@ struct grpc_chttp2_hpack_parser {
grpc_chttp2_hptbl table;
};
-void grpc_chttp2_hpack_parser_init(grpc_chttp2_hpack_parser* p);
-void grpc_chttp2_hpack_parser_destroy(grpc_chttp2_hpack_parser* p);
+void grpc_chttp2_hpack_parser_init(grpc_chttp2_hpack_parser* p);
+void grpc_chttp2_hpack_parser_destroy(grpc_chttp2_hpack_parser* p);
-void grpc_chttp2_hpack_parser_set_has_priority(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,
+grpc_error* grpc_chttp2_hpack_parser_parse(grpc_chttp2_hpack_parser* p,
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,
+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);
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 812d17cb457..d888bc049b5 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
@@ -1,68 +1,68 @@
-/*
- *
- * 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/transport/chttp2/transport/hpack_table.h"
-
-#include <assert.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/transport/chttp2/transport/hpack_table.h"
+
+#include <assert.h>
+#include <string.h>
+
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gpr/murmur_hash.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#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/transport/static_metadata.h"
-
-extern grpc_core::TraceFlag grpc_http_trace;
-
-void grpc_chttp2_hptbl_destroy(grpc_chttp2_hptbl* tbl) {
- size_t i;
- for (i = 0; i < tbl->num_ents; i++) {
- GRPC_MDELEM_UNREF(tbl->ents[(tbl->first_ent + i) % tbl->cap_entries]);
- }
- gpr_free(tbl->ents);
+
+extern grpc_core::TraceFlag grpc_http_trace;
+
+void grpc_chttp2_hptbl_destroy(grpc_chttp2_hptbl* tbl) {
+ size_t i;
+ for (i = 0; i < tbl->num_ents; i++) {
+ GRPC_MDELEM_UNREF(tbl->ents[(tbl->first_ent + i) % tbl->cap_entries]);
+ }
+ gpr_free(tbl->ents);
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 */
- 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;
+ 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;
- }
- /* Invalid entry: return error */
- return GRPC_MDNULL;
-}
-
+ }
+ /* 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);
@@ -73,153 +73,153 @@ grpc_mdelem grpc_chttp2_hptbl_lookup_ref_dynamic_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];
- size_t elem_bytes = GRPC_SLICE_LENGTH(GRPC_MDKEY(first_ent)) +
- GRPC_SLICE_LENGTH(GRPC_MDVALUE(first_ent)) +
- GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
- GPR_ASSERT(elem_bytes <= tbl->mem_used);
- tbl->mem_used -= static_cast<uint32_t>(elem_bytes);
- tbl->first_ent = ((tbl->first_ent + 1) % tbl->cap_entries);
- tbl->num_ents--;
- GRPC_MDELEM_UNREF(first_ent);
-}
-
-static void rebuild_ents(grpc_chttp2_hptbl* tbl, uint32_t new_cap) {
- grpc_mdelem* ents =
- static_cast<grpc_mdelem*>(gpr_malloc(sizeof(*ents) * new_cap));
- uint32_t i;
-
- for (i = 0; i < tbl->num_ents; i++) {
- ents[i] = tbl->ents[(tbl->first_ent + i) % tbl->cap_entries];
- }
- gpr_free(tbl->ents);
- tbl->ents = ents;
- tbl->cap_entries = new_cap;
- tbl->first_ent = 0;
-}
-
-void grpc_chttp2_hptbl_set_max_bytes(grpc_chttp2_hptbl* tbl,
- uint32_t max_bytes) {
- if (tbl->max_bytes == max_bytes) {
- return;
- }
+/* Evict one element from the table */
+static void evict1(grpc_chttp2_hptbl* tbl) {
+ grpc_mdelem first_ent = tbl->ents[tbl->first_ent];
+ size_t elem_bytes = GRPC_SLICE_LENGTH(GRPC_MDKEY(first_ent)) +
+ GRPC_SLICE_LENGTH(GRPC_MDVALUE(first_ent)) +
+ GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
+ GPR_ASSERT(elem_bytes <= tbl->mem_used);
+ tbl->mem_used -= static_cast<uint32_t>(elem_bytes);
+ tbl->first_ent = ((tbl->first_ent + 1) % tbl->cap_entries);
+ tbl->num_ents--;
+ GRPC_MDELEM_UNREF(first_ent);
+}
+
+static void rebuild_ents(grpc_chttp2_hptbl* tbl, uint32_t new_cap) {
+ grpc_mdelem* ents =
+ static_cast<grpc_mdelem*>(gpr_malloc(sizeof(*ents) * new_cap));
+ uint32_t i;
+
+ for (i = 0; i < tbl->num_ents; i++) {
+ ents[i] = tbl->ents[(tbl->first_ent + i) % tbl->cap_entries];
+ }
+ gpr_free(tbl->ents);
+ tbl->ents = ents;
+ tbl->cap_entries = new_cap;
+ tbl->first_ent = 0;
+}
+
+void grpc_chttp2_hptbl_set_max_bytes(grpc_chttp2_hptbl* tbl,
+ uint32_t max_bytes) {
+ if (tbl->max_bytes == max_bytes) {
+ return;
+ }
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) {
- evict1(tbl);
- }
- tbl->max_bytes = max_bytes;
-}
-
-grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_chttp2_hptbl* tbl,
- uint32_t bytes) {
- if (tbl->current_table_bytes == bytes) {
- return GRPC_ERROR_NONE;
- }
- if (bytes > tbl->max_bytes) {
+ gpr_log(GPR_INFO, "Update hpack parser max size to %d", max_bytes);
+ }
+ while (tbl->mem_used > max_bytes) {
+ evict1(tbl);
+ }
+ tbl->max_bytes = max_bytes;
+}
+
+grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_chttp2_hptbl* tbl,
+ uint32_t bytes) {
+ if (tbl->current_table_bytes == bytes) {
+ return GRPC_ERROR_NONE;
+ }
+ if (bytes > tbl->max_bytes) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat(
"Attempt to make hpack table %d bytes when max is %d bytes", bytes,
tbl->max_bytes)
.c_str());
- }
+ }
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;
+ 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);
- 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) {
- uint32_t new_cap = GPR_MAX(tbl->max_entries, 16u);
- if (new_cap != tbl->cap_entries) {
- rebuild_ents(tbl, new_cap);
- }
- }
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_chttp2_hptbl_add(grpc_chttp2_hptbl* tbl, grpc_mdelem md) {
- /* determine how many bytes of buffer this entry represents */
- size_t elem_bytes = GRPC_SLICE_LENGTH(GRPC_MDKEY(md)) +
- GRPC_SLICE_LENGTH(GRPC_MDVALUE(md)) +
- GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
-
- if (tbl->current_table_bytes > tbl->max_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) {
+ uint32_t new_cap = GPR_MAX(tbl->max_entries, 16u);
+ if (new_cap != tbl->cap_entries) {
+ rebuild_ents(tbl, new_cap);
+ }
+ }
+ return GRPC_ERROR_NONE;
+}
+
+grpc_error* grpc_chttp2_hptbl_add(grpc_chttp2_hptbl* tbl, grpc_mdelem md) {
+ /* determine how many bytes of buffer this entry represents */
+ size_t elem_bytes = GRPC_SLICE_LENGTH(GRPC_MDKEY(md)) +
+ GRPC_SLICE_LENGTH(GRPC_MDVALUE(md)) +
+ GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
+
+ if (tbl->current_table_bytes > tbl->max_bytes) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat(
"HPACK max table size reduced to %d but not reflected by hpack "
"stream (still at %d)",
tbl->max_bytes, tbl->current_table_bytes)
.c_str());
- }
-
- /* we can't add elements bigger than the max table size */
- if (elem_bytes > tbl->current_table_bytes) {
- /* HPACK draft 10 section 4.4 states:
- * If the size of the new entry is less than or equal to the maximum
- * size, that entry is added to the table. It is not an error to
- * attempt to add an entry that is larger than the maximum size; an
- * attempt to add an entry larger than the entire table causes
- * the table
- * to be emptied of all existing entries, and results in an
- * empty table.
- */
- while (tbl->num_ents) {
- evict1(tbl);
- }
- return GRPC_ERROR_NONE;
- }
-
- /* evict entries to ensure no overflow */
- while (elem_bytes >
- static_cast<size_t>(tbl->current_table_bytes) - tbl->mem_used) {
- evict1(tbl);
- }
-
- /* copy the finalized entry in */
- tbl->ents[(tbl->first_ent + tbl->num_ents) % tbl->cap_entries] =
- GRPC_MDELEM_REF(md);
-
- /* update accounting values */
- tbl->num_ents++;
- tbl->mem_used += static_cast<uint32_t>(elem_bytes);
- return GRPC_ERROR_NONE;
-}
-
-grpc_chttp2_hptbl_find_result grpc_chttp2_hptbl_find(
- const grpc_chttp2_hptbl* tbl, grpc_mdelem md) {
- grpc_chttp2_hptbl_find_result r = {0, 0};
- uint32_t i;
-
- /* See if the string is in the static table */
- for (i = 0; i < GRPC_CHTTP2_LAST_STATIC_ENTRY; i++) {
+ }
+
+ /* we can't add elements bigger than the max table size */
+ if (elem_bytes > tbl->current_table_bytes) {
+ /* HPACK draft 10 section 4.4 states:
+ * If the size of the new entry is less than or equal to the maximum
+ * size, that entry is added to the table. It is not an error to
+ * attempt to add an entry that is larger than the maximum size; an
+ * attempt to add an entry larger than the entire table causes
+ * the table
+ * to be emptied of all existing entries, and results in an
+ * empty table.
+ */
+ while (tbl->num_ents) {
+ evict1(tbl);
+ }
+ return GRPC_ERROR_NONE;
+ }
+
+ /* evict entries to ensure no overflow */
+ while (elem_bytes >
+ static_cast<size_t>(tbl->current_table_bytes) - tbl->mem_used) {
+ evict1(tbl);
+ }
+
+ /* copy the finalized entry in */
+ tbl->ents[(tbl->first_ent + tbl->num_ents) % tbl->cap_entries] =
+ GRPC_MDELEM_REF(md);
+
+ /* update accounting values */
+ tbl->num_ents++;
+ tbl->mem_used += static_cast<uint32_t>(elem_bytes);
+ return GRPC_ERROR_NONE;
+}
+
+grpc_chttp2_hptbl_find_result grpc_chttp2_hptbl_find(
+ const grpc_chttp2_hptbl* tbl, grpc_mdelem md) {
+ grpc_chttp2_hptbl_find_result r = {0, 0};
+ uint32_t i;
+
+ /* 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];
- 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));
- if (r.has_value) return r;
- }
-
- /* Scan the dynamic table */
- for (i = 0; i < tbl->num_ents; i++) {
- uint32_t idx = static_cast<uint32_t>(tbl->num_ents - i +
- GRPC_CHTTP2_LAST_STATIC_ENTRY);
- grpc_mdelem ent = tbl->ents[(tbl->first_ent + i) % tbl->cap_entries];
- if (!grpc_slice_eq(GRPC_MDKEY(md), GRPC_MDKEY(ent))) continue;
- r.index = idx;
- r.has_value = grpc_slice_eq(GRPC_MDVALUE(md), GRPC_MDVALUE(ent));
- if (r.has_value) return r;
- }
-
- return r;
-}
+ 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));
+ if (r.has_value) return r;
+ }
+
+ /* Scan the dynamic table */
+ for (i = 0; i < tbl->num_ents; i++) {
+ uint32_t idx = static_cast<uint32_t>(tbl->num_ents - i +
+ GRPC_CHTTP2_LAST_STATIC_ENTRY);
+ grpc_mdelem ent = tbl->ents[(tbl->first_ent + i) % tbl->cap_entries];
+ if (!grpc_slice_eq(GRPC_MDKEY(md), GRPC_MDKEY(ent))) continue;
+ r.index = idx;
+ r.has_value = grpc_slice_eq(GRPC_MDVALUE(md), GRPC_MDVALUE(ent));
+ if (r.has_value) return r;
+ }
+
+ return r;
+}
static size_t get_base64_encoded_size(size_t raw_length) {
static const uint8_t tail_xtra[3] = {0, 2, 3};
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 34c3dceda75..446477bf3ca 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_HPACK_TABLE_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_TABLE_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/iomgr/error.h"
@@ -86,10 +86,10 @@ struct grpc_chttp2_hptbl {
grpc_mdelem* ents = nullptr;
};
-void grpc_chttp2_hptbl_destroy(grpc_chttp2_hptbl* tbl);
-void grpc_chttp2_hptbl_set_max_bytes(grpc_chttp2_hptbl* tbl,
+void grpc_chttp2_hptbl_destroy(grpc_chttp2_hptbl* tbl);
+void grpc_chttp2_hptbl_set_max_bytes(grpc_chttp2_hptbl* tbl,
uint32_t max_bytes);
-grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_chttp2_hptbl* tbl,
+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 */
@@ -117,8 +117,8 @@ inline grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl* tbl,
}
}
/* add a table entry to the index */
-grpc_error* grpc_chttp2_hptbl_add(grpc_chttp2_hptbl* tbl,
- grpc_mdelem md) GRPC_MUST_USE_RESULT;
+grpc_error* grpc_chttp2_hptbl_add(grpc_chttp2_hptbl* tbl,
+ grpc_mdelem md) GRPC_MUST_USE_RESULT;
size_t grpc_chttp2_get_size_in_hpack_table(grpc_mdelem elem,
bool use_true_binary_metadata);
@@ -143,6 +143,6 @@ struct grpc_chttp2_hptbl_find_result {
int has_value;
};
grpc_chttp2_hptbl_find_result grpc_chttp2_hptbl_find(
- const grpc_chttp2_hptbl* tbl, grpc_mdelem md);
+ const grpc_chttp2_hptbl* tbl, grpc_mdelem md);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_TABLE_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.cc
index 294ee8e4aa8..9aa0202e1a8 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.cc
@@ -1,62 +1,62 @@
-/*
- * 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.
- */
-
-/*
- * Automatically generated by tools/codegen/core/gen_settings_ids.py
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/transport/chttp2/transport/http2_settings.h"
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/transport/http2_errors.h"
-
-const uint16_t grpc_setting_id_to_wire_id[] = {1, 2, 3, 4, 5, 6, 65027};
-
-bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id* out) {
- uint32_t i = wire_id - 1;
- uint32_t x = i % 256;
- uint32_t y = i / 256;
- uint32_t h = x;
- switch (y) {
- case 254:
- h += 4;
- break;
- }
- *out = static_cast<grpc_chttp2_setting_id>(h);
- return h < GPR_ARRAY_SIZE(grpc_setting_id_to_wire_id) &&
- grpc_setting_id_to_wire_id[h] == wire_id;
-}
-
-const grpc_chttp2_setting_parameters
- grpc_chttp2_settings_parameters[GRPC_CHTTP2_NUM_SETTINGS] = {
- {"HEADER_TABLE_SIZE", 4096u, 0u, 4294967295u,
- GRPC_CHTTP2_CLAMP_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
- {"ENABLE_PUSH", 1u, 0u, 1u, GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE,
- GRPC_HTTP2_PROTOCOL_ERROR},
- {"MAX_CONCURRENT_STREAMS", 4294967295u, 0u, 4294967295u,
- GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
- {"INITIAL_WINDOW_SIZE", 65535u, 0u, 2147483647u,
- GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE,
- GRPC_HTTP2_FLOW_CONTROL_ERROR},
- {"MAX_FRAME_SIZE", 16384u, 16384u, 16777215u,
- GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
- {"MAX_HEADER_LIST_SIZE", 16777216u, 0u, 16777216u,
- GRPC_CHTTP2_CLAMP_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
- {"GRPC_ALLOW_TRUE_BINARY_METADATA", 0u, 0u, 1u,
- GRPC_CHTTP2_CLAMP_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
-};
+/*
+ * 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.
+ */
+
+/*
+ * Automatically generated by tools/codegen/core/gen_settings_ids.py
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/transport/chttp2/transport/http2_settings.h"
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/transport/http2_errors.h"
+
+const uint16_t grpc_setting_id_to_wire_id[] = {1, 2, 3, 4, 5, 6, 65027};
+
+bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id* out) {
+ uint32_t i = wire_id - 1;
+ uint32_t x = i % 256;
+ uint32_t y = i / 256;
+ uint32_t h = x;
+ switch (y) {
+ case 254:
+ h += 4;
+ break;
+ }
+ *out = static_cast<grpc_chttp2_setting_id>(h);
+ return h < GPR_ARRAY_SIZE(grpc_setting_id_to_wire_id) &&
+ grpc_setting_id_to_wire_id[h] == wire_id;
+}
+
+const grpc_chttp2_setting_parameters
+ grpc_chttp2_settings_parameters[GRPC_CHTTP2_NUM_SETTINGS] = {
+ {"HEADER_TABLE_SIZE", 4096u, 0u, 4294967295u,
+ GRPC_CHTTP2_CLAMP_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
+ {"ENABLE_PUSH", 1u, 0u, 1u, GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE,
+ GRPC_HTTP2_PROTOCOL_ERROR},
+ {"MAX_CONCURRENT_STREAMS", 4294967295u, 0u, 4294967295u,
+ GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
+ {"INITIAL_WINDOW_SIZE", 65535u, 0u, 2147483647u,
+ GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE,
+ GRPC_HTTP2_FLOW_CONTROL_ERROR},
+ {"MAX_FRAME_SIZE", 16384u, 16384u, 16777215u,
+ GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
+ {"MAX_HEADER_LIST_SIZE", 16777216u, 0u, 16777216u,
+ GRPC_CHTTP2_CLAMP_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
+ {"GRPC_ALLOW_TRUE_BINARY_METADATA", 0u, 0u, 1u,
+ GRPC_CHTTP2_CLAMP_INVALID_VALUE, GRPC_HTTP2_PROTOCOL_ERROR},
+};
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.h
index 3e8ead60f44..663f2c913f2 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/http2_settings.h
@@ -1,61 +1,61 @@
-/*
- * 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.
- */
-
-/*
- * Automatically generated by tools/codegen/core/gen_settings_ids.py
- */
-
-#ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HTTP2_SETTINGS_H
-#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HTTP2_SETTINGS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-#include <stdint.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.
+ */
+
+/*
+ * Automatically generated by tools/codegen/core/gen_settings_ids.py
+ */
+
+#ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HTTP2_SETTINGS_H
+#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HTTP2_SETTINGS_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+#include <stdint.h>
+
enum grpc_chttp2_setting_id {
- GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE = 0, /* wire id 1 */
- GRPC_CHTTP2_SETTINGS_ENABLE_PUSH = 1, /* wire id 2 */
- GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 2, /* wire id 3 */
- GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 3, /* wire id 4 */
- GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE = 4, /* wire id 5 */
- GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE = 5, /* wire id 6 */
- GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA = 6, /* wire id 65027 */
+ GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE = 0, /* wire id 1 */
+ GRPC_CHTTP2_SETTINGS_ENABLE_PUSH = 1, /* wire id 2 */
+ GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 2, /* wire id 3 */
+ GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 3, /* wire id 4 */
+ GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE = 4, /* wire id 5 */
+ GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE = 5, /* wire id 6 */
+ GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA = 6, /* wire id 65027 */
};
-
-#define GRPC_CHTTP2_NUM_SETTINGS 7
-
-extern const uint16_t grpc_setting_id_to_wire_id[];
-
-bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id* out);
-
-typedef enum {
- GRPC_CHTTP2_CLAMP_INVALID_VALUE,
- GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE
-} grpc_chttp2_invalid_value_behavior;
-
+
+#define GRPC_CHTTP2_NUM_SETTINGS 7
+
+extern const uint16_t grpc_setting_id_to_wire_id[];
+
+bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id* out);
+
+typedef enum {
+ GRPC_CHTTP2_CLAMP_INVALID_VALUE,
+ GRPC_CHTTP2_DISCONNECT_ON_INVALID_VALUE
+} grpc_chttp2_invalid_value_behavior;
+
struct grpc_chttp2_setting_parameters {
- const char* name;
- uint32_t default_value;
- uint32_t min_value;
- uint32_t max_value;
- grpc_chttp2_invalid_value_behavior invalid_value_behavior;
- uint32_t error_value;
+ const char* name;
+ uint32_t default_value;
+ uint32_t min_value;
+ uint32_t max_value;
+ grpc_chttp2_invalid_value_behavior invalid_value_behavior;
+ uint32_t error_value;
};
-extern const grpc_chttp2_setting_parameters
- grpc_chttp2_settings_parameters[GRPC_CHTTP2_NUM_SETTINGS];
-
-#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HTTP2_SETTINGS_H */
+extern const grpc_chttp2_setting_parameters
+ grpc_chttp2_settings_parameters[GRPC_CHTTP2_NUM_SETTINGS];
+
+#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HTTP2_SETTINGS_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.cc
index 813e4c91b19..7f26dc422c9 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.cc
@@ -1,92 +1,92 @@
-/*
- *
- * 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/transport/chttp2/transport/huffsyms.h"
-
-/* Constants pulled from the HPACK spec, and converted to C using the vim
- command:
- :%s/.* \([0-9a-f]\+\) \[ *\([0-9]\+\)\]/{0x\1, \2},/g */
-const grpc_chttp2_huffsym grpc_chttp2_huffsyms[GRPC_CHTTP2_NUM_HUFFSYMS] = {
- {0x1ff8, 13}, {0x7fffd8, 23}, {0xfffffe2, 28}, {0xfffffe3, 28},
- {0xfffffe4, 28}, {0xfffffe5, 28}, {0xfffffe6, 28}, {0xfffffe7, 28},
- {0xfffffe8, 28}, {0xffffea, 24}, {0x3ffffffc, 30}, {0xfffffe9, 28},
- {0xfffffea, 28}, {0x3ffffffd, 30}, {0xfffffeb, 28}, {0xfffffec, 28},
- {0xfffffed, 28}, {0xfffffee, 28}, {0xfffffef, 28}, {0xffffff0, 28},
- {0xffffff1, 28}, {0xffffff2, 28}, {0x3ffffffe, 30}, {0xffffff3, 28},
- {0xffffff4, 28}, {0xffffff5, 28}, {0xffffff6, 28}, {0xffffff7, 28},
- {0xffffff8, 28}, {0xffffff9, 28}, {0xffffffa, 28}, {0xffffffb, 28},
- {0x14, 6}, {0x3f8, 10}, {0x3f9, 10}, {0xffa, 12},
- {0x1ff9, 13}, {0x15, 6}, {0xf8, 8}, {0x7fa, 11},
- {0x3fa, 10}, {0x3fb, 10}, {0xf9, 8}, {0x7fb, 11},
- {0xfa, 8}, {0x16, 6}, {0x17, 6}, {0x18, 6},
- {0x0, 5}, {0x1, 5}, {0x2, 5}, {0x19, 6},
- {0x1a, 6}, {0x1b, 6}, {0x1c, 6}, {0x1d, 6},
- {0x1e, 6}, {0x1f, 6}, {0x5c, 7}, {0xfb, 8},
- {0x7ffc, 15}, {0x20, 6}, {0xffb, 12}, {0x3fc, 10},
- {0x1ffa, 13}, {0x21, 6}, {0x5d, 7}, {0x5e, 7},
- {0x5f, 7}, {0x60, 7}, {0x61, 7}, {0x62, 7},
- {0x63, 7}, {0x64, 7}, {0x65, 7}, {0x66, 7},
- {0x67, 7}, {0x68, 7}, {0x69, 7}, {0x6a, 7},
- {0x6b, 7}, {0x6c, 7}, {0x6d, 7}, {0x6e, 7},
- {0x6f, 7}, {0x70, 7}, {0x71, 7}, {0x72, 7},
- {0xfc, 8}, {0x73, 7}, {0xfd, 8}, {0x1ffb, 13},
- {0x7fff0, 19}, {0x1ffc, 13}, {0x3ffc, 14}, {0x22, 6},
- {0x7ffd, 15}, {0x3, 5}, {0x23, 6}, {0x4, 5},
- {0x24, 6}, {0x5, 5}, {0x25, 6}, {0x26, 6},
- {0x27, 6}, {0x6, 5}, {0x74, 7}, {0x75, 7},
- {0x28, 6}, {0x29, 6}, {0x2a, 6}, {0x7, 5},
- {0x2b, 6}, {0x76, 7}, {0x2c, 6}, {0x8, 5},
- {0x9, 5}, {0x2d, 6}, {0x77, 7}, {0x78, 7},
- {0x79, 7}, {0x7a, 7}, {0x7b, 7}, {0x7ffe, 15},
- {0x7fc, 11}, {0x3ffd, 14}, {0x1ffd, 13}, {0xffffffc, 28},
- {0xfffe6, 20}, {0x3fffd2, 22}, {0xfffe7, 20}, {0xfffe8, 20},
- {0x3fffd3, 22}, {0x3fffd4, 22}, {0x3fffd5, 22}, {0x7fffd9, 23},
- {0x3fffd6, 22}, {0x7fffda, 23}, {0x7fffdb, 23}, {0x7fffdc, 23},
- {0x7fffdd, 23}, {0x7fffde, 23}, {0xffffeb, 24}, {0x7fffdf, 23},
- {0xffffec, 24}, {0xffffed, 24}, {0x3fffd7, 22}, {0x7fffe0, 23},
- {0xffffee, 24}, {0x7fffe1, 23}, {0x7fffe2, 23}, {0x7fffe3, 23},
- {0x7fffe4, 23}, {0x1fffdc, 21}, {0x3fffd8, 22}, {0x7fffe5, 23},
- {0x3fffd9, 22}, {0x7fffe6, 23}, {0x7fffe7, 23}, {0xffffef, 24},
- {0x3fffda, 22}, {0x1fffdd, 21}, {0xfffe9, 20}, {0x3fffdb, 22},
- {0x3fffdc, 22}, {0x7fffe8, 23}, {0x7fffe9, 23}, {0x1fffde, 21},
- {0x7fffea, 23}, {0x3fffdd, 22}, {0x3fffde, 22}, {0xfffff0, 24},
- {0x1fffdf, 21}, {0x3fffdf, 22}, {0x7fffeb, 23}, {0x7fffec, 23},
- {0x1fffe0, 21}, {0x1fffe1, 21}, {0x3fffe0, 22}, {0x1fffe2, 21},
- {0x7fffed, 23}, {0x3fffe1, 22}, {0x7fffee, 23}, {0x7fffef, 23},
- {0xfffea, 20}, {0x3fffe2, 22}, {0x3fffe3, 22}, {0x3fffe4, 22},
- {0x7ffff0, 23}, {0x3fffe5, 22}, {0x3fffe6, 22}, {0x7ffff1, 23},
- {0x3ffffe0, 26}, {0x3ffffe1, 26}, {0xfffeb, 20}, {0x7fff1, 19},
- {0x3fffe7, 22}, {0x7ffff2, 23}, {0x3fffe8, 22}, {0x1ffffec, 25},
- {0x3ffffe2, 26}, {0x3ffffe3, 26}, {0x3ffffe4, 26}, {0x7ffffde, 27},
- {0x7ffffdf, 27}, {0x3ffffe5, 26}, {0xfffff1, 24}, {0x1ffffed, 25},
- {0x7fff2, 19}, {0x1fffe3, 21}, {0x3ffffe6, 26}, {0x7ffffe0, 27},
- {0x7ffffe1, 27}, {0x3ffffe7, 26}, {0x7ffffe2, 27}, {0xfffff2, 24},
- {0x1fffe4, 21}, {0x1fffe5, 21}, {0x3ffffe8, 26}, {0x3ffffe9, 26},
- {0xffffffd, 28}, {0x7ffffe3, 27}, {0x7ffffe4, 27}, {0x7ffffe5, 27},
- {0xfffec, 20}, {0xfffff3, 24}, {0xfffed, 20}, {0x1fffe6, 21},
- {0x3fffe9, 22}, {0x1fffe7, 21}, {0x1fffe8, 21}, {0x7ffff3, 23},
- {0x3fffea, 22}, {0x3fffeb, 22}, {0x1ffffee, 25}, {0x1ffffef, 25},
- {0xfffff4, 24}, {0xfffff5, 24}, {0x3ffffea, 26}, {0x7ffff4, 23},
- {0x3ffffeb, 26}, {0x7ffffe6, 27}, {0x3ffffec, 26}, {0x3ffffed, 26},
- {0x7ffffe7, 27}, {0x7ffffe8, 27}, {0x7ffffe9, 27}, {0x7ffffea, 27},
- {0x7ffffeb, 27}, {0xffffffe, 28}, {0x7ffffec, 27}, {0x7ffffed, 27},
- {0x7ffffee, 27}, {0x7ffffef, 27}, {0x7fffff0, 27}, {0x3ffffee, 26},
- {0x3fffffff, 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/ext/transport/chttp2/transport/huffsyms.h"
+
+/* Constants pulled from the HPACK spec, and converted to C using the vim
+ command:
+ :%s/.* \([0-9a-f]\+\) \[ *\([0-9]\+\)\]/{0x\1, \2},/g */
+const grpc_chttp2_huffsym grpc_chttp2_huffsyms[GRPC_CHTTP2_NUM_HUFFSYMS] = {
+ {0x1ff8, 13}, {0x7fffd8, 23}, {0xfffffe2, 28}, {0xfffffe3, 28},
+ {0xfffffe4, 28}, {0xfffffe5, 28}, {0xfffffe6, 28}, {0xfffffe7, 28},
+ {0xfffffe8, 28}, {0xffffea, 24}, {0x3ffffffc, 30}, {0xfffffe9, 28},
+ {0xfffffea, 28}, {0x3ffffffd, 30}, {0xfffffeb, 28}, {0xfffffec, 28},
+ {0xfffffed, 28}, {0xfffffee, 28}, {0xfffffef, 28}, {0xffffff0, 28},
+ {0xffffff1, 28}, {0xffffff2, 28}, {0x3ffffffe, 30}, {0xffffff3, 28},
+ {0xffffff4, 28}, {0xffffff5, 28}, {0xffffff6, 28}, {0xffffff7, 28},
+ {0xffffff8, 28}, {0xffffff9, 28}, {0xffffffa, 28}, {0xffffffb, 28},
+ {0x14, 6}, {0x3f8, 10}, {0x3f9, 10}, {0xffa, 12},
+ {0x1ff9, 13}, {0x15, 6}, {0xf8, 8}, {0x7fa, 11},
+ {0x3fa, 10}, {0x3fb, 10}, {0xf9, 8}, {0x7fb, 11},
+ {0xfa, 8}, {0x16, 6}, {0x17, 6}, {0x18, 6},
+ {0x0, 5}, {0x1, 5}, {0x2, 5}, {0x19, 6},
+ {0x1a, 6}, {0x1b, 6}, {0x1c, 6}, {0x1d, 6},
+ {0x1e, 6}, {0x1f, 6}, {0x5c, 7}, {0xfb, 8},
+ {0x7ffc, 15}, {0x20, 6}, {0xffb, 12}, {0x3fc, 10},
+ {0x1ffa, 13}, {0x21, 6}, {0x5d, 7}, {0x5e, 7},
+ {0x5f, 7}, {0x60, 7}, {0x61, 7}, {0x62, 7},
+ {0x63, 7}, {0x64, 7}, {0x65, 7}, {0x66, 7},
+ {0x67, 7}, {0x68, 7}, {0x69, 7}, {0x6a, 7},
+ {0x6b, 7}, {0x6c, 7}, {0x6d, 7}, {0x6e, 7},
+ {0x6f, 7}, {0x70, 7}, {0x71, 7}, {0x72, 7},
+ {0xfc, 8}, {0x73, 7}, {0xfd, 8}, {0x1ffb, 13},
+ {0x7fff0, 19}, {0x1ffc, 13}, {0x3ffc, 14}, {0x22, 6},
+ {0x7ffd, 15}, {0x3, 5}, {0x23, 6}, {0x4, 5},
+ {0x24, 6}, {0x5, 5}, {0x25, 6}, {0x26, 6},
+ {0x27, 6}, {0x6, 5}, {0x74, 7}, {0x75, 7},
+ {0x28, 6}, {0x29, 6}, {0x2a, 6}, {0x7, 5},
+ {0x2b, 6}, {0x76, 7}, {0x2c, 6}, {0x8, 5},
+ {0x9, 5}, {0x2d, 6}, {0x77, 7}, {0x78, 7},
+ {0x79, 7}, {0x7a, 7}, {0x7b, 7}, {0x7ffe, 15},
+ {0x7fc, 11}, {0x3ffd, 14}, {0x1ffd, 13}, {0xffffffc, 28},
+ {0xfffe6, 20}, {0x3fffd2, 22}, {0xfffe7, 20}, {0xfffe8, 20},
+ {0x3fffd3, 22}, {0x3fffd4, 22}, {0x3fffd5, 22}, {0x7fffd9, 23},
+ {0x3fffd6, 22}, {0x7fffda, 23}, {0x7fffdb, 23}, {0x7fffdc, 23},
+ {0x7fffdd, 23}, {0x7fffde, 23}, {0xffffeb, 24}, {0x7fffdf, 23},
+ {0xffffec, 24}, {0xffffed, 24}, {0x3fffd7, 22}, {0x7fffe0, 23},
+ {0xffffee, 24}, {0x7fffe1, 23}, {0x7fffe2, 23}, {0x7fffe3, 23},
+ {0x7fffe4, 23}, {0x1fffdc, 21}, {0x3fffd8, 22}, {0x7fffe5, 23},
+ {0x3fffd9, 22}, {0x7fffe6, 23}, {0x7fffe7, 23}, {0xffffef, 24},
+ {0x3fffda, 22}, {0x1fffdd, 21}, {0xfffe9, 20}, {0x3fffdb, 22},
+ {0x3fffdc, 22}, {0x7fffe8, 23}, {0x7fffe9, 23}, {0x1fffde, 21},
+ {0x7fffea, 23}, {0x3fffdd, 22}, {0x3fffde, 22}, {0xfffff0, 24},
+ {0x1fffdf, 21}, {0x3fffdf, 22}, {0x7fffeb, 23}, {0x7fffec, 23},
+ {0x1fffe0, 21}, {0x1fffe1, 21}, {0x3fffe0, 22}, {0x1fffe2, 21},
+ {0x7fffed, 23}, {0x3fffe1, 22}, {0x7fffee, 23}, {0x7fffef, 23},
+ {0xfffea, 20}, {0x3fffe2, 22}, {0x3fffe3, 22}, {0x3fffe4, 22},
+ {0x7ffff0, 23}, {0x3fffe5, 22}, {0x3fffe6, 22}, {0x7ffff1, 23},
+ {0x3ffffe0, 26}, {0x3ffffe1, 26}, {0xfffeb, 20}, {0x7fff1, 19},
+ {0x3fffe7, 22}, {0x7ffff2, 23}, {0x3fffe8, 22}, {0x1ffffec, 25},
+ {0x3ffffe2, 26}, {0x3ffffe3, 26}, {0x3ffffe4, 26}, {0x7ffffde, 27},
+ {0x7ffffdf, 27}, {0x3ffffe5, 26}, {0xfffff1, 24}, {0x1ffffed, 25},
+ {0x7fff2, 19}, {0x1fffe3, 21}, {0x3ffffe6, 26}, {0x7ffffe0, 27},
+ {0x7ffffe1, 27}, {0x3ffffe7, 26}, {0x7ffffe2, 27}, {0xfffff2, 24},
+ {0x1fffe4, 21}, {0x1fffe5, 21}, {0x3ffffe8, 26}, {0x3ffffe9, 26},
+ {0xffffffd, 28}, {0x7ffffe3, 27}, {0x7ffffe4, 27}, {0x7ffffe5, 27},
+ {0xfffec, 20}, {0xfffff3, 24}, {0xfffed, 20}, {0x1fffe6, 21},
+ {0x3fffe9, 22}, {0x1fffe7, 21}, {0x1fffe8, 21}, {0x7ffff3, 23},
+ {0x3fffea, 22}, {0x3fffeb, 22}, {0x1ffffee, 25}, {0x1ffffef, 25},
+ {0xfffff4, 24}, {0xfffff5, 24}, {0x3ffffea, 26}, {0x7ffff4, 23},
+ {0x3ffffeb, 26}, {0x7ffffe6, 27}, {0x3ffffec, 26}, {0x3ffffed, 26},
+ {0x7ffffe7, 27}, {0x7ffffe8, 27}, {0x7ffffe9, 27}, {0x7ffffea, 27},
+ {0x7ffffeb, 27}, {0xffffffe, 28}, {0x7ffffec, 27}, {0x7ffffed, 27},
+ {0x7ffffee, 27}, {0x7ffffef, 27}, {0x7fffff0, 27}, {0x3ffffee, 26},
+ {0x3fffffff, 30},
+};
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.h
index 49feb238f10..f20ea9a0131 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/huffsyms.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/core/ext/transport/chttp2/transport/incoming_metadata.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.cc
index d04630d726b..579e26abb31 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/ext/transport/chttp2/transport/incoming_metadata.h"
-
-#include <string.h>
-
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-grpc_error* grpc_chttp2_incoming_metadata_buffer_add(
- grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) {
- buffer->size += GRPC_MDELEM_LENGTH(elem);
+/*
+ *
+ * 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/transport/chttp2/transport/incoming_metadata.h"
+
+#include <string.h>
+
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+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];
@@ -40,27 +40,27 @@ grpc_error* grpc_chttp2_incoming_metadata_buffer_add(
}
storage->md = elem;
return grpc_metadata_batch_link_tail(&buffer->batch, storage);
-}
-
-grpc_error* grpc_chttp2_incoming_metadata_buffer_replace_or_add(
- grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) {
- for (grpc_linked_mdelem* l = buffer->batch.list.head; l != nullptr;
- l = l->next) {
- if (grpc_slice_eq(GRPC_MDKEY(l->md), GRPC_MDKEY(elem))) {
- GRPC_MDELEM_UNREF(l->md);
- l->md = elem;
- return GRPC_ERROR_NONE;
- }
- }
- return grpc_chttp2_incoming_metadata_buffer_add(buffer, elem);
-}
-
-void grpc_chttp2_incoming_metadata_buffer_set_deadline(
- grpc_chttp2_incoming_metadata_buffer* buffer, grpc_millis deadline) {
- buffer->batch.deadline = deadline;
-}
-
-void grpc_chttp2_incoming_metadata_buffer_publish(
- grpc_chttp2_incoming_metadata_buffer* buffer, grpc_metadata_batch* batch) {
- grpc_metadata_batch_move(&buffer->batch, batch);
-}
+}
+
+grpc_error* grpc_chttp2_incoming_metadata_buffer_replace_or_add(
+ grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) {
+ for (grpc_linked_mdelem* l = buffer->batch.list.head; l != nullptr;
+ l = l->next) {
+ if (grpc_slice_eq(GRPC_MDKEY(l->md), GRPC_MDKEY(elem))) {
+ GRPC_MDELEM_UNREF(l->md);
+ l->md = elem;
+ return GRPC_ERROR_NONE;
+ }
+ }
+ return grpc_chttp2_incoming_metadata_buffer_add(buffer, elem);
+}
+
+void grpc_chttp2_incoming_metadata_buffer_set_deadline(
+ grpc_chttp2_incoming_metadata_buffer* buffer, grpc_millis deadline) {
+ buffer->batch.deadline = deadline;
+}
+
+void grpc_chttp2_incoming_metadata_buffer_publish(
+ grpc_chttp2_incoming_metadata_buffer* buffer, grpc_metadata_batch* batch) {
+ grpc_metadata_batch_move(&buffer->batch, batch);
+}
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 b63caa1ae25..ff22f0541c2 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_INCOMING_METADATA_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_INCOMING_METADATA_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/transport/transport.h"
struct grpc_chttp2_incoming_metadata_buffer {
@@ -40,19 +40,19 @@ struct grpc_chttp2_incoming_metadata_buffer {
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;
+ grpc_metadata_batch batch;
};
void grpc_chttp2_incoming_metadata_buffer_publish(
- grpc_chttp2_incoming_metadata_buffer* buffer, grpc_metadata_batch* batch);
-
-grpc_error* grpc_chttp2_incoming_metadata_buffer_add(
- grpc_chttp2_incoming_metadata_buffer* buffer,
- grpc_mdelem elem) GRPC_MUST_USE_RESULT;
-grpc_error* grpc_chttp2_incoming_metadata_buffer_replace_or_add(
- grpc_chttp2_incoming_metadata_buffer* buffer,
- grpc_mdelem elem) GRPC_MUST_USE_RESULT;
+ grpc_chttp2_incoming_metadata_buffer* buffer, grpc_metadata_batch* batch);
+
+grpc_error* grpc_chttp2_incoming_metadata_buffer_add(
+ grpc_chttp2_incoming_metadata_buffer* buffer,
+ grpc_mdelem elem) GRPC_MUST_USE_RESULT;
+grpc_error* grpc_chttp2_incoming_metadata_buffer_replace_or_add(
+ grpc_chttp2_incoming_metadata_buffer* buffer,
+ grpc_mdelem elem) GRPC_MUST_USE_RESULT;
void grpc_chttp2_incoming_metadata_buffer_set_deadline(
- grpc_chttp2_incoming_metadata_buffer* buffer, grpc_millis deadline);
+ grpc_chttp2_incoming_metadata_buffer* buffer, grpc_millis deadline);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_INCOMING_METADATA_H */
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 2f028c08f38..f42af27e524 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
@@ -1,30 +1,30 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CHTTP2_TRANSPORT_INTERNAL_H
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_INTERNAL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <assert.h>
#include <stdbool.h>
-#include "src/core/ext/transport/chttp2/transport/flow_control.h"
+#include "src/core/ext/transport/chttp2/transport/flow_control.h"
#include "src/core/ext/transport/chttp2/transport/frame.h"
#include "src/core/ext/transport/chttp2/transport/frame_data.h"
#include "src/core/ext/transport/chttp2/transport/frame_goaway.h"
@@ -37,11 +37,11 @@
#include "src/core/ext/transport/chttp2/transport/incoming_metadata.h"
#include "src/core/ext/transport/chttp2/transport/stream_map.h"
#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/compression/stream_compression.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/compression/stream_compression.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/endpoint.h"
-#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/transport_impl.h"
@@ -59,7 +59,7 @@ typedef enum {
/* No additional ref is taken for the following refs. Make sure to remove the
stream from these lists when the stream is removed. */
GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT,
- GRPC_CHTTP2_LIST_STALLED_BY_STREAM,
+ GRPC_CHTTP2_LIST_STALLED_BY_STREAM,
/** streams that are waiting to start because there are too many concurrent
streams on the connection */
GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY,
@@ -72,64 +72,64 @@ typedef enum {
GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE,
} grpc_chttp2_write_state;
-typedef enum {
- GRPC_CHTTP2_OPTIMIZE_FOR_LATENCY,
- GRPC_CHTTP2_OPTIMIZE_FOR_THROUGHPUT,
-} grpc_chttp2_optimization_target;
-
-typedef enum {
- GRPC_CHTTP2_PCL_INITIATE = 0,
- GRPC_CHTTP2_PCL_NEXT,
- GRPC_CHTTP2_PCL_INFLIGHT,
- GRPC_CHTTP2_PCL_COUNT /* must be last */
-} grpc_chttp2_ping_closure_list;
-
-typedef enum {
- GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE,
- GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM,
- GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE,
- GRPC_CHTTP2_INITIATE_WRITE_SEND_INITIAL_METADATA,
- GRPC_CHTTP2_INITIATE_WRITE_SEND_TRAILING_METADATA,
- GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING,
- GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS,
- GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT,
- GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM,
- GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API,
- GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL,
- GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL,
- GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS,
- GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING,
- GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE,
- GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING,
+typedef enum {
+ GRPC_CHTTP2_OPTIMIZE_FOR_LATENCY,
+ GRPC_CHTTP2_OPTIMIZE_FOR_THROUGHPUT,
+} grpc_chttp2_optimization_target;
+
+typedef enum {
+ GRPC_CHTTP2_PCL_INITIATE = 0,
+ GRPC_CHTTP2_PCL_NEXT,
+ GRPC_CHTTP2_PCL_INFLIGHT,
+ GRPC_CHTTP2_PCL_COUNT /* must be last */
+} grpc_chttp2_ping_closure_list;
+
+typedef enum {
+ GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE,
+ GRPC_CHTTP2_INITIATE_WRITE_START_NEW_STREAM,
+ GRPC_CHTTP2_INITIATE_WRITE_SEND_MESSAGE,
+ GRPC_CHTTP2_INITIATE_WRITE_SEND_INITIAL_METADATA,
+ GRPC_CHTTP2_INITIATE_WRITE_SEND_TRAILING_METADATA,
+ GRPC_CHTTP2_INITIATE_WRITE_RETRY_SEND_PING,
+ GRPC_CHTTP2_INITIATE_WRITE_CONTINUE_PINGS,
+ GRPC_CHTTP2_INITIATE_WRITE_GOAWAY_SENT,
+ GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM,
+ GRPC_CHTTP2_INITIATE_WRITE_CLOSE_FROM_API,
+ GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL,
+ GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL,
+ GRPC_CHTTP2_INITIATE_WRITE_SEND_SETTINGS,
+ GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_SETTING,
+ GRPC_CHTTP2_INITIATE_WRITE_FLOW_CONTROL_UNSTALLED_BY_UPDATE,
+ GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING,
GRPC_CHTTP2_INITIATE_WRITE_BDP_PING,
- GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING,
- GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED,
- GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE,
- GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM,
-} grpc_chttp2_initiate_write_reason;
-
-const char* grpc_chttp2_initiate_write_reason_string(
- grpc_chttp2_initiate_write_reason reason);
-
+ GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING,
+ GRPC_CHTTP2_INITIATE_WRITE_TRANSPORT_FLOW_CONTROL_UNSTALLED,
+ GRPC_CHTTP2_INITIATE_WRITE_PING_RESPONSE,
+ GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM,
+} grpc_chttp2_initiate_write_reason;
+
+const char* grpc_chttp2_initiate_write_reason_string(
+ grpc_chttp2_initiate_write_reason reason);
+
struct grpc_chttp2_ping_queue {
grpc_closure_list lists[GRPC_CHTTP2_PCL_COUNT] = {};
uint64_t inflight_id = 0;
};
struct grpc_chttp2_repeated_ping_policy {
- int max_pings_without_data;
- int max_ping_strikes;
- grpc_millis min_sent_ping_interval_without_data;
- grpc_millis min_recv_ping_interval_without_data;
+ int max_pings_without_data;
+ int max_ping_strikes;
+ grpc_millis min_sent_ping_interval_without_data;
+ grpc_millis min_recv_ping_interval_without_data;
};
struct grpc_chttp2_repeated_ping_state {
- grpc_millis last_ping_sent_time;
- int pings_before_data_required;
- grpc_timer delayed_ping_timer;
- bool is_delayed_ping_timer_set;
+ grpc_millis last_ping_sent_time;
+ int pings_before_data_required;
+ grpc_timer delayed_ping_timer;
+ bool is_delayed_ping_timer_set;
};
struct grpc_chttp2_server_ping_recv_state {
- grpc_millis last_ping_recv_time;
- int ping_strikes;
+ grpc_millis last_ping_recv_time;
+ int ping_strikes;
};
/* deframer state for the overall http2 stream of bytes */
typedef enum {
@@ -175,12 +175,12 @@ typedef enum {
} grpc_chttp2_deframe_transport_state;
struct grpc_chttp2_stream_list {
- grpc_chttp2_stream* head;
- grpc_chttp2_stream* tail;
+ grpc_chttp2_stream* head;
+ grpc_chttp2_stream* tail;
};
struct grpc_chttp2_stream_link {
- grpc_chttp2_stream* next;
- grpc_chttp2_stream* prev;
+ grpc_chttp2_stream* next;
+ grpc_chttp2_stream* prev;
};
/* We keep several sets of connection wide parameters */
typedef enum {
@@ -203,89 +203,89 @@ typedef enum {
typedef struct grpc_chttp2_write_cb {
int64_t call_at_byte;
- grpc_closure* closure;
- struct grpc_chttp2_write_cb* next;
+ grpc_closure* closure;
+ struct grpc_chttp2_write_cb* next;
} grpc_chttp2_write_cb;
-namespace grpc_core {
-
-class Chttp2IncomingByteStream : public ByteStream {
- public:
- Chttp2IncomingByteStream(grpc_chttp2_transport* transport,
- grpc_chttp2_stream* stream, uint32_t frame_size,
- uint32_t flags);
+namespace grpc_core {
- void Orphan() override;
+class Chttp2IncomingByteStream : public ByteStream {
+ public:
+ Chttp2IncomingByteStream(grpc_chttp2_transport* transport,
+ grpc_chttp2_stream* stream, uint32_t frame_size,
+ uint32_t flags);
- bool Next(size_t max_size_hint, grpc_closure* on_complete) override;
- grpc_error* Pull(grpc_slice* slice) override;
- void Shutdown(grpc_error* error) override;
+ void Orphan() override;
- // 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
+ bool Next(size_t max_size_hint, grpc_closure* on_complete) override;
+ grpc_error* Pull(grpc_slice* slice) override;
+ void Shutdown(grpc_error* error) override;
+
+ // 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
- // 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
+ // 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
- // 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<>.
+ // 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;
}
}
-
- void PublishError(grpc_error* error);
-
+
+ void PublishError(grpc_error* error);
+
grpc_error* Push(const grpc_slice& slice, grpc_slice* slice_out);
-
- grpc_error* Finished(grpc_error* error, bool reset_on_error);
-
- uint32_t remaining_bytes() const { return remaining_bytes_; }
-
- private:
- static void NextLocked(void* arg, grpc_error* error_ignored);
- static void OrphanLocked(void* arg, grpc_error* error_ignored);
-
+
+ grpc_error* Finished(grpc_error* error, bool reset_on_error);
+
+ uint32_t remaining_bytes() const { return remaining_bytes_; }
+
+ private:
+ static void NextLocked(void* arg, grpc_error* error_ignored);
+ static void OrphanLocked(void* arg, grpc_error* error_ignored);
+
void MaybeCreateStreamDecompressionCtx();
- grpc_chttp2_transport* transport_; // Immutable.
- grpc_chttp2_stream* stream_; // Immutable.
-
+ grpc_chttp2_transport* transport_; // Immutable.
+ grpc_chttp2_stream* stream_; // Immutable.
+
grpc_core::RefCount refs_;
-
- /* Accessed only by transport thread when stream->pending_byte_stream == false
- * Accessed only by application thread when stream->pending_byte_stream ==
- * true */
- uint32_t remaining_bytes_;
-
- /* Accessed only by transport thread when stream->pending_byte_stream == false
- * Accessed only by application thread when stream->pending_byte_stream ==
- * true */
+
+ /* Accessed only by transport thread when stream->pending_byte_stream == false
+ * Accessed only by application thread when stream->pending_byte_stream ==
+ * true */
+ uint32_t remaining_bytes_;
+
+ /* Accessed only by transport thread when stream->pending_byte_stream == false
+ * Accessed only by application thread when stream->pending_byte_stream ==
+ * true */
struct {
grpc_closure closure;
size_t max_size_hint;
- grpc_closure* on_complete;
- } next_action_;
- grpc_closure destroy_action_;
+ grpc_closure* on_complete;
+ } next_action_;
+ grpc_closure destroy_action_;
};
-} // namespace grpc_core
-
-typedef enum {
- GRPC_CHTTP2_KEEPALIVE_STATE_WAITING,
- GRPC_CHTTP2_KEEPALIVE_STATE_PINGING,
- GRPC_CHTTP2_KEEPALIVE_STATE_DYING,
- GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED,
-} grpc_chttp2_keepalive_state;
-
+} // namespace grpc_core
+
+typedef enum {
+ GRPC_CHTTP2_KEEPALIVE_STATE_WAITING,
+ GRPC_CHTTP2_KEEPALIVE_STATE_PINGING,
+ GRPC_CHTTP2_KEEPALIVE_STATE_DYING,
+ GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED,
+} grpc_chttp2_keepalive_state;
+
struct grpc_chttp2_transport {
grpc_chttp2_transport(const grpc_channel_args* channel_args,
grpc_endpoint* ep, bool is_client,
@@ -294,7 +294,7 @@ struct grpc_chttp2_transport {
grpc_transport base; /* must be first */
grpc_core::RefCount refs;
- grpc_endpoint* ep;
+ grpc_endpoint* ep;
TString peer_string;
grpc_resource_user* resource_user;
@@ -302,7 +302,7 @@ struct grpc_chttp2_transport {
grpc_core::Combiner* combiner;
grpc_closure* notify_on_receive_settings = nullptr;
-
+
/** write execution state of the transport */
grpc_chttp2_write_state write_state = GRPC_CHTTP2_WRITE_STATE_IDLE;
@@ -347,7 +347,7 @@ struct grpc_chttp2_transport {
/** hpack encoding */
grpc_chttp2_hpack_compressor hpack_compressor;
/** is this a client? */
- bool is_client;
+ bool is_client;
/** data to write next write */
grpc_slice_buffer qbuf;
@@ -356,10 +356,10 @@ struct grpc_chttp2_transport {
*/
uint32_t write_buffer_size = grpc_core::chttp2::kDefaultWindow;
- /** Set to a grpc_error object if a goaway frame is received. By default, set
- * to GRPC_ERROR_NONE */
+ /** Set to a grpc_error object if a goaway frame is received. By default, set
+ * to GRPC_ERROR_NONE */
grpc_error* goaway_error = GRPC_ERROR_NONE;
-
+
grpc_chttp2_sent_goaway_state sent_goaway_state = GRPC_CHTTP2_NO_GOAWAY_SEND;
/** are the local settings dirty and need to be sent? */
@@ -380,19 +380,19 @@ struct grpc_chttp2_transport {
/** last new stream id */
uint32_t last_new_stream_id = 0;
- /** ping queues for various ping insertion points */
+ /** ping queues for various ping insertion points */
grpc_chttp2_ping_queue ping_queue = grpc_chttp2_ping_queue();
- grpc_chttp2_repeated_ping_policy ping_policy;
- grpc_chttp2_repeated_ping_state ping_state;
+ grpc_chttp2_repeated_ping_policy ping_policy;
+ grpc_chttp2_repeated_ping_state ping_state;
uint64_t ping_ctr = 0; /* unique id for pings */
- grpc_closure retry_initiate_ping_locked;
+ grpc_closure retry_initiate_ping_locked;
- /** ping acks */
+ /** ping acks */
size_t ping_ack_count = 0;
size_t ping_ack_capacity = 0;
uint64_t* ping_acks = nullptr;
- grpc_chttp2_server_ping_recv_state ping_recv_state;
-
+ grpc_chttp2_server_ping_recv_state ping_recv_state;
+
/** parser for headers */
grpc_chttp2_hpack_parser hpack_parser;
/** simple one shot parsers */
@@ -405,15 +405,15 @@ struct grpc_chttp2_transport {
/** parser for goaway frames */
grpc_chttp2_goaway_parser goaway_parser;
- grpc_core::PolymorphicManualConstructor<
- grpc_core::chttp2::TransportFlowControlBase,
- grpc_core::chttp2::TransportFlowControl,
- grpc_core::chttp2::TransportFlowControlDisabled>
- flow_control;
- /** initial window change. This is tracked as we parse settings frames from
- * the remote peer. If there is a positive delta, then we will make all
- * streams readable since they may have become unstalled */
- int64_t initial_window_update = 0;
+ grpc_core::PolymorphicManualConstructor<
+ grpc_core::chttp2::TransportFlowControlBase,
+ grpc_core::chttp2::TransportFlowControl,
+ grpc_core::chttp2::TransportFlowControlDisabled>
+ flow_control;
+ /** initial window change. This is tracked as we parse settings frames from
+ * the remote peer. If there is a positive delta, then we will make all
+ * streams readable since they may have become unstalled */
+ int64_t initial_window_update = 0;
/* deframing */
grpc_chttp2_deframe_transport_state deframe_state = GRPC_DTS_CLIENT_PREFIX_0;
@@ -428,18 +428,18 @@ struct grpc_chttp2_transport {
/* active parser */
void* parser_data = nullptr;
grpc_chttp2_stream* incoming_stream = nullptr;
- grpc_error* (*parser)(void* parser_user_data, grpc_chttp2_transport* t,
+ grpc_error* (*parser)(void* parser_user_data, grpc_chttp2_transport* t,
grpc_chttp2_stream* s, const grpc_slice& slice,
int is_last);
grpc_chttp2_write_cb* write_cb_pool = nullptr;
- /* bdp estimator */
+ /* bdp estimator */
bool bdp_ping_blocked =
false; /* Is the BDP blocked due to not receiving any data? */
- grpc_closure next_bdp_ping_timer_expired_locked;
- grpc_closure start_bdp_ping_locked;
- grpc_closure finish_bdp_ping_locked;
+ grpc_closure next_bdp_ping_timer_expired_locked;
+ grpc_closure start_bdp_ping_locked;
+ grpc_closure finish_bdp_ping_locked;
/* if non-NULL, close the transport with this error when writes are finished
*/
@@ -457,36 +457,36 @@ struct grpc_chttp2_transport {
grpc_closure benign_reclaimer_locked;
/** destructive cleanup closure */
grpc_closure destructive_reclaimer_locked;
-
- /* next bdp ping timer */
+
+ /* next bdp ping timer */
bool have_next_bdp_ping_timer = false;
/** If start_bdp_ping_locked has been called */
bool bdp_ping_started = false;
- grpc_timer next_bdp_ping_timer;
-
- /* keep-alive ping support */
- /** Closure to initialize a keepalive ping */
- grpc_closure init_keepalive_ping_locked;
- /** Closure to run when the keepalive ping is sent */
- grpc_closure start_keepalive_ping_locked;
- /** Cousure to run when the keepalive ping ack is received */
- grpc_closure finish_keepalive_ping_locked;
- /** Closrue to run when the keepalive ping timeouts */
- grpc_closure keepalive_watchdog_fired_locked;
- /** timer to initiate ping events */
- grpc_timer keepalive_ping_timer;
- /** watchdog to kill the transport when waiting for the keepalive ping */
- grpc_timer keepalive_watchdog_timer;
- /** time duration in between pings */
- grpc_millis keepalive_time;
- /** grace period for a ping to complete before watchdog kicks in */
- grpc_millis keepalive_timeout;
- /** if keepalive pings are allowed when there's no outstanding streams */
+ grpc_timer next_bdp_ping_timer;
+
+ /* keep-alive ping support */
+ /** Closure to initialize a keepalive ping */
+ grpc_closure init_keepalive_ping_locked;
+ /** Closure to run when the keepalive ping is sent */
+ grpc_closure start_keepalive_ping_locked;
+ /** Cousure to run when the keepalive ping ack is received */
+ grpc_closure finish_keepalive_ping_locked;
+ /** Closrue to run when the keepalive ping timeouts */
+ grpc_closure keepalive_watchdog_fired_locked;
+ /** timer to initiate ping events */
+ grpc_timer keepalive_ping_timer;
+ /** watchdog to kill the transport when waiting for the keepalive ping */
+ grpc_timer keepalive_watchdog_timer;
+ /** time duration in between pings */
+ grpc_millis keepalive_time;
+ /** grace period for a ping to complete before watchdog kicks in */
+ 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;
- /** keep-alive state machine state */
- grpc_chttp2_keepalive_state keepalive_state;
+ /** 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;
@@ -512,8 +512,8 @@ struct grpc_chttp2_stream {
~grpc_chttp2_stream();
void* context;
- grpc_chttp2_transport* t;
- grpc_stream_refcount* refcount;
+ 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`.
@@ -522,7 +522,7 @@ struct grpc_chttp2_stream {
} reffer;
grpc_closure destroy_stream;
- grpc_closure* destroy_stream_arg;
+ grpc_closure* destroy_stream_arg;
grpc_chttp2_stream_link links[STREAM_LIST_COUNT];
uint8_t included[STREAM_LIST_COUNT] = {};
@@ -543,7 +543,7 @@ struct grpc_chttp2_stream {
bool* sent_trailing_metadata_op = nullptr;
grpc_closure* send_trailing_metadata_finished = nullptr;
- grpc_core::OrphanablePtr<grpc_core::ByteStream> fetching_send_message;
+ grpc_core::OrphanablePtr<grpc_core::ByteStream> fetching_send_message;
uint32_t fetched_send_message_length = 0;
grpc_slice fetching_slice = grpc_empty_slice();
int64_t next_message_end_offset;
@@ -552,12 +552,12 @@ struct grpc_chttp2_stream {
grpc_closure complete_fetch_locked;
grpc_closure* fetching_send_message_finished = nullptr;
- grpc_metadata_batch* recv_initial_metadata;
+ grpc_metadata_batch* recv_initial_metadata;
grpc_closure* recv_initial_metadata_ready = nullptr;
bool* trailing_metadata_available = nullptr;
- grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message;
+ grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message;
grpc_closure* recv_message_ready = nullptr;
- grpc_metadata_batch* recv_trailing_metadata;
+ grpc_metadata_batch* recv_trailing_metadata;
grpc_closure* recv_trailing_metadata_finished = nullptr;
grpc_transport_stream_stats* collecting_stats = nullptr;
@@ -590,66 +590,66 @@ struct grpc_chttp2_stream {
grpc_chttp2_incoming_metadata_buffer metadata_buffer[2];
- grpc_slice_buffer frame_storage; /* protected by t combiner */
+ grpc_slice_buffer frame_storage; /* protected by t combiner */
grpc_closure* on_next = nullptr; /* protected by t combiner */
bool pending_byte_stream = false; /* protected by t combiner */
- // cached length of buffer to be used by the transport thread in cases where
- // stream->pending_byte_stream == true. The value is saved before
- // application threads are allowed to modify
- // unprocessed_incoming_frames_buffer
+ // cached length of buffer to be used by the transport thread in cases where
+ // stream->pending_byte_stream == true. The value is saved before
+ // 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;
- grpc_closure reset_byte_stream;
+ 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 */
grpc_millis deadline = GRPC_MILLIS_INF_FUTURE;
-
+
/** saw some stream level error */
grpc_error* forced_close_error = GRPC_ERROR_NONE;
/** how many header frames have we received? */
uint8_t header_frames_received = 0;
/** parsing state for data frames */
- /* Accessed only by transport thread when stream->pending_byte_stream == false
- * Accessed only by application thread when stream->pending_byte_stream ==
- * true */
+ /* Accessed only by transport thread when stream->pending_byte_stream == false
+ * Accessed only by application thread when stream->pending_byte_stream ==
+ * true */
grpc_chttp2_data_parser data_parser;
/** number of bytes received - reset at end of parse thread execution */
int64_t received_bytes = 0;
bool sent_initial_metadata = false;
bool sent_trailing_metadata = false;
-
- grpc_core::PolymorphicManualConstructor<
- grpc_core::chttp2::StreamFlowControlBase,
- grpc_core::chttp2::StreamFlowControl,
- grpc_core::chttp2::StreamFlowControlDisabled>
- flow_control;
-
+
+ grpc_core::PolymorphicManualConstructor<
+ grpc_core::chttp2::StreamFlowControlBase,
+ grpc_core::chttp2::StreamFlowControl,
+ grpc_core::chttp2::StreamFlowControlDisabled>
+ flow_control;
+
grpc_slice_buffer flow_controlled_buffer;
grpc_chttp2_write_cb* on_flow_controlled_cbs = nullptr;
grpc_chttp2_write_cb* on_write_finished_cbs = nullptr;
grpc_chttp2_write_cb* finish_after_write = nullptr;
size_t sending_bytes = 0;
-
- /* Stream compression method to be used. */
+
+ /* Stream compression method to be used. */
grpc_stream_compression_method stream_compression_method =
GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS;
- /* Stream decompression method to be used. */
+ /* Stream decompression method to be used. */
grpc_stream_compression_method stream_decompression_method =
GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS;
-
- /** Whether bytes stored in unprocessed_incoming_byte_stream is decompressed
- */
+
+ /** Whether bytes stored in unprocessed_incoming_byte_stream is decompressed
+ */
bool unprocessed_incoming_frames_decompressed = false;
/** Whether the bytes needs to be traced using Fathom */
bool traced = false;
- /** gRPC header bytes that are already decompressed */
+ /** gRPC header bytes that are already decompressed */
size_t decompressed_header_bytes = 0;
/** Byte counter for number of bytes written */
size_t byte_counter = 0;
@@ -683,105 +683,105 @@ struct grpc_chttp2_stream {
The actual call chain is documented in the implementation of this function.
*/
-void grpc_chttp2_initiate_write(grpc_chttp2_transport* t,
- grpc_chttp2_initiate_write_reason reason);
+void grpc_chttp2_initiate_write(grpc_chttp2_transport* t,
+ grpc_chttp2_initiate_write_reason reason);
struct grpc_chttp2_begin_write_result {
- /** are we writing? */
- bool writing;
- /** if writing: was it a complete flush (false) or a partial flush (true) */
- bool partial;
- /** did we queue any completions as part of beginning the write */
- bool early_results_scheduled;
+ /** are we writing? */
+ bool writing;
+ /** if writing: was it a complete flush (false) or a partial flush (true) */
+ bool partial;
+ /** did we queue any completions as part of beginning the write */
+ bool early_results_scheduled;
};
-grpc_chttp2_begin_write_result grpc_chttp2_begin_write(
- grpc_chttp2_transport* t);
-void grpc_chttp2_end_write(grpc_chttp2_transport* t, grpc_error* error);
-
+grpc_chttp2_begin_write_result grpc_chttp2_begin_write(
+ grpc_chttp2_transport* t);
+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,
+grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
const grpc_slice& slice);
-bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
+bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
/** Get a writable stream
returns non-zero if there was a stream available */
-bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s);
-bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-
-bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport* t);
-bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s);
-
-void grpc_chttp2_list_add_written_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-bool grpc_chttp2_list_pop_written_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s);
-
-void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s);
-void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-
-void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s);
-void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-
-void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s);
-bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-
-/********* Flow Control ***************/
-
-// Takes in a flow control action and performs all the needed operations.
-void grpc_chttp2_act_on_flowctl_action(
- const grpc_core::chttp2::FlowControlAction& action,
- grpc_chttp2_transport* t, grpc_chttp2_stream* s);
-
-/********* End of Flow Control ***************/
-
+bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s);
+bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+
+bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport* t);
+bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s);
+
+void grpc_chttp2_list_add_written_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+bool grpc_chttp2_list_pop_written_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s);
+
+void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s);
+void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+
+void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s);
+void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+
+void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s);
+bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+
+/********* Flow Control ***************/
+
+// Takes in a flow control action and performs all the needed operations.
+void grpc_chttp2_act_on_flowctl_action(
+ const grpc_core::chttp2::FlowControlAction& action,
+ grpc_chttp2_transport* t, grpc_chttp2_stream* s);
+
+/********* 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));
}
-grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t,
+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,
+void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t,
uint32_t goaway_error,
uint32_t last_stream_id,
const grpc_slice& goaway_text);
-void grpc_chttp2_parsing_become_skip_parser(grpc_chttp2_transport* t);
+void grpc_chttp2_parsing_become_skip_parser(grpc_chttp2_transport* t);
-void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
- grpc_closure** pclosure,
- grpc_error* error, const char* desc);
-
-#define GRPC_HEADER_SIZE_IN_BYTES 5
-#define MAX_SIZE_T (~(size_t)0)
+void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
+ grpc_closure** pclosure,
+ grpc_error* error, const char* desc);
+#define GRPC_HEADER_SIZE_IN_BYTES 5
+#define MAX_SIZE_T (~(size_t)0)
+
#define GRPC_CHTTP2_CLIENT_CONNECT_STRING "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
#define GRPC_CHTTP2_CLIENT_CONNECT_STRLEN \
(sizeof(GRPC_CHTTP2_CLIENT_CONNECT_STRING) - 1)
-// extern grpc_core::TraceFlag grpc_http_trace;
-// extern grpc_core::TraceFlag grpc_flowctl_trace;
+// extern grpc_core::TraceFlag grpc_http_trace;
+// extern grpc_core::TraceFlag grpc_flowctl_trace;
#define GRPC_CHTTP2_IF_TRACING(stmt) \
do { \
@@ -790,33 +790,33 @@ void grpc_chttp2_complete_closure_step(grpc_chttp2_transport* t,
} \
} while (0)
-void grpc_chttp2_fake_status(grpc_chttp2_transport* t,
- grpc_chttp2_stream* stream, grpc_error* error);
-void grpc_chttp2_mark_stream_closed(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s, int close_reads,
- int close_writes, grpc_error* error);
-void grpc_chttp2_start_writing(grpc_chttp2_transport* t);
+void grpc_chttp2_fake_status(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* stream, grpc_error* error);
+void grpc_chttp2_mark_stream_closed(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s, int close_reads,
+ int close_writes, grpc_error* error);
+void grpc_chttp2_start_writing(grpc_chttp2_transport* t);
-#ifndef NDEBUG
+#ifndef NDEBUG
#define GRPC_CHTTP2_STREAM_REF(stream, reason) \
grpc_chttp2_stream_ref(stream, reason)
-#define GRPC_CHTTP2_STREAM_UNREF(stream, reason) \
- grpc_chttp2_stream_unref(stream, reason)
-void grpc_chttp2_stream_ref(grpc_chttp2_stream* s, const char* reason);
-void grpc_chttp2_stream_unref(grpc_chttp2_stream* s, const char* reason);
+#define GRPC_CHTTP2_STREAM_UNREF(stream, reason) \
+ grpc_chttp2_stream_unref(stream, reason)
+void grpc_chttp2_stream_ref(grpc_chttp2_stream* s, const char* reason);
+void grpc_chttp2_stream_unref(grpc_chttp2_stream* s, const char* reason);
#else
#define GRPC_CHTTP2_STREAM_REF(stream, reason) grpc_chttp2_stream_ref(stream)
-#define GRPC_CHTTP2_STREAM_UNREF(stream, reason) \
- grpc_chttp2_stream_unref(stream)
-void grpc_chttp2_stream_ref(grpc_chttp2_stream* s);
-void grpc_chttp2_stream_unref(grpc_chttp2_stream* s);
+#define GRPC_CHTTP2_STREAM_UNREF(stream, reason) \
+ grpc_chttp2_stream_unref(stream)
+void grpc_chttp2_stream_ref(grpc_chttp2_stream* s);
+void grpc_chttp2_stream_unref(grpc_chttp2_stream* s);
#endif
-#ifndef NDEBUG
+#ifndef NDEBUG
#define GRPC_CHTTP2_REF_TRANSPORT(t, r) \
grpc_chttp2_ref_transport(t, r, __FILE__, __LINE__)
-#define GRPC_CHTTP2_UNREF_TRANSPORT(t, r) \
- grpc_chttp2_unref_transport(t, r, __FILE__, __LINE__)
+#define GRPC_CHTTP2_UNREF_TRANSPORT(t, r) \
+ grpc_chttp2_unref_transport(t, r, __FILE__, __LINE__)
inline void grpc_chttp2_unref_transport(grpc_chttp2_transport* t,
const char* reason, const char* file,
int line) {
@@ -831,7 +831,7 @@ inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t,
}
#else
#define GRPC_CHTTP2_REF_TRANSPORT(t, r) grpc_chttp2_ref_transport(t)
-#define GRPC_CHTTP2_UNREF_TRANSPORT(t, r) grpc_chttp2_unref_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;
@@ -842,13 +842,13 @@ inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t) {
}
#endif
-void grpc_chttp2_ack_ping(grpc_chttp2_transport* t, uint64_t id);
+void grpc_chttp2_ack_ping(grpc_chttp2_transport* t, uint64_t id);
-/** Add a new ping strike to ping_recv_state.ping_strikes. If
- ping_recv_state.ping_strikes > ping_policy.max_ping_strikes, it sends GOAWAY
- with error code ENHANCE_YOUR_CALM and additional debug data resembling
- "too_many_pings" followed by immediately closing the connection. */
-void grpc_chttp2_add_ping_strike(grpc_chttp2_transport* t);
+/** Add a new ping strike to ping_recv_state.ping_strikes. If
+ ping_recv_state.ping_strikes > ping_policy.max_ping_strikes, it sends GOAWAY
+ with error code ENHANCE_YOUR_CALM and additional debug data resembling
+ "too_many_pings" followed by immediately closing the connection. */
+void grpc_chttp2_add_ping_strike(grpc_chttp2_transport* t);
/** Resets ping clock. Should be called when flushing window updates,
* initial/trailing metadata or data frames. For a server, it resets the number
@@ -858,27 +858,27 @@ void grpc_chttp2_reset_ping_clock(grpc_chttp2_transport* t);
/** add a ref to the stream and add it to the writable list;
ref will be dropped in writing.c */
-void grpc_chttp2_mark_stream_writable(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-
-void grpc_chttp2_cancel_stream(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_error* due_to_error);
-
-void grpc_chttp2_maybe_complete_recv_initial_metadata(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-void grpc_chttp2_maybe_complete_recv_message(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s);
-
-void grpc_chttp2_fail_pending_writes(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s, grpc_error* error);
-
-/** Set the default keepalive configurations, must only be called at
- initialization */
-void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args,
- bool is_client);
-
+void grpc_chttp2_mark_stream_writable(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+
+void grpc_chttp2_cancel_stream(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_error* due_to_error);
+
+void grpc_chttp2_maybe_complete_recv_initial_metadata(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+void grpc_chttp2_maybe_complete_recv_message(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s);
+
+void grpc_chttp2_fail_pending_writes(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s, grpc_error* error);
+
+/** Set the default keepalive configurations, must only be called at
+ initialization */
+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 schedule_bdp_ping_locked(grpc_chttp2_transport* t);
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 741d72041b2..59a310492db 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
@@ -1,92 +1,92 @@
-/*
- *
- * 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/transport/chttp2/transport/internal.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/transport/chttp2/transport/internal.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.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/transport/http2_errors.h"
-#include "src/core/lib/transport/static_metadata.h"
-#include "src/core/lib/transport/status_conversion.h"
-#include "src/core/lib/transport/timeout_encoding.h"
-
-static grpc_error* init_frame_parser(grpc_chttp2_transport* t);
-static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t,
- int is_continuation);
-static grpc_error* init_data_frame_parser(grpc_chttp2_transport* t);
-static grpc_error* init_rst_stream_parser(grpc_chttp2_transport* t);
-static grpc_error* init_settings_frame_parser(grpc_chttp2_transport* t);
-static grpc_error* init_window_update_frame_parser(grpc_chttp2_transport* t);
-static grpc_error* init_ping_parser(grpc_chttp2_transport* t);
-static grpc_error* init_goaway_parser(grpc_chttp2_transport* t);
-static grpc_error* init_skip_frame_parser(grpc_chttp2_transport* t,
- int is_header);
-
+#include "src/core/lib/transport/http2_errors.h"
+#include "src/core/lib/transport/static_metadata.h"
+#include "src/core/lib/transport/status_conversion.h"
+#include "src/core/lib/transport/timeout_encoding.h"
+
+static grpc_error* init_frame_parser(grpc_chttp2_transport* t);
+static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t,
+ int is_continuation);
+static grpc_error* init_data_frame_parser(grpc_chttp2_transport* t);
+static grpc_error* init_rst_stream_parser(grpc_chttp2_transport* t);
+static grpc_error* init_settings_frame_parser(grpc_chttp2_transport* t);
+static grpc_error* init_window_update_frame_parser(grpc_chttp2_transport* t);
+static grpc_error* init_ping_parser(grpc_chttp2_transport* t);
+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);
-
-grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
+
+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;
- grpc_error* err;
-
- if (cur == end) return GRPC_ERROR_NONE;
-
- switch (t->deframe_state) {
- case GRPC_DTS_CLIENT_PREFIX_0:
- case GRPC_DTS_CLIENT_PREFIX_1:
- case GRPC_DTS_CLIENT_PREFIX_2:
- case GRPC_DTS_CLIENT_PREFIX_3:
- case GRPC_DTS_CLIENT_PREFIX_4:
- case GRPC_DTS_CLIENT_PREFIX_5:
- case GRPC_DTS_CLIENT_PREFIX_6:
- case GRPC_DTS_CLIENT_PREFIX_7:
- case GRPC_DTS_CLIENT_PREFIX_8:
- case GRPC_DTS_CLIENT_PREFIX_9:
- case GRPC_DTS_CLIENT_PREFIX_10:
- case GRPC_DTS_CLIENT_PREFIX_11:
- case GRPC_DTS_CLIENT_PREFIX_12:
- case GRPC_DTS_CLIENT_PREFIX_13:
- case GRPC_DTS_CLIENT_PREFIX_14:
- case GRPC_DTS_CLIENT_PREFIX_15:
- case GRPC_DTS_CLIENT_PREFIX_16:
- case GRPC_DTS_CLIENT_PREFIX_17:
- case GRPC_DTS_CLIENT_PREFIX_18:
- case GRPC_DTS_CLIENT_PREFIX_19:
- case GRPC_DTS_CLIENT_PREFIX_20:
- case GRPC_DTS_CLIENT_PREFIX_21:
- case GRPC_DTS_CLIENT_PREFIX_22:
- case GRPC_DTS_CLIENT_PREFIX_23:
- while (cur != end && t->deframe_state != GRPC_DTS_FH_0) {
- if (*cur != GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state]) {
+ grpc_error* err;
+
+ if (cur == end) return GRPC_ERROR_NONE;
+
+ switch (t->deframe_state) {
+ case GRPC_DTS_CLIENT_PREFIX_0:
+ case GRPC_DTS_CLIENT_PREFIX_1:
+ case GRPC_DTS_CLIENT_PREFIX_2:
+ case GRPC_DTS_CLIENT_PREFIX_3:
+ case GRPC_DTS_CLIENT_PREFIX_4:
+ case GRPC_DTS_CLIENT_PREFIX_5:
+ case GRPC_DTS_CLIENT_PREFIX_6:
+ case GRPC_DTS_CLIENT_PREFIX_7:
+ case GRPC_DTS_CLIENT_PREFIX_8:
+ case GRPC_DTS_CLIENT_PREFIX_9:
+ case GRPC_DTS_CLIENT_PREFIX_10:
+ case GRPC_DTS_CLIENT_PREFIX_11:
+ case GRPC_DTS_CLIENT_PREFIX_12:
+ case GRPC_DTS_CLIENT_PREFIX_13:
+ case GRPC_DTS_CLIENT_PREFIX_14:
+ case GRPC_DTS_CLIENT_PREFIX_15:
+ case GRPC_DTS_CLIENT_PREFIX_16:
+ case GRPC_DTS_CLIENT_PREFIX_17:
+ case GRPC_DTS_CLIENT_PREFIX_18:
+ case GRPC_DTS_CLIENT_PREFIX_19:
+ case GRPC_DTS_CLIENT_PREFIX_20:
+ case GRPC_DTS_CLIENT_PREFIX_21:
+ case GRPC_DTS_CLIENT_PREFIX_22:
+ case GRPC_DTS_CLIENT_PREFIX_23:
+ while (cur != end && t->deframe_state != GRPC_DTS_FH_0) {
+ if (*cur != GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state]) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat(
"Connect string mismatch: expected '%c' (%d) got '%c' (%d) "
@@ -96,244 +96,244 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state])),
*cur, static_cast<int>(*cur), t->deframe_state)
.c_str());
- }
- ++cur;
- t->deframe_state = static_cast<grpc_chttp2_deframe_transport_state>(
- 1 + static_cast<int>(t->deframe_state));
- }
- if (cur == end) {
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- dts_fh_0:
- case GRPC_DTS_FH_0:
+ }
+ ++cur;
+ t->deframe_state = static_cast<grpc_chttp2_deframe_transport_state>(
+ 1 + static_cast<int>(t->deframe_state));
+ }
+ if (cur == end) {
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ dts_fh_0:
+ case GRPC_DTS_FH_0:
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;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_1:
+ t->incoming_frame_size = (static_cast<uint32_t>(*cur)) << 16;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_1;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_1:
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;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_2:
+ t->incoming_frame_size |= (static_cast<uint32_t>(*cur)) << 8;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_2;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_2:
GPR_DEBUG_ASSERT(cur < end);
- t->incoming_frame_size |= *cur;
- if (++cur == end) {
- t->deframe_state = GRPC_DTS_FH_3;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_3:
+ t->incoming_frame_size |= *cur;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_3;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_3:
GPR_DEBUG_ASSERT(cur < end);
- t->incoming_frame_type = *cur;
- if (++cur == end) {
- t->deframe_state = GRPC_DTS_FH_4;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_4:
+ t->incoming_frame_type = *cur;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_4;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_4:
GPR_DEBUG_ASSERT(cur < end);
- t->incoming_frame_flags = *cur;
- if (++cur == end) {
- t->deframe_state = GRPC_DTS_FH_5;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_5:
+ t->incoming_frame_flags = *cur;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_5;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_5:
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;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_6:
+ t->incoming_stream_id = ((static_cast<uint32_t>(*cur)) & 0x7f) << 24;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_6;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_6:
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;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_7:
+ t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 16;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_7;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_7:
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;
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FH_8:
+ t->incoming_stream_id |= (static_cast<uint32_t>(*cur)) << 8;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_8;
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FH_8:
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);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- if (t->incoming_frame_size == 0) {
- err = parse_frame_slice(t, grpc_empty_slice(), 1);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- t->incoming_stream = nullptr;
- if (++cur == end) {
- t->deframe_state = GRPC_DTS_FH_0;
- return GRPC_ERROR_NONE;
- }
- goto dts_fh_0; /* loop */
- } else if (t->flow_control->flow_control_enabled() &&
- t->incoming_frame_size >
- t->settings[GRPC_ACKED_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE]) {
+ t->incoming_stream_id |= (static_cast<uint32_t>(*cur));
+ t->deframe_state = GRPC_DTS_FRAME;
+ err = init_frame_parser(t);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ if (t->incoming_frame_size == 0) {
+ err = parse_frame_slice(t, grpc_empty_slice(), 1);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ t->incoming_stream = nullptr;
+ if (++cur == end) {
+ t->deframe_state = GRPC_DTS_FH_0;
+ return GRPC_ERROR_NONE;
+ }
+ goto dts_fh_0; /* loop */
+ } else if (t->flow_control->flow_control_enabled() &&
+ t->incoming_frame_size >
+ t->settings[GRPC_ACKED_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE]) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("Frame size %d is larger than max frame size %d",
t->incoming_frame_size,
t->settings[GRPC_ACKED_SETTINGS]
[GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE])
.c_str());
- }
- if (++cur == end) {
- return GRPC_ERROR_NONE;
- }
- /* fallthrough */
- case GRPC_DTS_FRAME:
+ }
+ if (++cur == end) {
+ return GRPC_ERROR_NONE;
+ }
+ /* fallthrough */
+ case GRPC_DTS_FRAME:
GPR_DEBUG_ASSERT(cur < end);
- if (static_cast<uint32_t>(end - cur) == t->incoming_frame_size) {
- err = parse_frame_slice(
- t,
- grpc_slice_sub_no_ref(slice, static_cast<size_t>(cur - beg),
- static_cast<size_t>(end - beg)),
- 1);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- t->deframe_state = GRPC_DTS_FH_0;
- t->incoming_stream = nullptr;
- return GRPC_ERROR_NONE;
- } else if (static_cast<uint32_t>(end - cur) > t->incoming_frame_size) {
- size_t cur_offset = static_cast<size_t>(cur - beg);
- err = parse_frame_slice(
- t,
- grpc_slice_sub_no_ref(slice, cur_offset,
- cur_offset + t->incoming_frame_size),
- 1);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- cur += t->incoming_frame_size;
- t->incoming_stream = nullptr;
- goto dts_fh_0; /* loop */
- } else {
- err = parse_frame_slice(
- t,
- grpc_slice_sub_no_ref(slice, static_cast<size_t>(cur - beg),
- static_cast<size_t>(end - beg)),
- 0);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- t->incoming_frame_size -= static_cast<uint32_t>(end - cur);
- return GRPC_ERROR_NONE;
- }
- GPR_UNREACHABLE_CODE(return nullptr);
- }
-
- GPR_UNREACHABLE_CODE(return nullptr);
-}
-
-static grpc_error* init_frame_parser(grpc_chttp2_transport* t) {
- if (t->is_first_frame &&
- t->incoming_frame_type != GRPC_CHTTP2_FRAME_SETTINGS) {
+ if (static_cast<uint32_t>(end - cur) == t->incoming_frame_size) {
+ err = parse_frame_slice(
+ t,
+ grpc_slice_sub_no_ref(slice, static_cast<size_t>(cur - beg),
+ static_cast<size_t>(end - beg)),
+ 1);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ t->deframe_state = GRPC_DTS_FH_0;
+ t->incoming_stream = nullptr;
+ return GRPC_ERROR_NONE;
+ } else if (static_cast<uint32_t>(end - cur) > t->incoming_frame_size) {
+ size_t cur_offset = static_cast<size_t>(cur - beg);
+ err = parse_frame_slice(
+ t,
+ grpc_slice_sub_no_ref(slice, cur_offset,
+ cur_offset + t->incoming_frame_size),
+ 1);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ cur += t->incoming_frame_size;
+ t->incoming_stream = nullptr;
+ goto dts_fh_0; /* loop */
+ } else {
+ err = parse_frame_slice(
+ t,
+ grpc_slice_sub_no_ref(slice, static_cast<size_t>(cur - beg),
+ static_cast<size_t>(end - beg)),
+ 0);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ t->incoming_frame_size -= static_cast<uint32_t>(end - cur);
+ return GRPC_ERROR_NONE;
+ }
+ GPR_UNREACHABLE_CODE(return nullptr);
+ }
+
+ GPR_UNREACHABLE_CODE(return nullptr);
+}
+
+static grpc_error* init_frame_parser(grpc_chttp2_transport* t) {
+ if (t->is_first_frame &&
+ t->incoming_frame_type != GRPC_CHTTP2_FRAME_SETTINGS) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat(
"Expected SETTINGS frame as the first frame, got frame type ",
t->incoming_frame_type)
.c_str());
- }
- t->is_first_frame = false;
- if (t->expect_continuation_stream_id != 0) {
- if (t->incoming_frame_type != GRPC_CHTTP2_FRAME_CONTINUATION) {
+ }
+ t->is_first_frame = false;
+ if (t->expect_continuation_stream_id != 0) {
+ if (t->incoming_frame_type != GRPC_CHTTP2_FRAME_CONTINUATION) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("Expected CONTINUATION frame, got frame type %02x",
t->incoming_frame_type)
.c_str());
- }
- if (t->expect_continuation_stream_id != t->incoming_stream_id) {
+ }
+ if (t->expect_continuation_stream_id != t->incoming_stream_id) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat(
"Expected CONTINUATION frame for grpc_chttp2_stream %08x, got "
"grpc_chttp2_stream %08x",
t->expect_continuation_stream_id, t->incoming_stream_id)
.c_str());
- }
- return init_header_frame_parser(t, 1);
- }
- switch (t->incoming_frame_type) {
- case GRPC_CHTTP2_FRAME_DATA:
- return init_data_frame_parser(t);
- case GRPC_CHTTP2_FRAME_HEADER:
- return init_header_frame_parser(t, 0);
- case GRPC_CHTTP2_FRAME_CONTINUATION:
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Unexpected CONTINUATION frame");
- case GRPC_CHTTP2_FRAME_RST_STREAM:
- return init_rst_stream_parser(t);
- case GRPC_CHTTP2_FRAME_SETTINGS:
- return init_settings_frame_parser(t);
- case GRPC_CHTTP2_FRAME_WINDOW_UPDATE:
- return init_window_update_frame_parser(t);
- case GRPC_CHTTP2_FRAME_PING:
- return init_ping_parser(t);
- case GRPC_CHTTP2_FRAME_GOAWAY:
- return init_goaway_parser(t);
- default:
+ }
+ return init_header_frame_parser(t, 1);
+ }
+ switch (t->incoming_frame_type) {
+ case GRPC_CHTTP2_FRAME_DATA:
+ return init_data_frame_parser(t);
+ case GRPC_CHTTP2_FRAME_HEADER:
+ return init_header_frame_parser(t, 0);
+ case GRPC_CHTTP2_FRAME_CONTINUATION:
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Unexpected CONTINUATION frame");
+ case GRPC_CHTTP2_FRAME_RST_STREAM:
+ return init_rst_stream_parser(t);
+ case GRPC_CHTTP2_FRAME_SETTINGS:
+ return init_settings_frame_parser(t);
+ case GRPC_CHTTP2_FRAME_WINDOW_UPDATE:
+ return init_window_update_frame_parser(t);
+ case GRPC_CHTTP2_FRAME_PING:
+ return init_ping_parser(t);
+ case GRPC_CHTTP2_FRAME_GOAWAY:
+ return init_goaway_parser(t);
+ default:
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);
- }
-}
-
+ 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*/) {
- return GRPC_ERROR_NONE;
-}
-
+ 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) {
- if (is_header) {
- uint8_t is_eoh = t->expect_continuation_stream_id != 0;
- t->parser = grpc_chttp2_header_parser_parse;
- t->parser_data = &t->hpack_parser;
- t->hpack_parser.on_header = skip_header;
- t->hpack_parser.on_header_user_data = nullptr;
- t->hpack_parser.is_boundary = is_eoh;
- t->hpack_parser.is_eof = static_cast<uint8_t>(is_eoh ? t->header_eof : 0);
- } else {
- t->parser = skip_parser;
- }
- return GRPC_ERROR_NONE;
-}
-
-void grpc_chttp2_parsing_become_skip_parser(grpc_chttp2_transport* t) {
- init_skip_frame_parser(t, t->parser == grpc_chttp2_header_parser_parse);
-}
-
-static grpc_error* init_data_frame_parser(grpc_chttp2_transport* t) {
+
+static grpc_error* init_skip_frame_parser(grpc_chttp2_transport* t,
+ int is_header) {
+ if (is_header) {
+ uint8_t is_eoh = t->expect_continuation_stream_id != 0;
+ t->parser = grpc_chttp2_header_parser_parse;
+ t->parser_data = &t->hpack_parser;
+ t->hpack_parser.on_header = skip_header;
+ t->hpack_parser.on_header_user_data = nullptr;
+ t->hpack_parser.is_boundary = is_eoh;
+ t->hpack_parser.is_eof = static_cast<uint8_t>(is_eoh ? t->header_eof : 0);
+ } else {
+ t->parser = skip_parser;
+ }
+ return GRPC_ERROR_NONE;
+}
+
+void grpc_chttp2_parsing_become_skip_parser(grpc_chttp2_transport* t) {
+ init_skip_frame_parser(t, t->parser == grpc_chttp2_header_parser_parse);
+}
+
+static grpc_error* init_data_frame_parser(grpc_chttp2_transport* t) {
// Update BDP accounting since we have received a data frame.
grpc_core::BdpEstimator* bdp_est = t->flow_control->bdp_estimator();
if (bdp_est) {
@@ -344,58 +344,58 @@ static grpc_error* init_data_frame_parser(grpc_chttp2_transport* t) {
}
bdp_est->AddIncomingBytes(t->incoming_frame_size);
}
- grpc_chttp2_stream* s =
- grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
- grpc_error* err = GRPC_ERROR_NONE;
- grpc_core::chttp2::FlowControlAction action;
- if (s == nullptr) {
- err = t->flow_control->RecvData(t->incoming_frame_size);
- action = t->flow_control->MakeAction();
- } else {
- err = s->flow_control->RecvData(t->incoming_frame_size);
- action = s->flow_control->MakeAction();
- }
- grpc_chttp2_act_on_flowctl_action(action, t, s);
- if (err != GRPC_ERROR_NONE) {
- goto error_handler;
- }
- if (s == nullptr) {
- return init_skip_frame_parser(t, 0);
- }
- s->received_bytes += t->incoming_frame_size;
- s->stats.incoming.framing_bytes += 9;
- if (err == GRPC_ERROR_NONE && s->read_closed) {
- return init_skip_frame_parser(t, 0);
- }
- if (err == GRPC_ERROR_NONE) {
- err = grpc_chttp2_data_parser_begin_frame(
- &s->data_parser, t->incoming_frame_flags, s->id, s);
- }
-error_handler:
+ grpc_chttp2_stream* s =
+ grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
+ grpc_error* err = GRPC_ERROR_NONE;
+ grpc_core::chttp2::FlowControlAction action;
+ if (s == nullptr) {
+ err = t->flow_control->RecvData(t->incoming_frame_size);
+ action = t->flow_control->MakeAction();
+ } else {
+ err = s->flow_control->RecvData(t->incoming_frame_size);
+ action = s->flow_control->MakeAction();
+ }
+ grpc_chttp2_act_on_flowctl_action(action, t, s);
+ if (err != GRPC_ERROR_NONE) {
+ goto error_handler;
+ }
+ if (s == nullptr) {
+ return init_skip_frame_parser(t, 0);
+ }
+ s->received_bytes += t->incoming_frame_size;
+ s->stats.incoming.framing_bytes += 9;
+ if (err == GRPC_ERROR_NONE && s->read_closed) {
+ return init_skip_frame_parser(t, 0);
+ }
+ if (err == GRPC_ERROR_NONE) {
+ err = grpc_chttp2_data_parser_begin_frame(
+ &s->data_parser, t->incoming_frame_flags, s->id, s);
+ }
+error_handler:
intptr_t unused;
- if (err == GRPC_ERROR_NONE) {
- t->incoming_stream = s;
- /* t->parser = grpc_chttp2_data_parser_parse;*/
- t->parser = grpc_chttp2_data_parser_parse;
- t->parser_data = &s->data_parser;
- t->ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST;
- return GRPC_ERROR_NONE;
+ if (err == GRPC_ERROR_NONE) {
+ t->incoming_stream = s;
+ /* t->parser = grpc_chttp2_data_parser_parse;*/
+ t->parser = grpc_chttp2_data_parser_parse;
+ t->parser_data = &s->data_parser;
+ t->ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST;
+ return GRPC_ERROR_NONE;
} else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, &unused)) {
- /* handle stream errors by closing the stream */
- if (s != nullptr) {
- grpc_chttp2_mark_stream_closed(t, s, true, false, err);
- }
+ /* handle stream errors by closing the stream */
+ 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);
- return init_skip_frame_parser(t, 0);
- } else {
- return err;
- }
-}
-
-static void free_timeout(void* p) { gpr_free(p); }
-
+ return init_skip_frame_parser(t, 0);
+ } else {
+ return err;
+ }
+}
+
+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;
@@ -473,16 +473,16 @@ handle_metadata_add_failure(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
}
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_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);
-
+
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);
}
@@ -494,287 +494,287 @@ static grpc_error* on_initial_header(void* tp, grpc_mdelem md) {
if (GPR_UNLIKELY(new_size > metadata_size_limit)) {
return handle_metadata_size_limit_exceeded(t, s, md, new_size,
metadata_size_limit);
- } else {
+ } 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);
- }
- }
+ }
+ }
// Not timeout-related metadata, and no error occurred.
return GRPC_ERROR_NONE;
-}
-
+}
+
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_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);
-
+
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);
- gpr_log(GPR_INFO, "HTTP:%d:TRL:%s: %s: %s", s->id,
- t->is_client ? "CLI" : "SVR", key, value);
- gpr_free(key);
- gpr_free(value);
- }
-
- const size_t new_size = s->metadata_buffer[1].size + GRPC_MDELEM_LENGTH(md);
- const size_t metadata_size_limit =
- t->settings[GRPC_ACKED_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE];
- if (new_size > metadata_size_limit) {
- gpr_log(GPR_DEBUG,
- "received trailing metadata size exceeds limit (%" PRIuPTR
+ 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:TRL:%s: %s: %s", s->id,
+ t->is_client ? "CLI" : "SVR", key, value);
+ gpr_free(key);
+ gpr_free(value);
+ }
+
+ const size_t new_size = s->metadata_buffer[1].size + GRPC_MDELEM_LENGTH(md);
+ const size_t metadata_size_limit =
+ t->settings[GRPC_ACKED_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE];
+ if (new_size > metadata_size_limit) {
+ gpr_log(GPR_DEBUG,
+ "received trailing metadata size exceeds limit (%" PRIuPTR
" vs. %" PRIuPTR
"). Please note that the status is also included in the trailing "
"metadata and a large status message can also trigger this. "
"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 trailing 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);
- } else {
- grpc_error* error =
- grpc_chttp2_incoming_metadata_buffer_add(&s->metadata_buffer[1], md);
- if (error != GRPC_ERROR_NONE) {
- grpc_chttp2_cancel_stream(t, s, error);
- grpc_chttp2_parsing_become_skip_parser(t);
- s->seen_error = true;
- GRPC_MDELEM_UNREF(md);
- }
- }
+ new_size, metadata_size_limit);
+ grpc_chttp2_cancel_stream(
+ t, s,
+ grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "received trailing 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);
+ } else {
+ grpc_error* error =
+ grpc_chttp2_incoming_metadata_buffer_add(&s->metadata_buffer[1], md);
+ if (error != GRPC_ERROR_NONE) {
+ 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* init_header_frame_parser(grpc_chttp2_transport* t,
- int is_continuation) {
- uint8_t is_eoh =
- (t->incoming_frame_flags & GRPC_CHTTP2_DATA_FLAG_END_HEADERS) != 0;
- grpc_chttp2_stream* s;
-
- /* TODO(ctiller): when to increment header_frames_received? */
-
- if (is_eoh) {
- t->expect_continuation_stream_id = 0;
- } else {
- t->expect_continuation_stream_id = t->incoming_stream_id;
- }
-
- if (!is_continuation) {
- t->header_eof =
- (t->incoming_frame_flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM) != 0;
- }
-
- t->ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST;
-
- /* could be a new grpc_chttp2_stream or an existing grpc_chttp2_stream */
- s = grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
- if (s == nullptr) {
+}
+
+static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t,
+ int is_continuation) {
+ uint8_t is_eoh =
+ (t->incoming_frame_flags & GRPC_CHTTP2_DATA_FLAG_END_HEADERS) != 0;
+ grpc_chttp2_stream* s;
+
+ /* TODO(ctiller): when to increment header_frames_received? */
+
+ if (is_eoh) {
+ t->expect_continuation_stream_id = 0;
+ } else {
+ t->expect_continuation_stream_id = t->incoming_stream_id;
+ }
+
+ if (!is_continuation) {
+ t->header_eof =
+ (t->incoming_frame_flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM) != 0;
+ }
+
+ t->ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST;
+
+ /* could be a new grpc_chttp2_stream or an existing grpc_chttp2_stream */
+ s = grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
+ if (s == nullptr) {
if (GPR_UNLIKELY(is_continuation)) {
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_ERROR,
- "grpc_chttp2_stream disbanded before CONTINUATION received"));
- return init_skip_frame_parser(t, 1);
- }
- if (t->is_client) {
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_ERROR,
+ "grpc_chttp2_stream disbanded before CONTINUATION received"));
+ return init_skip_frame_parser(t, 1);
+ }
+ if (t->is_client) {
if (GPR_LIKELY((t->incoming_stream_id & 1) &&
t->incoming_stream_id < t->next_stream_id)) {
- /* this is an old (probably cancelled) grpc_chttp2_stream */
- } else {
- GRPC_CHTTP2_IF_TRACING(gpr_log(
- GPR_ERROR, "ignoring new grpc_chttp2_stream creation on client"));
- }
- grpc_error* err = init_skip_frame_parser(t, 1);
- if (t->incoming_frame_flags & GRPC_CHTTP2_FLAG_HAS_PRIORITY) {
- grpc_chttp2_hpack_parser_set_has_priority(&t->hpack_parser);
- }
- return err;
+ /* this is an old (probably cancelled) grpc_chttp2_stream */
+ } else {
+ GRPC_CHTTP2_IF_TRACING(gpr_log(
+ GPR_ERROR, "ignoring new grpc_chttp2_stream creation on client"));
+ }
+ grpc_error* err = init_skip_frame_parser(t, 1);
+ if (t->incoming_frame_flags & GRPC_CHTTP2_FLAG_HAS_PRIORITY) {
+ grpc_chttp2_hpack_parser_set_has_priority(&t->hpack_parser);
+ }
+ return err;
} else if (GPR_UNLIKELY(t->last_new_stream_id >= t->incoming_stream_id)) {
- GRPC_CHTTP2_IF_TRACING(gpr_log(
- GPR_ERROR,
- "ignoring out of order new grpc_chttp2_stream request on server; "
- "last grpc_chttp2_stream "
- "id=%d, new grpc_chttp2_stream id=%d",
- t->last_new_stream_id, t->incoming_stream_id));
- return init_skip_frame_parser(t, 1);
+ GRPC_CHTTP2_IF_TRACING(gpr_log(
+ GPR_ERROR,
+ "ignoring out of order new grpc_chttp2_stream request on server; "
+ "last grpc_chttp2_stream "
+ "id=%d, new grpc_chttp2_stream id=%d",
+ t->last_new_stream_id, t->incoming_stream_id));
+ return init_skip_frame_parser(t, 1);
} else if (GPR_UNLIKELY((t->incoming_stream_id & 1) == 0)) {
- GRPC_CHTTP2_IF_TRACING(gpr_log(
- GPR_ERROR,
- "ignoring grpc_chttp2_stream with non-client generated index %d",
- t->incoming_stream_id));
- return init_skip_frame_parser(t, 1);
+ GRPC_CHTTP2_IF_TRACING(gpr_log(
+ GPR_ERROR,
+ "ignoring grpc_chttp2_stream with non-client generated index %d",
+ t->incoming_stream_id));
+ return init_skip_frame_parser(t, 1);
} else if (GPR_UNLIKELY(
grpc_chttp2_stream_map_size(&t->stream_map) >=
t->settings[GRPC_ACKED_SETTINGS]
[GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS])) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Max stream count exceeded");
- }
- t->last_new_stream_id = t->incoming_stream_id;
- s = t->incoming_stream =
- grpc_chttp2_parsing_accept_stream(t, t->incoming_stream_id);
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Max stream count exceeded");
+ }
+ t->last_new_stream_id = t->incoming_stream_id;
+ s = t->incoming_stream =
+ grpc_chttp2_parsing_accept_stream(t, t->incoming_stream_id);
if (GPR_UNLIKELY(s == nullptr)) {
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_ERROR, "grpc_chttp2_stream not accepted"));
- return init_skip_frame_parser(t, 1);
- }
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_ERROR, "grpc_chttp2_stream not accepted"));
+ return init_skip_frame_parser(t, 1);
+ }
if (t->channelz_socket != nullptr) {
t->channelz_socket->RecordStreamStartedFromRemote();
}
- } else {
- t->incoming_stream = s;
- }
+ } else {
+ t->incoming_stream = s;
+ }
GPR_DEBUG_ASSERT(s != nullptr);
- s->stats.incoming.framing_bytes += 9;
+ s->stats.incoming.framing_bytes += 9;
if (GPR_UNLIKELY(s->read_closed)) {
- GRPC_CHTTP2_IF_TRACING(gpr_log(
- GPR_ERROR, "skipping already closed grpc_chttp2_stream header"));
- t->incoming_stream = nullptr;
- return init_skip_frame_parser(t, 1);
- }
- t->parser = grpc_chttp2_header_parser_parse;
- t->parser_data = &t->hpack_parser;
+ GRPC_CHTTP2_IF_TRACING(gpr_log(
+ GPR_ERROR, "skipping already closed grpc_chttp2_stream header"));
+ t->incoming_stream = nullptr;
+ return init_skip_frame_parser(t, 1);
+ }
+ t->parser = grpc_chttp2_header_parser_parse;
+ t->parser_data = &t->hpack_parser;
if (t->header_eof) {
s->eos_received = true;
}
- switch (s->header_frames_received) {
- case 0:
- if (t->is_client && t->header_eof) {
- GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "parsing Trailers-Only"));
- if (s->trailing_metadata_available != nullptr) {
- *s->trailing_metadata_available = true;
- }
- t->hpack_parser.on_header = on_trailing_header;
- } else {
- GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "parsing initial_metadata"));
- t->hpack_parser.on_header = on_initial_header;
- }
- break;
- case 1:
- GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "parsing trailing_metadata"));
- t->hpack_parser.on_header = on_trailing_header;
- break;
- case 2:
- gpr_log(GPR_ERROR, "too many header frames received");
- return init_skip_frame_parser(t, 1);
- }
- t->hpack_parser.on_header_user_data = t;
- t->hpack_parser.is_boundary = is_eoh;
- t->hpack_parser.is_eof = static_cast<uint8_t>(is_eoh ? t->header_eof : 0);
- if (!is_continuation &&
- (t->incoming_frame_flags & GRPC_CHTTP2_FLAG_HAS_PRIORITY)) {
- grpc_chttp2_hpack_parser_set_has_priority(&t->hpack_parser);
- }
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* init_window_update_frame_parser(grpc_chttp2_transport* t) {
- grpc_error* err = grpc_chttp2_window_update_parser_begin_frame(
- &t->simple.window_update, t->incoming_frame_size,
- t->incoming_frame_flags);
- if (err != GRPC_ERROR_NONE) return err;
- if (t->incoming_stream_id != 0) {
- grpc_chttp2_stream* s = t->incoming_stream =
- grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
- if (s == nullptr) {
- return init_skip_frame_parser(t, 0);
- }
- s->stats.incoming.framing_bytes += 9;
- }
- t->parser = grpc_chttp2_window_update_parser_parse;
- t->parser_data = &t->simple.window_update;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* init_ping_parser(grpc_chttp2_transport* t) {
- grpc_error* err = grpc_chttp2_ping_parser_begin_frame(
- &t->simple.ping, t->incoming_frame_size, t->incoming_frame_flags);
- if (err != GRPC_ERROR_NONE) return err;
- t->parser = grpc_chttp2_ping_parser_parse;
- t->parser_data = &t->simple.ping;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* init_rst_stream_parser(grpc_chttp2_transport* t) {
- grpc_error* err = grpc_chttp2_rst_stream_parser_begin_frame(
- &t->simple.rst_stream, t->incoming_frame_size, t->incoming_frame_flags);
- if (err != GRPC_ERROR_NONE) return err;
- grpc_chttp2_stream* s = t->incoming_stream =
- grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
- if (!t->incoming_stream) {
- return init_skip_frame_parser(t, 0);
- }
- s->stats.incoming.framing_bytes += 9;
- t->parser = grpc_chttp2_rst_stream_parser_parse;
- t->parser_data = &t->simple.rst_stream;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* init_goaway_parser(grpc_chttp2_transport* t) {
- grpc_error* err = grpc_chttp2_goaway_parser_begin_frame(
- &t->goaway_parser, t->incoming_frame_size, t->incoming_frame_flags);
- if (err != GRPC_ERROR_NONE) return err;
- t->parser = grpc_chttp2_goaway_parser_parse;
- t->parser_data = &t->goaway_parser;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* init_settings_frame_parser(grpc_chttp2_transport* t) {
- if (t->incoming_stream_id != 0) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Settings frame received for grpc_chttp2_stream");
- }
-
- grpc_error* err = grpc_chttp2_settings_parser_begin_frame(
- &t->simple.settings, t->incoming_frame_size, t->incoming_frame_flags,
- t->settings[GRPC_PEER_SETTINGS]);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- if (t->incoming_frame_flags & GRPC_CHTTP2_FLAG_ACK) {
- memcpy(t->settings[GRPC_ACKED_SETTINGS], t->settings[GRPC_SENT_SETTINGS],
- GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t));
- grpc_chttp2_hptbl_set_max_bytes(
- &t->hpack_parser.table,
- t->settings[GRPC_ACKED_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE]);
- t->sent_local_settings = 0;
- }
- t->parser = grpc_chttp2_settings_parser_parse;
- t->parser_data = &t->simple.settings;
- return GRPC_ERROR_NONE;
-}
-
+ switch (s->header_frames_received) {
+ case 0:
+ if (t->is_client && t->header_eof) {
+ GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "parsing Trailers-Only"));
+ if (s->trailing_metadata_available != nullptr) {
+ *s->trailing_metadata_available = true;
+ }
+ t->hpack_parser.on_header = on_trailing_header;
+ } else {
+ GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "parsing initial_metadata"));
+ t->hpack_parser.on_header = on_initial_header;
+ }
+ break;
+ case 1:
+ GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "parsing trailing_metadata"));
+ t->hpack_parser.on_header = on_trailing_header;
+ break;
+ case 2:
+ gpr_log(GPR_ERROR, "too many header frames received");
+ return init_skip_frame_parser(t, 1);
+ }
+ t->hpack_parser.on_header_user_data = t;
+ t->hpack_parser.is_boundary = is_eoh;
+ t->hpack_parser.is_eof = static_cast<uint8_t>(is_eoh ? t->header_eof : 0);
+ if (!is_continuation &&
+ (t->incoming_frame_flags & GRPC_CHTTP2_FLAG_HAS_PRIORITY)) {
+ grpc_chttp2_hpack_parser_set_has_priority(&t->hpack_parser);
+ }
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* init_window_update_frame_parser(grpc_chttp2_transport* t) {
+ grpc_error* err = grpc_chttp2_window_update_parser_begin_frame(
+ &t->simple.window_update, t->incoming_frame_size,
+ t->incoming_frame_flags);
+ if (err != GRPC_ERROR_NONE) return err;
+ if (t->incoming_stream_id != 0) {
+ grpc_chttp2_stream* s = t->incoming_stream =
+ grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
+ if (s == nullptr) {
+ return init_skip_frame_parser(t, 0);
+ }
+ s->stats.incoming.framing_bytes += 9;
+ }
+ t->parser = grpc_chttp2_window_update_parser_parse;
+ t->parser_data = &t->simple.window_update;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* init_ping_parser(grpc_chttp2_transport* t) {
+ grpc_error* err = grpc_chttp2_ping_parser_begin_frame(
+ &t->simple.ping, t->incoming_frame_size, t->incoming_frame_flags);
+ if (err != GRPC_ERROR_NONE) return err;
+ t->parser = grpc_chttp2_ping_parser_parse;
+ t->parser_data = &t->simple.ping;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* init_rst_stream_parser(grpc_chttp2_transport* t) {
+ grpc_error* err = grpc_chttp2_rst_stream_parser_begin_frame(
+ &t->simple.rst_stream, t->incoming_frame_size, t->incoming_frame_flags);
+ if (err != GRPC_ERROR_NONE) return err;
+ grpc_chttp2_stream* s = t->incoming_stream =
+ grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id);
+ if (!t->incoming_stream) {
+ return init_skip_frame_parser(t, 0);
+ }
+ s->stats.incoming.framing_bytes += 9;
+ t->parser = grpc_chttp2_rst_stream_parser_parse;
+ t->parser_data = &t->simple.rst_stream;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* init_goaway_parser(grpc_chttp2_transport* t) {
+ grpc_error* err = grpc_chttp2_goaway_parser_begin_frame(
+ &t->goaway_parser, t->incoming_frame_size, t->incoming_frame_flags);
+ if (err != GRPC_ERROR_NONE) return err;
+ t->parser = grpc_chttp2_goaway_parser_parse;
+ t->parser_data = &t->goaway_parser;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* init_settings_frame_parser(grpc_chttp2_transport* t) {
+ if (t->incoming_stream_id != 0) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Settings frame received for grpc_chttp2_stream");
+ }
+
+ grpc_error* err = grpc_chttp2_settings_parser_begin_frame(
+ &t->simple.settings, t->incoming_frame_size, t->incoming_frame_flags,
+ t->settings[GRPC_PEER_SETTINGS]);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ if (t->incoming_frame_flags & GRPC_CHTTP2_FLAG_ACK) {
+ memcpy(t->settings[GRPC_ACKED_SETTINGS], t->settings[GRPC_SENT_SETTINGS],
+ GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t));
+ grpc_chttp2_hptbl_set_max_bytes(
+ &t->hpack_parser.table,
+ t->settings[GRPC_ACKED_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE]);
+ t->sent_local_settings = 0;
+ }
+ t->parser = grpc_chttp2_settings_parser_parse;
+ t->parser_data = &t->simple.settings;
+ return GRPC_ERROR_NONE;
+}
+
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);
+ 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;
+ return err;
} else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, &unused)) {
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;
+ 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);
- } else {
- GRPC_ERROR_UNREF(err);
- }
- }
- return err;
-}
+ } else {
+ GRPC_ERROR_UNREF(err);
+ }
+ }
+ return 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 db79899dedc..675082ffe04 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
@@ -1,216 +1,216 @@
-/*
- *
- * 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/transport/chttp2/transport/chttp2_transport.h"
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-
-#include <grpc/support/log.h>
-
-static const char* stream_list_id_string(grpc_chttp2_stream_list_id id) {
- switch (id) {
- case GRPC_CHTTP2_LIST_WRITABLE:
- return "writable";
- case GRPC_CHTTP2_LIST_WRITING:
- return "writing";
- case GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT:
- return "stalled_by_transport";
- case GRPC_CHTTP2_LIST_STALLED_BY_STREAM:
- return "stalled_by_stream";
- case GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY:
- return "waiting_for_concurrency";
- case STREAM_LIST_COUNT:
- GPR_UNREACHABLE_CODE(return "unknown");
- }
- GPR_UNREACHABLE_CODE(return "unknown");
-}
-
-grpc_core::TraceFlag grpc_trace_http2_stream_state(false, "http2_stream_state");
-
-/* core list management */
-
-static bool stream_list_empty(grpc_chttp2_transport* t,
- grpc_chttp2_stream_list_id id) {
- return t->lists[id].head == nullptr;
-}
-
-static bool stream_list_pop(grpc_chttp2_transport* t,
- grpc_chttp2_stream** stream,
- grpc_chttp2_stream_list_id id) {
- grpc_chttp2_stream* s = t->lists[id].head;
- if (s) {
- grpc_chttp2_stream* new_head = s->links[id].next;
- GPR_ASSERT(s->included[id]);
- if (new_head) {
- t->lists[id].head = new_head;
- new_head->links[id].prev = nullptr;
- } else {
- t->lists[id].head = nullptr;
- t->lists[id].tail = nullptr;
- }
- s->included[id] = 0;
- }
- *stream = s;
+/*
+ *
+ * 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/transport/chttp2/transport/chttp2_transport.h"
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
+#include <grpc/support/log.h>
+
+static const char* stream_list_id_string(grpc_chttp2_stream_list_id id) {
+ switch (id) {
+ case GRPC_CHTTP2_LIST_WRITABLE:
+ return "writable";
+ case GRPC_CHTTP2_LIST_WRITING:
+ return "writing";
+ case GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT:
+ return "stalled_by_transport";
+ case GRPC_CHTTP2_LIST_STALLED_BY_STREAM:
+ return "stalled_by_stream";
+ case GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY:
+ return "waiting_for_concurrency";
+ case STREAM_LIST_COUNT:
+ GPR_UNREACHABLE_CODE(return "unknown");
+ }
+ GPR_UNREACHABLE_CODE(return "unknown");
+}
+
+grpc_core::TraceFlag grpc_trace_http2_stream_state(false, "http2_stream_state");
+
+/* core list management */
+
+static bool stream_list_empty(grpc_chttp2_transport* t,
+ grpc_chttp2_stream_list_id id) {
+ return t->lists[id].head == nullptr;
+}
+
+static bool stream_list_pop(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** stream,
+ grpc_chttp2_stream_list_id id) {
+ grpc_chttp2_stream* s = t->lists[id].head;
+ if (s) {
+ grpc_chttp2_stream* new_head = s->links[id].next;
+ GPR_ASSERT(s->included[id]);
+ if (new_head) {
+ t->lists[id].head = new_head;
+ new_head->links[id].prev = nullptr;
+ } else {
+ t->lists[id].head = nullptr;
+ t->lists[id].tail = nullptr;
+ }
+ s->included[id] = 0;
+ }
+ *stream = s;
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));
- }
- return s != nullptr;
-}
-
-static void stream_list_remove(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_chttp2_stream_list_id id) {
- GPR_ASSERT(s->included[id]);
- s->included[id] = 0;
- if (s->links[id].prev) {
- s->links[id].prev->links[id].next = s->links[id].next;
- } else {
- GPR_ASSERT(t->lists[id].head == s);
- t->lists[id].head = s->links[id].next;
- }
- if (s->links[id].next) {
- s->links[id].next->links[id].prev = s->links[id].prev;
- } else {
- t->lists[id].tail = s->links[id].prev;
- }
+ gpr_log(GPR_INFO, "%p[%d][%s]: pop from %s", t, s->id,
+ t->is_client ? "cli" : "svr", stream_list_id_string(id));
+ }
+ return s != nullptr;
+}
+
+static void stream_list_remove(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_chttp2_stream_list_id id) {
+ GPR_ASSERT(s->included[id]);
+ s->included[id] = 0;
+ if (s->links[id].prev) {
+ s->links[id].prev->links[id].next = s->links[id].next;
+ } else {
+ GPR_ASSERT(t->lists[id].head == s);
+ t->lists[id].head = s->links[id].next;
+ }
+ if (s->links[id].next) {
+ s->links[id].next->links[id].prev = s->links[id].prev;
+ } else {
+ t->lists[id].tail = s->links[id].prev;
+ }
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));
- }
-}
-
-static bool stream_list_maybe_remove(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
- grpc_chttp2_stream_list_id id) {
- if (s->included[id]) {
- stream_list_remove(t, s, id);
- return true;
- } else {
- return false;
- }
-}
-
-static void stream_list_add_tail(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s,
- grpc_chttp2_stream_list_id id) {
- grpc_chttp2_stream* old_tail;
- GPR_ASSERT(!s->included[id]);
- old_tail = t->lists[id].tail;
- s->links[id].next = nullptr;
- s->links[id].prev = old_tail;
- if (old_tail) {
- old_tail->links[id].next = s;
- } else {
- t->lists[id].head = s;
- }
- t->lists[id].tail = s;
- s->included[id] = 1;
+ gpr_log(GPR_INFO, "%p[%d][%s]: remove from %s", t, s->id,
+ t->is_client ? "cli" : "svr", stream_list_id_string(id));
+ }
+}
+
+static bool stream_list_maybe_remove(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
+ grpc_chttp2_stream_list_id id) {
+ if (s->included[id]) {
+ stream_list_remove(t, s, id);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+static void stream_list_add_tail(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s,
+ grpc_chttp2_stream_list_id id) {
+ grpc_chttp2_stream* old_tail;
+ GPR_ASSERT(!s->included[id]);
+ old_tail = t->lists[id].tail;
+ s->links[id].next = nullptr;
+ s->links[id].prev = old_tail;
+ if (old_tail) {
+ old_tail->links[id].next = s;
+ } else {
+ t->lists[id].head = s;
+ }
+ t->lists[id].tail = s;
+ s->included[id] = 1;
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));
- }
-}
-
-static bool stream_list_add(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_chttp2_stream_list_id id) {
- if (s->included[id]) {
- return false;
- }
- stream_list_add_tail(t, s, id);
- return true;
-}
-
-/* wrappers for specializations */
-
-bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- GPR_ASSERT(s->id != 0);
- return stream_list_add(t, s, GRPC_CHTTP2_LIST_WRITABLE);
-}
-
-bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s) {
- return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WRITABLE);
-}
-
-bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- return stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_WRITABLE);
-}
-
-bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- return stream_list_add(t, s, GRPC_CHTTP2_LIST_WRITING);
-}
-
-bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport* t) {
- return !stream_list_empty(t, GRPC_CHTTP2_LIST_WRITING);
-}
-
-bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s) {
- return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WRITING);
-}
-
-void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- stream_list_add(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY);
-}
-
-bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s) {
- return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY);
-}
-
-void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY);
-}
-
-void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- GPR_ASSERT(t->flow_control->flow_control_enabled());
- stream_list_add(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT);
-}
-
-bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s) {
- return stream_list_pop(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT);
-}
-
-void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT);
-}
-
-void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- GPR_ASSERT(t->flow_control->flow_control_enabled());
- stream_list_add(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM);
-}
-
-bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream** s) {
- return stream_list_pop(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM);
-}
-
-bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport* t,
- grpc_chttp2_stream* s) {
- return stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM);
-}
+ gpr_log(GPR_INFO, "%p[%d][%s]: add to %s", t, s->id,
+ t->is_client ? "cli" : "svr", stream_list_id_string(id));
+ }
+}
+
+static bool stream_list_add(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_chttp2_stream_list_id id) {
+ if (s->included[id]) {
+ return false;
+ }
+ stream_list_add_tail(t, s, id);
+ return true;
+}
+
+/* wrappers for specializations */
+
+bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ GPR_ASSERT(s->id != 0);
+ return stream_list_add(t, s, GRPC_CHTTP2_LIST_WRITABLE);
+}
+
+bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s) {
+ return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WRITABLE);
+}
+
+bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ return stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_WRITABLE);
+}
+
+bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ return stream_list_add(t, s, GRPC_CHTTP2_LIST_WRITING);
+}
+
+bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport* t) {
+ return !stream_list_empty(t, GRPC_CHTTP2_LIST_WRITING);
+}
+
+bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s) {
+ return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WRITING);
+}
+
+void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ stream_list_add(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY);
+}
+
+bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s) {
+ return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY);
+}
+
+void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY);
+}
+
+void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ GPR_ASSERT(t->flow_control->flow_control_enabled());
+ stream_list_add(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT);
+}
+
+bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s) {
+ return stream_list_pop(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT);
+}
+
+void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT);
+}
+
+void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ GPR_ASSERT(t->flow_control->flow_control_enabled());
+ stream_list_add(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM);
+}
+
+bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream** s) {
+ return stream_list_pop(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM);
+}
+
+bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s) {
+ return stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM);
+}
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 647214b94a0..b3b80ee74df 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
@@ -1,70 +1,70 @@
-/*
- *
- * 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/transport/chttp2/transport/stream_map.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map* map,
- size_t initial_capacity) {
+/*
+ *
+ * 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/transport/chttp2/transport/stream_map.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map* map,
+ size_t initial_capacity) {
GPR_DEBUG_ASSERT(initial_capacity > 1);
- map->keys =
- static_cast<uint32_t*>(gpr_malloc(sizeof(uint32_t) * initial_capacity));
- map->values =
- static_cast<void**>(gpr_malloc(sizeof(void*) * initial_capacity));
- map->count = 0;
- map->free = 0;
- map->capacity = initial_capacity;
-}
-
-void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map* map) {
- gpr_free(map->keys);
- gpr_free(map->values);
-}
-
-static size_t compact(uint32_t* keys, void** values, size_t count) {
- size_t i, out;
-
- for (i = 0, out = 0; i < count; i++) {
- if (values[i]) {
- keys[out] = keys[i];
- values[out] = values[i];
- out++;
- }
- }
-
- return out;
-}
-
-void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
- void* value) {
- size_t count = map->count;
- size_t capacity = map->capacity;
- uint32_t* keys = map->keys;
- void** values = map->values;
-
+ map->keys =
+ static_cast<uint32_t*>(gpr_malloc(sizeof(uint32_t) * initial_capacity));
+ map->values =
+ static_cast<void**>(gpr_malloc(sizeof(void*) * initial_capacity));
+ map->count = 0;
+ map->free = 0;
+ map->capacity = initial_capacity;
+}
+
+void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map* map) {
+ gpr_free(map->keys);
+ gpr_free(map->values);
+}
+
+static size_t compact(uint32_t* keys, void** values, size_t count) {
+ size_t i, out;
+
+ for (i = 0, out = 0; i < count; i++) {
+ if (values[i]) {
+ keys[out] = keys[i];
+ values[out] = values[i];
+ out++;
+ }
+ }
+
+ return out;
+}
+
+void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
+ void* value) {
+ size_t count = map->count;
+ size_t capacity = map->capacity;
+ uint32_t* keys = map->keys;
+ void** values = map->values;
+
// The first assertion ensures that the table is monotonically increasing.
- GPR_ASSERT(count == 0 || keys[count - 1] < key);
+ 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
@@ -74,59 +74,59 @@ void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
// 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) {
- count = compact(keys, values, count);
- map->free = 0;
- } else {
- /* resize when less than 25% of the table is free, because compaction
- won't help much */
+
+ if (count == capacity) {
+ if (map->free > capacity / 4) {
+ count = compact(keys, values, count);
+ map->free = 0;
+ } else {
+ /* resize when less than 25% of the table is free, because compaction
+ won't help much */
map->capacity = capacity = 2 * capacity;
- map->keys = keys = static_cast<uint32_t*>(
- gpr_realloc(keys, capacity * sizeof(uint32_t)));
- map->values = values =
- static_cast<void**>(gpr_realloc(values, capacity * sizeof(void*)));
- }
- }
-
- keys[count] = key;
- values[count] = value;
- map->count = count + 1;
-}
-
+ map->keys = keys = static_cast<uint32_t*>(
+ gpr_realloc(keys, capacity * sizeof(uint32_t)));
+ map->values = values =
+ static_cast<void**>(gpr_realloc(values, capacity * sizeof(void*)));
+ }
+ }
+
+ keys[count] = key;
+ values[count] = value;
+ map->count = count + 1;
+}
+
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;
- size_t mid_idx;
- uint32_t* keys = map->keys;
- void** values = map->values;
- uint32_t mid_key;
-
+static void** find(grpc_chttp2_stream_map* map, uint32_t key) {
+ size_t min_idx = 0;
+ size_t max_idx = map->count;
+ size_t mid_idx;
+ uint32_t* keys = map->keys;
+ void** values = map->values;
+ uint32_t mid_key;
+
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 */
- mid_idx = min_idx + ((max_idx - min_idx) / 2);
- mid_key = keys[mid_idx];
-
- if (mid_key < key) {
- min_idx = mid_idx + 1;
- } else if (mid_key > key) {
- max_idx = mid_idx;
- } else /* mid_key == key */
- {
- return &values[mid_idx];
- }
- }
-
+
+ while (min_idx < max_idx) {
+ /* find the midpoint, avoiding overflow */
+ mid_idx = min_idx + ((max_idx - min_idx) / 2);
+ mid_key = keys[mid_idx];
+
+ if (mid_key < key) {
+ min_idx = mid_idx + 1;
+ } else if (mid_key > key) {
+ max_idx = mid_idx;
+ } else /* mid_key == key */
+ {
+ return &values[mid_idx];
+ }
+ }
+
GPR_DEBUG_ASSERT(!strict_find);
- return nullptr;
-}
-
-void* grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map* map, uint32_t key) {
+ 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;
@@ -137,41 +137,41 @@ void* grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map* map, uint32_t key) {
defragmentation later */
if (map->free == map->count) {
map->free = map->count = 0;
- }
+ }
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) {
+ return out;
+}
+
+void* grpc_chttp2_stream_map_find(grpc_chttp2_stream_map* map, uint32_t key) {
void** pvalue = find<false>(map, key);
- return pvalue != nullptr ? *pvalue : nullptr;
-}
-
-size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map* map) {
- return map->count - map->free;
-}
-
-void* grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map* map) {
- if (map->count == map->free) {
- return nullptr;
- }
- if (map->free != 0) {
- map->count = compact(map->keys, map->values, map->count);
- map->free = 0;
- GPR_ASSERT(map->count > 0);
- }
- return map->values[(static_cast<size_t>(rand())) % map->count];
-}
-
-void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map* map,
- void (*f)(void* user_data, uint32_t key,
- void* value),
- void* user_data) {
- size_t i;
-
- for (i = 0; i < map->count; i++) {
- if (map->values[i]) {
- f(user_data, map->keys[i], map->values[i]);
- }
- }
-}
+ return pvalue != nullptr ? *pvalue : nullptr;
+}
+
+size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map* map) {
+ return map->count - map->free;
+}
+
+void* grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map* map) {
+ if (map->count == map->free) {
+ return nullptr;
+ }
+ if (map->free != 0) {
+ map->count = compact(map->keys, map->values, map->count);
+ map->free = 0;
+ GPR_ASSERT(map->count > 0);
+ }
+ return map->values[(static_cast<size_t>(rand())) % map->count];
+}
+
+void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map* map,
+ void (*f)(void* user_data, uint32_t key,
+ void* value),
+ void* user_data) {
+ size_t i;
+
+ for (i = 0; i < map->count; i++) {
+ if (map->values[i]) {
+ f(user_data, map->keys[i], map->values[i]);
+ }
+ }
+}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.h
index 485abd2d130..1b3498ceed4 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/stream_map.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -30,38 +30,38 @@
Adds are restricted to strictly higher keys than previously seen (this is
guaranteed by http2). */
struct grpc_chttp2_stream_map {
- uint32_t* keys;
- void** values;
+ uint32_t* keys;
+ void** values;
size_t count;
size_t free;
size_t capacity;
};
-void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map* map,
+void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map* map,
size_t initial_capacity);
-void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map* map);
+void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map* map);
/* Add a new key: given http2 semantics, new keys must always be greater than
existing keys - this is asserted */
-void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
- void* value);
+void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key,
+ void* value);
/* Delete an existing key - returns the previous value of the key if it existed,
or NULL otherwise */
-void* grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map* map, uint32_t key);
+void* grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map* map, uint32_t key);
/* Return an existing key, or NULL if it does not exist */
-void* grpc_chttp2_stream_map_find(grpc_chttp2_stream_map* map, uint32_t key);
+void* grpc_chttp2_stream_map_find(grpc_chttp2_stream_map* map, uint32_t key);
/* Return a random entry */
-void* grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map* map);
+void* grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map* map);
/* How many (populated) entries are in the stream map? */
-size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map* map);
+size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map* map);
/* Callback on each stream */
-void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map* map,
- void (*f)(void* user_data, uint32_t key,
- void* value),
- void* user_data);
+void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map* map,
+ void (*f)(void* user_data, uint32_t key,
+ void* value),
+ void* user_data);
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_STREAM_MAP_H */
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.cc
index d4b01788b94..a0cdbc486c9 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.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 <grpc/support/port_platform.h>
-
-#include "src/core/ext/transport/chttp2/transport/varint.h"
-
-uint32_t grpc_chttp2_hpack_varint_length(uint32_t tail_value) {
- if (tail_value < (1 << 7)) {
- return 2;
- } else if (tail_value < (1 << 14)) {
- return 3;
- } else if (tail_value < (1 << 21)) {
- return 4;
- } else if (tail_value < (1 << 28)) {
- return 5;
- } else {
- return 6;
- }
-}
-
-void grpc_chttp2_hpack_write_varint_tail(uint32_t tail_value, uint8_t* target,
- uint32_t tail_length) {
- switch (tail_length) {
- case 5:
- target[4] = static_cast<uint8_t>((tail_value >> 28) | 0x80);
- /* fallthrough */
- case 4:
- target[3] = static_cast<uint8_t>((tail_value >> 21) | 0x80);
- /* fallthrough */
- case 3:
- target[2] = static_cast<uint8_t>((tail_value >> 14) | 0x80);
- /* fallthrough */
- case 2:
- target[1] = static_cast<uint8_t>((tail_value >> 7) | 0x80);
- /* fallthrough */
- case 1:
- target[0] = static_cast<uint8_t>((tail_value) | 0x80);
- }
- target[tail_length - 1] &= 0x7f;
-}
+/*
+ *
+ * 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/transport/chttp2/transport/varint.h"
+
+uint32_t grpc_chttp2_hpack_varint_length(uint32_t tail_value) {
+ if (tail_value < (1 << 7)) {
+ return 2;
+ } else if (tail_value < (1 << 14)) {
+ return 3;
+ } else if (tail_value < (1 << 21)) {
+ return 4;
+ } else if (tail_value < (1 << 28)) {
+ return 5;
+ } else {
+ return 6;
+ }
+}
+
+void grpc_chttp2_hpack_write_varint_tail(uint32_t tail_value, uint8_t* target,
+ uint32_t tail_length) {
+ switch (tail_length) {
+ case 5:
+ target[4] = static_cast<uint8_t>((tail_value >> 28) | 0x80);
+ /* fallthrough */
+ case 4:
+ target[3] = static_cast<uint8_t>((tail_value >> 21) | 0x80);
+ /* fallthrough */
+ case 3:
+ target[2] = static_cast<uint8_t>((tail_value >> 14) | 0x80);
+ /* fallthrough */
+ case 2:
+ target[1] = static_cast<uint8_t>((tail_value >> 7) | 0x80);
+ /* fallthrough */
+ case 1:
+ target[0] = static_cast<uint8_t>((tail_value) | 0x80);
+ }
+ target[tail_length - 1] &= 0x7f;
+}
diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.h
index 5a2b670f065..c6c74964e56 100644
--- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.h
+++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/varint.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/core/ext/transport/chttp2/transport/writing.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc
index f8e21e8e159..8f852cc454c 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
@@ -1,161 +1,161 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/ext/transport/chttp2/transport/context_list.h"
-#include "src/core/ext/transport/chttp2/transport/internal.h"
-
-#include <limits.h>
-
-#include <grpc/support/log.h>
-
+#include "src/core/ext/transport/chttp2/transport/internal.h"
+
+#include <limits.h>
+
+#include <grpc/support/log.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"
-#include "src/core/lib/transport/http2_errors.h"
-
-static void add_to_write_list(grpc_chttp2_write_cb** list,
- grpc_chttp2_write_cb* cb) {
- cb->next = *list;
- *list = cb;
-}
-
-static void finish_write_cb(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- grpc_chttp2_write_cb* cb, grpc_error* error) {
- grpc_chttp2_complete_closure_step(t, s, &cb->closure, error,
- "finish_write_cb");
- cb->next = t->write_cb_pool;
- t->write_cb_pool = cb;
-}
-
-static void maybe_initiate_ping(grpc_chttp2_transport* t) {
- grpc_chttp2_ping_queue* pq = &t->ping_queue;
- if (grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_NEXT])) {
- /* no ping needed: wait */
- return;
- }
- if (!grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_INFLIGHT])) {
- /* ping already in-flight: wait */
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/transport/http2_errors.h"
+
+static void add_to_write_list(grpc_chttp2_write_cb** list,
+ grpc_chttp2_write_cb* cb) {
+ cb->next = *list;
+ *list = cb;
+}
+
+static void finish_write_cb(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ grpc_chttp2_write_cb* cb, grpc_error* error) {
+ grpc_chttp2_complete_closure_step(t, s, &cb->closure, error,
+ "finish_write_cb");
+ cb->next = t->write_cb_pool;
+ t->write_cb_pool = cb;
+}
+
+static void maybe_initiate_ping(grpc_chttp2_transport* t) {
+ grpc_chttp2_ping_queue* pq = &t->ping_queue;
+ if (grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_NEXT])) {
+ /* no ping needed: wait */
+ return;
+ }
+ if (!grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_INFLIGHT])) {
+ /* ping already in-flight: wait */
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",
t->is_client ? "CLIENT" : "SERVER", t->peer_string.c_str());
- }
- return;
- }
- 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 */
+ }
+ return;
+ }
+ 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) ||
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",
t->is_client ? "CLIENT" : "SERVER", t->peer_string.c_str(),
- t->ping_state.pings_before_data_required,
- t->ping_policy.max_pings_without_data);
- }
- return;
- }
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
-
- grpc_millis next_allowed_ping_interval =
- (t->keepalive_permit_without_calls == 0 &&
- grpc_chttp2_stream_map_size(&t->stream_map) == 0)
- ? 7200 * GPR_MS_PER_SEC
+ t->ping_state.pings_before_data_required,
+ t->ping_policy.max_pings_without_data);
+ }
+ return;
+ }
+ grpc_millis now = grpc_core::ExecCtx::Get()->Now();
+
+ grpc_millis next_allowed_ping_interval =
+ (t->keepalive_permit_without_calls == 0 &&
+ grpc_chttp2_stream_map_size(&t->stream_map) == 0)
+ ? 7200 * GPR_MS_PER_SEC
: (t->ping_policy.min_sent_ping_interval_without_data +
GPR_MS_PER_SEC); /* A second is added to deal with network delays
and timing imprecision */
- grpc_millis next_allowed_ping =
- t->ping_state.last_ping_sent_time + next_allowed_ping_interval;
-
- if (next_allowed_ping > now) {
- /* not enough elapsed time between successive pings */
+ grpc_millis next_allowed_ping =
+ t->ping_state.last_ping_sent_time + next_allowed_ping_interval;
+
+ if (next_allowed_ping > now) {
+ /* not enough elapsed time between successive pings */
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,
+ gpr_log(GPR_INFO,
"%s: Ping delayed [%s]: not enough time elapsed since last ping. "
- " Last ping %f: Next ping %f: Now %f",
+ " Last ping %f: Next ping %f: Now %f",
t->is_client ? "CLIENT" : "SERVER", t->peer_string.c_str(),
- static_cast<double>(t->ping_state.last_ping_sent_time),
- static_cast<double>(next_allowed_ping), static_cast<double>(now));
- }
- 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");
+ static_cast<double>(t->ping_state.last_ping_sent_time),
+ static_cast<double>(next_allowed_ping), static_cast<double>(now));
+ }
+ 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_timer_init(&t->ping_state.delayed_ping_timer, next_allowed_ping,
- &t->retry_initiate_ping_locked);
- }
- return;
- }
-
- pq->inflight_id = t->ping_ctr;
- t->ping_ctr++;
+ grpc_timer_init(&t->ping_state.delayed_ping_timer, next_allowed_ping,
+ &t->retry_initiate_ping_locked);
+ }
+ return;
+ }
+
+ pq->inflight_id = t->ping_ctr;
+ t->ping_ctr++;
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;
+ 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) ||
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",
t->is_client ? "CLIENT" : "SERVER", t->peer_string.c_str(),
- t->ping_state.pings_before_data_required,
- t->ping_policy.max_pings_without_data);
- }
- t->ping_state.pings_before_data_required -=
- (t->ping_state.pings_before_data_required != 0);
-}
-
-static bool update_list(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- int64_t send_bytes, grpc_chttp2_write_cb** list,
- int64_t* ctr, grpc_error* error) {
- bool sched_any = false;
- grpc_chttp2_write_cb* cb = *list;
- *list = nullptr;
- *ctr += send_bytes;
- while (cb) {
- grpc_chttp2_write_cb* next = cb->next;
- if (cb->call_at_byte <= *ctr) {
- sched_any = true;
- finish_write_cb(t, s, cb, GRPC_ERROR_REF(error));
- } else {
- add_to_write_list(list, cb);
- }
- cb = next;
- }
- GRPC_ERROR_UNREF(error);
- return sched_any;
-}
-
-static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
- const char* staller) {
+ t->ping_state.pings_before_data_required,
+ t->ping_policy.max_pings_without_data);
+ }
+ t->ping_state.pings_before_data_required -=
+ (t->ping_state.pings_before_data_required != 0);
+}
+
+static bool update_list(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ int64_t send_bytes, grpc_chttp2_write_cb** list,
+ int64_t* ctr, grpc_error* error) {
+ bool sched_any = false;
+ grpc_chttp2_write_cb* cb = *list;
+ *list = nullptr;
+ *ctr += send_bytes;
+ while (cb) {
+ grpc_chttp2_write_cb* next = cb->next;
+ if (cb->call_at_byte <= *ctr) {
+ sched_any = true;
+ finish_write_cb(t, s, cb, GRPC_ERROR_REF(error));
+ } else {
+ add_to_write_list(list, cb);
+ }
+ cb = next;
+ }
+ GRPC_ERROR_UNREF(error);
+ return sched_any;
+}
+
+static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
+ const char* staller) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace)) {
gpr_log(
GPR_DEBUG,
@@ -182,162 +182,162 @@ static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s,
[GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE]),
s->flow_control->remote_window_delta());
}
-}
-
-/* How many bytes would we like to put on the wire during a single syscall */
+}
+
+/* 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*/) {
- return 1024 * 1024;
-}
-
-// Returns true if initial_metadata contains only default headers.
-static bool is_default_initial_metadata(grpc_metadata_batch* initial_metadata) {
- return initial_metadata->list.default_count == initial_metadata->list.count;
-}
-
-namespace {
-class StreamWriteContext;
-
-class WriteContext {
- public:
- WriteContext(grpc_chttp2_transport* t) : t_(t) {
- GRPC_STATS_INC_HTTP2_WRITES_BEGUN();
- GPR_TIMER_SCOPE("grpc_chttp2_begin_write", 0);
- }
-
- // TODO(ctiller): make this the destructor
- void FlushStats() {
- GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE(
- initial_metadata_writes_);
- GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(message_writes_);
- GRPC_STATS_INC_HTTP2_SEND_TRAILING_METADATA_PER_WRITE(
- trailing_metadata_writes_);
- GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(flow_control_writes_);
- }
-
- void FlushSettings() {
- if (t_->dirtied_local_settings && !t_->sent_local_settings) {
- grpc_slice_buffer_add(
- &t_->outbuf, grpc_chttp2_settings_create(
- t_->settings[GRPC_SENT_SETTINGS],
- t_->settings[GRPC_LOCAL_SETTINGS],
- t_->force_send_settings, GRPC_CHTTP2_NUM_SETTINGS));
- t_->force_send_settings = false;
- t_->dirtied_local_settings = false;
- t_->sent_local_settings = true;
- GRPC_STATS_INC_HTTP2_SETTINGS_WRITES();
- }
- }
-
- void FlushQueuedBuffers() {
- /* simple writes are queued to qbuf, and flushed here */
- grpc_slice_buffer_move_into(&t_->qbuf, &t_->outbuf);
+ return 1024 * 1024;
+}
+
+// Returns true if initial_metadata contains only default headers.
+static bool is_default_initial_metadata(grpc_metadata_batch* initial_metadata) {
+ return initial_metadata->list.default_count == initial_metadata->list.count;
+}
+
+namespace {
+class StreamWriteContext;
+
+class WriteContext {
+ public:
+ WriteContext(grpc_chttp2_transport* t) : t_(t) {
+ GRPC_STATS_INC_HTTP2_WRITES_BEGUN();
+ GPR_TIMER_SCOPE("grpc_chttp2_begin_write", 0);
+ }
+
+ // TODO(ctiller): make this the destructor
+ void FlushStats() {
+ GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE(
+ initial_metadata_writes_);
+ GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(message_writes_);
+ GRPC_STATS_INC_HTTP2_SEND_TRAILING_METADATA_PER_WRITE(
+ trailing_metadata_writes_);
+ GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(flow_control_writes_);
+ }
+
+ void FlushSettings() {
+ if (t_->dirtied_local_settings && !t_->sent_local_settings) {
+ grpc_slice_buffer_add(
+ &t_->outbuf, grpc_chttp2_settings_create(
+ t_->settings[GRPC_SENT_SETTINGS],
+ t_->settings[GRPC_LOCAL_SETTINGS],
+ t_->force_send_settings, GRPC_CHTTP2_NUM_SETTINGS));
+ t_->force_send_settings = false;
+ t_->dirtied_local_settings = false;
+ t_->sent_local_settings = true;
+ GRPC_STATS_INC_HTTP2_SETTINGS_WRITES();
+ }
+ }
+
+ 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;
- GPR_ASSERT(t_->qbuf.count == 0);
- }
-
- void FlushWindowUpdates() {
- uint32_t transport_announce =
- t_->flow_control->MaybeSendUpdate(t_->outbuf.count > 0);
- if (transport_announce) {
- grpc_transport_one_way_stats throwaway_stats;
- grpc_slice_buffer_add(
- &t_->outbuf, grpc_chttp2_window_update_create(0, transport_announce,
- &throwaway_stats));
+ GPR_ASSERT(t_->qbuf.count == 0);
+ }
+
+ void FlushWindowUpdates() {
+ uint32_t transport_announce =
+ t_->flow_control->MaybeSendUpdate(t_->outbuf.count > 0);
+ if (transport_announce) {
+ grpc_transport_one_way_stats throwaway_stats;
+ grpc_slice_buffer_add(
+ &t_->outbuf, grpc_chttp2_window_update_create(0, transport_announce,
+ &throwaway_stats));
grpc_chttp2_reset_ping_clock(t_);
- }
- }
-
- void FlushPingAcks() {
- for (size_t i = 0; i < t_->ping_ack_count; i++) {
- grpc_slice_buffer_add(&t_->outbuf,
- grpc_chttp2_ping_create(true, t_->ping_acks[i]));
- }
- t_->ping_ack_count = 0;
- }
-
- void EnactHpackSettings() {
- grpc_chttp2_hpack_compressor_set_max_table_size(
- &t_->hpack_compressor,
- t_->settings[GRPC_PEER_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE]);
- }
-
- void UpdateStreamsNoLongerStalled() {
- grpc_chttp2_stream* s;
- 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)) {
+ }
+ }
+
+ void FlushPingAcks() {
+ for (size_t i = 0; i < t_->ping_ack_count; i++) {
+ grpc_slice_buffer_add(&t_->outbuf,
+ grpc_chttp2_ping_create(true, t_->ping_acks[i]));
+ }
+ t_->ping_ack_count = 0;
+ }
+
+ void EnactHpackSettings() {
+ grpc_chttp2_hpack_compressor_set_max_table_size(
+ &t_->hpack_compressor,
+ t_->settings[GRPC_PEER_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE]);
+ }
+
+ void UpdateStreamsNoLongerStalled() {
+ grpc_chttp2_stream* s;
+ 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()) {
- grpc_chttp2_list_remove_writable_stream(t_, s);
- }
- }
- }
- }
-
- grpc_chttp2_stream* NextStream() {
- if (t_->outbuf.length > target_write_size(t_)) {
- result_.partial = true;
- return nullptr;
- }
-
- grpc_chttp2_stream* s;
- if (!grpc_chttp2_list_pop_writable_stream(t_, &s)) {
- return nullptr;
- }
-
- return s;
- }
-
- void IncInitialMetadataWrites() { ++initial_metadata_writes_; }
- void IncWindowUpdateWrites() { ++flow_control_writes_; }
- void IncMessageWrites() { ++message_writes_; }
- void IncTrailingMetadataWrites() { ++trailing_metadata_writes_; }
-
- void NoteScheduledResults() { result_.early_results_scheduled = true; }
-
- grpc_chttp2_transport* transport() const { return t_; }
-
- grpc_chttp2_begin_write_result Result() {
- result_.writing = t_->outbuf.count > 0;
- return result_;
- }
-
- private:
- grpc_chttp2_transport* const t_;
-
- /* stats histogram counters: we increment these throughout this function,
- and at the end publish to the central stats histograms */
- int flow_control_writes_ = 0;
- int initial_metadata_writes_ = 0;
- int trailing_metadata_writes_ = 0;
- int message_writes_ = 0;
- grpc_chttp2_begin_write_result result_ = {false, false, false};
-};
-
-class DataSendContext {
- public:
- DataSendContext(WriteContext* write_context, grpc_chttp2_transport* t,
- grpc_chttp2_stream* s)
- : write_context_(write_context),
- t_(t),
- s_(s),
- sending_bytes_before_(s_->sending_bytes) {}
-
- uint32_t stream_remote_window() const {
- return static_cast<uint32_t> GPR_MAX(
- 0, s_->flow_control->remote_window_delta() +
- (int64_t)t_->settings[GRPC_PEER_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE]);
- }
-
- uint32_t max_outgoing() const {
- return static_cast<uint32_t> GPR_MIN(
- t_->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE],
- GPR_MIN(stream_remote_window(), t_->flow_control->remote_window()));
- }
-
- bool AnyOutgoing() const { return max_outgoing() > 0; }
-
+ grpc_chttp2_list_remove_writable_stream(t_, s);
+ }
+ }
+ }
+ }
+
+ grpc_chttp2_stream* NextStream() {
+ if (t_->outbuf.length > target_write_size(t_)) {
+ result_.partial = true;
+ return nullptr;
+ }
+
+ grpc_chttp2_stream* s;
+ if (!grpc_chttp2_list_pop_writable_stream(t_, &s)) {
+ return nullptr;
+ }
+
+ return s;
+ }
+
+ void IncInitialMetadataWrites() { ++initial_metadata_writes_; }
+ void IncWindowUpdateWrites() { ++flow_control_writes_; }
+ void IncMessageWrites() { ++message_writes_; }
+ void IncTrailingMetadataWrites() { ++trailing_metadata_writes_; }
+
+ void NoteScheduledResults() { result_.early_results_scheduled = true; }
+
+ grpc_chttp2_transport* transport() const { return t_; }
+
+ grpc_chttp2_begin_write_result Result() {
+ result_.writing = t_->outbuf.count > 0;
+ return result_;
+ }
+
+ private:
+ grpc_chttp2_transport* const t_;
+
+ /* stats histogram counters: we increment these throughout this function,
+ and at the end publish to the central stats histograms */
+ int flow_control_writes_ = 0;
+ int initial_metadata_writes_ = 0;
+ int trailing_metadata_writes_ = 0;
+ int message_writes_ = 0;
+ grpc_chttp2_begin_write_result result_ = {false, false, false};
+};
+
+class DataSendContext {
+ public:
+ DataSendContext(WriteContext* write_context, grpc_chttp2_transport* t,
+ grpc_chttp2_stream* s)
+ : write_context_(write_context),
+ t_(t),
+ s_(s),
+ sending_bytes_before_(s_->sending_bytes) {}
+
+ uint32_t stream_remote_window() const {
+ return static_cast<uint32_t> GPR_MAX(
+ 0, s_->flow_control->remote_window_delta() +
+ (int64_t)t_->settings[GRPC_PEER_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE]);
+ }
+
+ uint32_t max_outgoing() const {
+ return static_cast<uint32_t> GPR_MIN(
+ t_->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE],
+ GPR_MIN(stream_remote_window(), t_->flow_control->remote_window()));
+ }
+
+ 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);
@@ -351,133 +351,133 @@ class DataSendContext {
s_->sending_bytes += send_bytes;
}
- void FlushCompressedBytes() {
+ void FlushCompressedBytes() {
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 =
- (send_bytes == s_->compressed_data_buffer.length &&
- s_->flow_controlled_buffer.length == 0 &&
- s_->fetching_send_message == nullptr);
- if (is_last_data_frame && s_->send_trailing_metadata != nullptr &&
- s_->stream_compression_ctx != nullptr) {
+ uint32_t send_bytes = static_cast<uint32_t> GPR_MIN(
+ max_outgoing(), s_->compressed_data_buffer.length);
+ bool is_last_data_frame =
+ (send_bytes == s_->compressed_data_buffer.length &&
+ s_->flow_controlled_buffer.length == 0 &&
+ s_->fetching_send_message == nullptr);
+ if (is_last_data_frame && s_->send_trailing_metadata != nullptr &&
+ s_->stream_compression_ctx != nullptr) {
if (GPR_UNLIKELY(!grpc_stream_compress(
- s_->stream_compression_ctx, &s_->flow_controlled_buffer,
- &s_->compressed_data_buffer, nullptr, MAX_SIZE_T,
+ s_->stream_compression_ctx, &s_->flow_controlled_buffer,
+ &s_->compressed_data_buffer, nullptr, MAX_SIZE_T,
GRPC_STREAM_COMPRESSION_FLUSH_FINISH))) {
- gpr_log(GPR_ERROR, "Stream compression failed.");
- }
- grpc_stream_compression_context_destroy(s_->stream_compression_ctx);
- s_->stream_compression_ctx = nullptr;
- /* After finish, bytes in s->compressed_data_buffer may be
- * more than max_outgoing. Start another round of the current
- * while loop so that send_bytes and is_last_data_frame are
- * recalculated. */
- return;
- }
- is_last_frame_ = is_last_data_frame &&
- s_->send_trailing_metadata != nullptr &&
- grpc_metadata_batch_is_empty(s_->send_trailing_metadata);
- grpc_chttp2_encode_data(s_->id, &s_->compressed_data_buffer, send_bytes,
- is_last_frame_, &s_->stats.outgoing, &t_->outbuf);
- s_->flow_control->SentData(send_bytes);
- if (s_->compressed_data_buffer.length == 0) {
- s_->sending_bytes += s_->uncompressed_data_size;
- }
- }
-
- void CompressMoreBytes() {
+ gpr_log(GPR_ERROR, "Stream compression failed.");
+ }
+ grpc_stream_compression_context_destroy(s_->stream_compression_ctx);
+ s_->stream_compression_ctx = nullptr;
+ /* After finish, bytes in s->compressed_data_buffer may be
+ * more than max_outgoing. Start another round of the current
+ * while loop so that send_bytes and is_last_data_frame are
+ * recalculated. */
+ return;
+ }
+ is_last_frame_ = is_last_data_frame &&
+ s_->send_trailing_metadata != nullptr &&
+ grpc_metadata_batch_is_empty(s_->send_trailing_metadata);
+ grpc_chttp2_encode_data(s_->id, &s_->compressed_data_buffer, send_bytes,
+ is_last_frame_, &s_->stats.outgoing, &t_->outbuf);
+ s_->flow_control->SentData(send_bytes);
+ if (s_->compressed_data_buffer.length == 0) {
+ s_->sending_bytes += s_->uncompressed_data_size;
+ }
+ }
+
+ void CompressMoreBytes() {
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);
- }
- s_->uncompressed_data_size = s_->flow_controlled_buffer.length;
+ if (s_->stream_compression_ctx == nullptr) {
+ s_->stream_compression_ctx =
+ grpc_stream_compression_context_create(s_->stream_compression_method);
+ }
+ s_->uncompressed_data_size = s_->flow_controlled_buffer.length;
if (GPR_UNLIKELY(!grpc_stream_compress(
s_->stream_compression_ctx, &s_->flow_controlled_buffer,
&s_->compressed_data_buffer, nullptr, MAX_SIZE_T,
GRPC_STREAM_COMPRESSION_FLUSH_SYNC))) {
- gpr_log(GPR_ERROR, "Stream compression failed.");
- }
- }
-
- bool is_last_frame() const { return is_last_frame_; }
-
- void CallCallbacks() {
- if (update_list(
- t_, s_,
- static_cast<int64_t>(s_->sending_bytes - sending_bytes_before_),
- &s_->on_flow_controlled_cbs, &s_->flow_controlled_bytes_flowed,
- GRPC_ERROR_NONE)) {
- write_context_->NoteScheduledResults();
- }
- }
-
- private:
- WriteContext* write_context_;
- grpc_chttp2_transport* t_;
- grpc_chttp2_stream* s_;
- const size_t sending_bytes_before_;
- bool is_last_frame_ = false;
-};
-
-class StreamWriteContext {
- public:
- StreamWriteContext(WriteContext* write_context, grpc_chttp2_stream* s)
- : write_context_(write_context), t_(write_context->transport()), s_(s) {
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_INFO, "W:%p %s[%d] im-(sent,send)=(%d,%d) announce=%d", t_,
- t_->is_client ? "CLIENT" : "SERVER", s->id,
- s->sent_initial_metadata, s->send_initial_metadata != nullptr,
- (int)(s->flow_control->local_window_delta() -
- s->flow_control->announced_window_delta())));
- }
-
- void FlushInitialMetadata() {
- /* send initial metadata if it's available */
- if (s_->sent_initial_metadata) return;
- if (s_->send_initial_metadata == nullptr) return;
-
- // We skip this on the server side if there is no custom initial
- // metadata, there are no messages to send, and we are also sending
- // trailing metadata. This results in a Trailers-Only response,
- // which is required for retries, as per:
- // 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 &&
+ gpr_log(GPR_ERROR, "Stream compression failed.");
+ }
+ }
+
+ bool is_last_frame() const { return is_last_frame_; }
+
+ void CallCallbacks() {
+ if (update_list(
+ t_, s_,
+ static_cast<int64_t>(s_->sending_bytes - sending_bytes_before_),
+ &s_->on_flow_controlled_cbs, &s_->flow_controlled_bytes_flowed,
+ GRPC_ERROR_NONE)) {
+ write_context_->NoteScheduledResults();
+ }
+ }
+
+ private:
+ WriteContext* write_context_;
+ grpc_chttp2_transport* t_;
+ grpc_chttp2_stream* s_;
+ const size_t sending_bytes_before_;
+ bool is_last_frame_ = false;
+};
+
+class StreamWriteContext {
+ public:
+ StreamWriteContext(WriteContext* write_context, grpc_chttp2_stream* s)
+ : write_context_(write_context), t_(write_context->transport()), s_(s) {
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_INFO, "W:%p %s[%d] im-(sent,send)=(%d,%d) announce=%d", t_,
+ t_->is_client ? "CLIENT" : "SERVER", s->id,
+ s->sent_initial_metadata, s->send_initial_metadata != nullptr,
+ (int)(s->flow_control->local_window_delta() -
+ s->flow_control->announced_window_delta())));
+ }
+
+ void FlushInitialMetadata() {
+ /* send initial metadata if it's available */
+ if (s_->sent_initial_metadata) return;
+ if (s_->send_initial_metadata == nullptr) return;
+
+ // We skip this on the server side if there is no custom initial
+ // metadata, there are no messages to send, and we are also sending
+ // trailing metadata. This results in a Trailers-Only response,
+ // which is required for retries, as per:
+ // 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 &&
- s_->send_trailing_metadata != nullptr &&
- is_default_initial_metadata(s_->send_initial_metadata)) {
- ConvertInitialMetadataToTrailingMetadata();
- } else {
- grpc_encode_header_options hopt = {
- s_->id, // stream_id
- false, // is_eof
- t_->settings[GRPC_PEER_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA] !=
- 0, // use_true_binary_metadata
- t_->settings[GRPC_PEER_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE], // max_frame_size
- &s_->stats.outgoing // stats
- };
- grpc_chttp2_encode_header(&t_->hpack_compressor, nullptr, 0,
- s_->send_initial_metadata, &hopt, &t_->outbuf);
+ s_->send_trailing_metadata != nullptr &&
+ is_default_initial_metadata(s_->send_initial_metadata)) {
+ ConvertInitialMetadataToTrailingMetadata();
+ } else {
+ grpc_encode_header_options hopt = {
+ s_->id, // stream_id
+ false, // is_eof
+ t_->settings[GRPC_PEER_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA] !=
+ 0, // use_true_binary_metadata
+ t_->settings[GRPC_PEER_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE], // max_frame_size
+ &s_->stats.outgoing // stats
+ };
+ grpc_chttp2_encode_header(&t_->hpack_compressor, nullptr, 0,
+ s_->send_initial_metadata, &hopt, &t_->outbuf);
grpc_chttp2_reset_ping_clock(t_);
- write_context_->IncInitialMetadataWrites();
- }
-
- s_->send_initial_metadata = nullptr;
- s_->sent_initial_metadata = true;
- write_context_->NoteScheduledResults();
- grpc_chttp2_complete_closure_step(
- t_, s_, &s_->send_initial_metadata_finished, GRPC_ERROR_NONE,
- "send_initial_metadata_finished");
- }
-
+ write_context_->IncInitialMetadataWrites();
+ }
+
+ s_->send_initial_metadata = nullptr;
+ s_->sent_initial_metadata = true;
+ write_context_->NoteScheduledResults();
+ grpc_chttp2_complete_closure_step(
+ t_, s_, &s_->send_initial_metadata_finished, GRPC_ERROR_NONE,
+ "send_initial_metadata_finished");
+ }
+
size_t compressed_data_buffer_len() {
return s_->stream_compression_method ==
GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS
@@ -485,45 +485,45 @@ class StreamWriteContext {
: s_->compressed_data_buffer.length;
}
- void FlushWindowUpdates() {
- /* send any window updates */
- const uint32_t stream_announce = s_->flow_control->MaybeSendUpdate();
- if (stream_announce == 0) return;
-
- grpc_slice_buffer_add(
- &t_->outbuf, grpc_chttp2_window_update_create(s_->id, stream_announce,
- &s_->stats.outgoing));
+ void FlushWindowUpdates() {
+ /* send any window updates */
+ const uint32_t stream_announce = s_->flow_control->MaybeSendUpdate();
+ if (stream_announce == 0) return;
+
+ grpc_slice_buffer_add(
+ &t_->outbuf, grpc_chttp2_window_update_create(s_->id, stream_announce,
+ &s_->stats.outgoing));
grpc_chttp2_reset_ping_clock(t_);
- write_context_->IncWindowUpdateWrites();
- }
-
- void FlushData() {
- if (!s_->sent_initial_metadata) return;
-
- if (s_->flow_controlled_buffer.length == 0 &&
+ write_context_->IncWindowUpdateWrites();
+ }
+
+ void FlushData() {
+ if (!s_->sent_initial_metadata) return;
+
+ if (s_->flow_controlled_buffer.length == 0 &&
compressed_data_buffer_len() == 0) {
- return; // early out: nothing to do
- }
-
- DataSendContext data_send_context(write_context_, t_, s_);
-
- if (!data_send_context.AnyOutgoing()) {
- if (t_->flow_control->remote_window() <= 0) {
- report_stall(t_, s_, "transport");
- grpc_chttp2_list_add_stalled_by_transport(t_, s_);
- } else if (data_send_context.stream_remote_window() <= 0) {
- report_stall(t_, s_, "stream");
- grpc_chttp2_list_add_stalled_by_stream(t_, s_);
- }
- return; // early out: nothing to do
- }
-
+ return; // early out: nothing to do
+ }
+
+ DataSendContext data_send_context(write_context_, t_, s_);
+
+ if (!data_send_context.AnyOutgoing()) {
+ if (t_->flow_control->remote_window() <= 0) {
+ report_stall(t_, s_, "transport");
+ grpc_chttp2_list_add_stalled_by_transport(t_, s_);
+ } else if (data_send_context.stream_remote_window() <= 0) {
+ report_stall(t_, s_, "stream");
+ grpc_chttp2_list_add_stalled_by_stream(t_, s_);
+ }
+ 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) &&
@@ -534,125 +534,125 @@ class StreamWriteContext {
data_send_context.CompressMoreBytes();
}
}
- }
+ }
grpc_chttp2_reset_ping_clock(t_);
- if (data_send_context.is_last_frame()) {
- SentLastFrame();
- }
- data_send_context.CallCallbacks();
- stream_became_writable_ = true;
- if (s_->flow_controlled_buffer.length > 0 ||
+ if (data_send_context.is_last_frame()) {
+ SentLastFrame();
+ }
+ data_send_context.CallCallbacks();
+ stream_became_writable_ = true;
+ if (s_->flow_controlled_buffer.length > 0 ||
compressed_data_buffer_len() > 0) {
- GRPC_CHTTP2_STREAM_REF(s_, "chttp2_writing:fork");
- grpc_chttp2_list_add_writable_stream(t_, s_);
- }
- write_context_->IncMessageWrites();
- }
-
- void FlushTrailingMetadata() {
- if (!s_->sent_initial_metadata) return;
-
- if (s_->send_trailing_metadata == nullptr) return;
- if (s_->fetching_send_message != nullptr) return;
- if (s_->flow_controlled_buffer.length != 0) return;
+ GRPC_CHTTP2_STREAM_REF(s_, "chttp2_writing:fork");
+ grpc_chttp2_list_add_writable_stream(t_, s_);
+ }
+ write_context_->IncMessageWrites();
+ }
+
+ void FlushTrailingMetadata() {
+ if (!s_->sent_initial_metadata) return;
+
+ 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;
-
- GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "sending trailing_metadata"));
- if (grpc_metadata_batch_is_empty(s_->send_trailing_metadata)) {
- grpc_chttp2_encode_data(s_->id, &s_->flow_controlled_buffer, 0, true,
- &s_->stats.outgoing, &t_->outbuf);
- } else {
- grpc_encode_header_options hopt = {
- s_->id, true,
- t_->settings[GRPC_PEER_SETTINGS]
- [GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA] !=
- 0,
-
- t_->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE],
- &s_->stats.outgoing};
- grpc_chttp2_encode_header(&t_->hpack_compressor,
- extra_headers_for_trailing_metadata_,
- num_extra_headers_for_trailing_metadata_,
- s_->send_trailing_metadata, &hopt, &t_->outbuf);
- }
- write_context_->IncTrailingMetadataWrites();
+
+ GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "sending trailing_metadata"));
+ if (grpc_metadata_batch_is_empty(s_->send_trailing_metadata)) {
+ grpc_chttp2_encode_data(s_->id, &s_->flow_controlled_buffer, 0, true,
+ &s_->stats.outgoing, &t_->outbuf);
+ } else {
+ grpc_encode_header_options hopt = {
+ s_->id, true,
+ t_->settings[GRPC_PEER_SETTINGS]
+ [GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA] !=
+ 0,
+
+ t_->settings[GRPC_PEER_SETTINGS][GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE],
+ &s_->stats.outgoing};
+ grpc_chttp2_encode_header(&t_->hpack_compressor,
+ extra_headers_for_trailing_metadata_,
+ num_extra_headers_for_trailing_metadata_,
+ s_->send_trailing_metadata, &hopt, &t_->outbuf);
+ }
+ write_context_->IncTrailingMetadataWrites();
grpc_chttp2_reset_ping_clock(t_);
- SentLastFrame();
-
- write_context_->NoteScheduledResults();
- grpc_chttp2_complete_closure_step(
- t_, s_, &s_->send_trailing_metadata_finished, GRPC_ERROR_NONE,
- "send_trailing_metadata_finished");
- }
-
- bool stream_became_writable() { return stream_became_writable_; }
-
- private:
- void ConvertInitialMetadataToTrailingMetadata() {
- GRPC_CHTTP2_IF_TRACING(
- gpr_log(GPR_INFO, "not sending initial_metadata (Trailers-Only)"));
- // When sending Trailers-Only, we need to move the :status and
- // content-type headers to the trailers.
- if (s_->send_initial_metadata->idx.named.status != nullptr) {
- extra_headers_for_trailing_metadata_
- [num_extra_headers_for_trailing_metadata_++] =
- &s_->send_initial_metadata->idx.named.status->md;
- }
- if (s_->send_initial_metadata->idx.named.content_type != nullptr) {
- extra_headers_for_trailing_metadata_
- [num_extra_headers_for_trailing_metadata_++] =
- &s_->send_initial_metadata->idx.named.content_type->md;
- }
- }
-
- void SentLastFrame() {
- s_->send_trailing_metadata = nullptr;
+ SentLastFrame();
+
+ write_context_->NoteScheduledResults();
+ grpc_chttp2_complete_closure_step(
+ t_, s_, &s_->send_trailing_metadata_finished, GRPC_ERROR_NONE,
+ "send_trailing_metadata_finished");
+ }
+
+ bool stream_became_writable() { return stream_became_writable_; }
+
+ private:
+ void ConvertInitialMetadataToTrailingMetadata() {
+ GRPC_CHTTP2_IF_TRACING(
+ gpr_log(GPR_INFO, "not sending initial_metadata (Trailers-Only)"));
+ // When sending Trailers-Only, we need to move the :status and
+ // content-type headers to the trailers.
+ if (s_->send_initial_metadata->idx.named.status != nullptr) {
+ extra_headers_for_trailing_metadata_
+ [num_extra_headers_for_trailing_metadata_++] =
+ &s_->send_initial_metadata->idx.named.status->md;
+ }
+ if (s_->send_initial_metadata->idx.named.content_type != nullptr) {
+ extra_headers_for_trailing_metadata_
+ [num_extra_headers_for_trailing_metadata_++] =
+ &s_->send_initial_metadata->idx.named.content_type->md;
+ }
+ }
+
+ void SentLastFrame() {
+ s_->send_trailing_metadata = nullptr;
if (s_->sent_trailing_metadata_op) {
*s_->sent_trailing_metadata_op = true;
s_->sent_trailing_metadata_op = nullptr;
}
- s_->sent_trailing_metadata = true;
+ s_->sent_trailing_metadata = true;
s_->eos_sent = true;
-
- if (!t_->is_client && !s_->read_closed) {
- grpc_slice_buffer_add(
- &t_->outbuf, grpc_chttp2_rst_stream_create(
- s_->id, GRPC_HTTP2_NO_ERROR, &s_->stats.outgoing));
- }
- grpc_chttp2_mark_stream_closed(t_, s_, !t_->is_client, true,
- GRPC_ERROR_NONE);
- }
-
- WriteContext* const write_context_;
- grpc_chttp2_transport* const t_;
- grpc_chttp2_stream* const s_;
- bool stream_became_writable_ = false;
- grpc_mdelem* extra_headers_for_trailing_metadata_[2];
- size_t num_extra_headers_for_trailing_metadata_ = 0;
-};
-} // namespace
-
-grpc_chttp2_begin_write_result grpc_chttp2_begin_write(
- grpc_chttp2_transport* t) {
- WriteContext ctx(t);
- ctx.FlushSettings();
- ctx.FlushPingAcks();
- ctx.FlushQueuedBuffers();
- ctx.EnactHpackSettings();
-
- if (t->flow_control->remote_window() > 0) {
- ctx.UpdateStreamsNoLongerStalled();
- }
-
- /* for each grpc_chttp2_stream that's become writable, frame it's data
- (according to available window sizes) and add to the output buffer */
- while (grpc_chttp2_stream* s = ctx.NextStream()) {
- StreamWriteContext stream_ctx(&ctx, s);
+
+ if (!t_->is_client && !s_->read_closed) {
+ grpc_slice_buffer_add(
+ &t_->outbuf, grpc_chttp2_rst_stream_create(
+ s_->id, GRPC_HTTP2_NO_ERROR, &s_->stats.outgoing));
+ }
+ grpc_chttp2_mark_stream_closed(t_, s_, !t_->is_client, true,
+ GRPC_ERROR_NONE);
+ }
+
+ WriteContext* const write_context_;
+ grpc_chttp2_transport* const t_;
+ grpc_chttp2_stream* const s_;
+ bool stream_became_writable_ = false;
+ grpc_mdelem* extra_headers_for_trailing_metadata_[2];
+ size_t num_extra_headers_for_trailing_metadata_ = 0;
+};
+} // namespace
+
+grpc_chttp2_begin_write_result grpc_chttp2_begin_write(
+ grpc_chttp2_transport* t) {
+ WriteContext ctx(t);
+ ctx.FlushSettings();
+ ctx.FlushPingAcks();
+ ctx.FlushQueuedBuffers();
+ ctx.EnactHpackSettings();
+
+ if (t->flow_control->remote_window() > 0) {
+ ctx.UpdateStreamsNoLongerStalled();
+ }
+
+ /* for each grpc_chttp2_stream that's become writable, frame it's data
+ (according to available window sizes) and add to the output buffer */
+ while (grpc_chttp2_stream* s = ctx.NextStream()) {
+ StreamWriteContext stream_ctx(&ctx, s);
size_t orig_len = t->outbuf.length;
- stream_ctx.FlushInitialMetadata();
- stream_ctx.FlushWindowUpdates();
- stream_ctx.FlushData();
- stream_ctx.FlushTrailingMetadata();
+ stream_ctx.FlushInitialMetadata();
+ stream_ctx.FlushWindowUpdates();
+ stream_ctx.FlushData();
+ stream_ctx.FlushTrailingMetadata();
if (t->outbuf.length > orig_len) {
/* Add this stream to the list of the contexts to be traced at TCP */
s->byte_counter += t->outbuf.length - orig_len;
@@ -660,43 +660,43 @@ grpc_chttp2_begin_write_result grpc_chttp2_begin_write(
grpc_core::ContextList::Append(&t->cl, s);
}
}
- if (stream_ctx.stream_became_writable()) {
- if (!grpc_chttp2_list_add_writing_stream(t, s)) {
- /* already in writing list: drop ref */
- GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:already_writing");
- } else {
- /* ref will be dropped at end of write */
- }
- } else {
- GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:no_write");
- }
- }
-
- ctx.FlushWindowUpdates();
-
- maybe_initiate_ping(t);
-
- return ctx.Result();
-}
-
-void grpc_chttp2_end_write(grpc_chttp2_transport* t, grpc_error* error) {
- GPR_TIMER_SCOPE("grpc_chttp2_end_write", 0);
- grpc_chttp2_stream* s;
-
+ if (stream_ctx.stream_became_writable()) {
+ if (!grpc_chttp2_list_add_writing_stream(t, s)) {
+ /* already in writing list: drop ref */
+ GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:already_writing");
+ } else {
+ /* ref will be dropped at end of write */
+ }
+ } else {
+ GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:no_write");
+ }
+ }
+
+ ctx.FlushWindowUpdates();
+
+ maybe_initiate_ping(t);
+
+ return ctx.Result();
+}
+
+void grpc_chttp2_end_write(grpc_chttp2_transport* t, grpc_error* error) {
+ GPR_TIMER_SCOPE("grpc_chttp2_end_write", 0);
+ grpc_chttp2_stream* s;
+
if (t->channelz_socket != nullptr) {
t->channelz_socket->RecordMessagesSent(t->num_messages_in_next_write);
}
t->num_messages_in_next_write = 0;
- while (grpc_chttp2_list_pop_writing_stream(t, &s)) {
- if (s->sending_bytes != 0) {
- update_list(t, s, static_cast<int64_t>(s->sending_bytes),
- &s->on_write_finished_cbs, &s->flow_controlled_bytes_written,
- GRPC_ERROR_REF(error));
- s->sending_bytes = 0;
- }
- GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:end");
- }
- grpc_slice_buffer_reset_and_unref_internal(&t->outbuf);
- GRPC_ERROR_UNREF(error);
-}
+ while (grpc_chttp2_list_pop_writing_stream(t, &s)) {
+ if (s->sending_bytes != 0) {
+ update_list(t, s, static_cast<int64_t>(s->sending_bytes),
+ &s->on_write_finished_cbs, &s->flow_controlled_bytes_written,
+ GRPC_ERROR_REF(error));
+ s->sending_bytes = 0;
+ }
+ GRPC_CHTTP2_STREAM_UNREF(s, "chttp2_writing:end");
+ }
+ grpc_slice_buffer_reset_and_unref_internal(&t->outbuf);
+ GRPC_ERROR_UNREF(error);
+}
diff --git a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_plugin.cc b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_plugin.cc
index 8e251fa2d85..cc58c11f470 100644
--- a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_plugin.cc
+++ b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_plugin.cc
@@ -1,28 +1,28 @@
-/*
- *
- * 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/ext/transport/inproc/inproc_transport.h"
-#include "src/core/lib/debug/trace.h"
-
-grpc_core::TraceFlag grpc_inproc_trace(false, "inproc");
-
-void grpc_inproc_plugin_init(void) { grpc_inproc_transport_init(); }
-
-void grpc_inproc_plugin_shutdown(void) { grpc_inproc_transport_shutdown(); }
+/*
+ *
+ * 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/ext/transport/inproc/inproc_transport.h"
+#include "src/core/lib/debug/trace.h"
+
+grpc_core::TraceFlag grpc_inproc_trace(false, "inproc");
+
+void grpc_inproc_plugin_init(void) { grpc_inproc_transport_init(); }
+
+void grpc_inproc_plugin_shutdown(void) { grpc_inproc_transport_shutdown(); }
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 728831f3648..91e0c28d0f1 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
@@ -1,54 +1,54 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-#include <string.h>
-#include "src/core/ext/transport/inproc/inproc_transport.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/channel.h"
-#include "src/core/lib/surface/channel_stack_type.h"
-#include "src/core/lib/surface/server.h"
-#include "src/core/lib/transport/connectivity_state.h"
-#include "src/core/lib/transport/error_utils.h"
-#include "src/core/lib/transport/transport_impl.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+#include <string.h>
+#include "src/core/ext/transport/inproc/inproc_transport.h"
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/surface/channel_stack_type.h"
+#include "src/core/lib/surface/server.h"
+#include "src/core/lib/transport/connectivity_state.h"
+#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__); \
} \
- } while (0)
-
+ } while (0)
+
namespace {
grpc_slice g_empty_slice;
grpc_slice g_fake_path_key;
grpc_slice g_fake_path_value;
grpc_slice g_fake_auth_key;
grpc_slice g_fake_auth_value;
-
+
struct inproc_stream;
bool cancel_stream_locked(inproc_stream* s, grpc_error* error);
void maybe_process_ops_locked(inproc_stream* s, grpc_error* error);
@@ -69,10 +69,10 @@ struct shared_mu {
~shared_mu() { gpr_mu_destroy(&mu); }
- gpr_mu mu;
- gpr_refcount refs;
+ gpr_mu mu;
+ gpr_refcount refs;
};
-
+
struct inproc_transport {
inproc_transport(const grpc_transport_vtable* vtable, shared_mu* mu,
bool is_client)
@@ -108,19 +108,19 @@ struct inproc_transport {
gpr_free(this);
}
- grpc_transport base;
- shared_mu* mu;
- gpr_refcount refs;
- bool is_client;
+ grpc_transport base;
+ shared_mu* mu;
+ gpr_refcount refs;
+ bool is_client;
grpc_core::ConnectivityStateTracker state_tracker;
- void (*accept_stream_cb)(void* user_data, grpc_transport* transport,
- const void* server_data);
- void* accept_stream_data;
+ void (*accept_stream_cb)(void* user_data, grpc_transport* transport,
+ const void* server_data);
+ void* accept_stream_data;
bool is_closed = false;
- struct inproc_transport* other_side;
+ struct inproc_transport* other_side;
struct inproc_stream* stream_list = nullptr;
};
-
+
struct inproc_stream {
inproc_stream(inproc_transport* t, grpc_stream_refcount* refcount,
const void* server_data, grpc_core::Arena* arena)
@@ -128,12 +128,12 @@ struct inproc_stream {
// Ref this stream right now for ctor and list.
ref("inproc_init_stream:init");
ref("inproc_init_stream:list");
-
+
grpc_metadata_batch_init(&to_read_initial_md);
grpc_metadata_batch_init(&to_read_trailing_md);
grpc_metadata_batch_init(&write_buffer_initial_md);
grpc_metadata_batch_init(&write_buffer_trailing_md);
-
+
stream_list_prev = nullptr;
gpr_mu_lock(&t->mu->mu);
stream_list_next = t->stream_list;
@@ -142,7 +142,7 @@ struct inproc_stream {
}
t->stream_list = this;
gpr_mu_unlock(&t->mu->mu);
-
+
if (!server_data) {
t->ref();
inproc_transport* st = t->other_side;
@@ -160,7 +160,7 @@ struct inproc_stream {
other_side = cs;
// Ref the server-side stream on behalf of the client now
ref("inproc_init_stream:srv");
-
+
// Now we are about to affect the other side, so lock the transport
// to make sure that it doesn't get destroyed
gpr_mu_lock(&t->mu->mu);
@@ -187,42 +187,42 @@ struct inproc_stream {
cs->write_buffer_cancel_error = GRPC_ERROR_NONE;
maybe_process_ops_locked(this, cancel_other_error);
}
-
+
gpr_mu_unlock(&t->mu->mu);
}
}
-
+
~inproc_stream() {
GRPC_ERROR_UNREF(write_buffer_cancel_error);
GRPC_ERROR_UNREF(cancel_self_error);
GRPC_ERROR_UNREF(cancel_other_error);
-
+
if (recv_inited) {
grpc_slice_buffer_destroy_internal(&recv_message);
}
-
+
t->unref();
- }
-
-#ifndef NDEBUG
-#define STREAM_REF(refs, reason) grpc_stream_ref(refs, reason)
-#define STREAM_UNREF(refs, reason) grpc_stream_unref(refs, reason)
-#else
-#define STREAM_REF(refs, reason) grpc_stream_ref(refs)
-#define STREAM_UNREF(refs, reason) grpc_stream_unref(refs)
-#endif
+ }
+
+#ifndef NDEBUG
+#define STREAM_REF(refs, reason) grpc_stream_ref(refs, reason)
+#define STREAM_UNREF(refs, reason) grpc_stream_unref(refs, reason)
+#else
+#define STREAM_REF(refs, reason) grpc_stream_ref(refs)
+#define STREAM_UNREF(refs, reason) grpc_stream_unref(refs)
+#endif
void ref(const char* reason) {
INPROC_LOG(GPR_INFO, "ref_stream %p %s", this, reason);
STREAM_REF(refs, reason);
}
-
+
void unref(const char* reason) {
INPROC_LOG(GPR_INFO, "unref_stream %p %s", this, reason);
STREAM_UNREF(refs, reason);
}
#undef STREAM_REF
#undef STREAM_UNREF
-
+
inproc_transport* t;
grpc_metadata_batch to_read_initial_md;
uint32_t to_read_initial_md_flags = 0;
@@ -239,24 +239,24 @@ struct inproc_stream {
grpc_metadata_batch write_buffer_trailing_md;
bool write_buffer_trailing_md_filled = false;
grpc_error* write_buffer_cancel_error = GRPC_ERROR_NONE;
-
+
struct inproc_stream* other_side;
bool other_side_closed = false; // won't talk anymore
bool write_buffer_other_side_closed = false; // on hold
grpc_stream_refcount* refs;
-
+
grpc_core::Arena* arena;
-
+
grpc_transport_stream_op_batch* send_message_op = nullptr;
grpc_transport_stream_op_batch* send_trailing_md_op = nullptr;
grpc_transport_stream_op_batch* recv_initial_md_op = nullptr;
grpc_transport_stream_op_batch* recv_message_op = nullptr;
grpc_transport_stream_op_batch* recv_trailing_md_op = nullptr;
-
+
grpc_slice_buffer recv_message;
grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> recv_stream;
bool recv_inited = false;
-
+
bool initial_md_sent = false;
bool trailing_md_sent = false;
bool initial_md_recvd = false;
@@ -266,7 +266,7 @@ struct inproc_stream {
// case, it is still ok for the client to send trailing metadata (in which
// case it will be ignored).
bool trailing_md_recvd_implicit_only = false;
-
+
bool closed = false;
grpc_error* cancel_self_error = GRPC_ERROR_NONE;
@@ -281,232 +281,232 @@ struct inproc_stream {
void log_metadata(const grpc_metadata_batch* md_batch, bool is_client,
bool is_initial) {
- for (grpc_linked_mdelem* md = md_batch->list.head; md != nullptr;
- md = md->next) {
- char* key = grpc_slice_to_c_string(GRPC_MDKEY(md->md));
- char* value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md));
- gpr_log(GPR_INFO, "INPROC:%s:%s: %s: %s", is_initial ? "HDR" : "TRL",
- is_client ? "CLI" : "SVR", key, value);
- gpr_free(key);
- gpr_free(value);
- }
-}
-
+ for (grpc_linked_mdelem* md = md_batch->list.head; md != nullptr;
+ md = md->next) {
+ char* key = grpc_slice_to_c_string(GRPC_MDKEY(md->md));
+ char* value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md));
+ gpr_log(GPR_INFO, "INPROC:%s:%s: %s: %s", is_initial ? "HDR" : "TRL",
+ is_client ? "CLI" : "SVR", key, value);
+ gpr_free(key);
+ gpr_free(value);
+ }
+}
+
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)) {
- log_metadata(metadata, s->t->is_client, outflags != nullptr);
- }
-
- if (outflags != nullptr) {
- *outflags = flags;
- }
- if (markfilled != nullptr) {
- *markfilled = true;
- }
- grpc_error* error = GRPC_ERROR_NONE;
- for (grpc_linked_mdelem* elem = metadata->list.head;
- (elem != nullptr) && (error == GRPC_ERROR_NONE); elem = elem->next) {
+ log_metadata(metadata, s->t->is_client, outflags != nullptr);
+ }
+
+ if (outflags != nullptr) {
+ *outflags = flags;
+ }
+ if (markfilled != nullptr) {
+ *markfilled = true;
+ }
+ 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)));
- nelem->md =
- grpc_mdelem_from_slices(grpc_slice_intern(GRPC_MDKEY(elem->md)),
- grpc_slice_intern(GRPC_MDVALUE(elem->md)));
-
- error = grpc_metadata_batch_link_tail(out_md, nelem);
- }
- return error;
-}
-
+ nelem->md =
+ grpc_mdelem_from_slices(grpc_slice_intern(GRPC_MDKEY(elem->md)),
+ grpc_slice_intern(GRPC_MDVALUE(elem->md)));
+
+ error = grpc_metadata_batch_link_tail(out_md, nelem);
+ }
+ return error;
+}
+
int init_stream(grpc_transport* gt, grpc_stream* gs,
grpc_stream_refcount* refcount, const void* server_data,
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);
+ 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);
- return 0; // return value is not important
-}
-
+ return 0; // return value is not important
+}
+
void close_stream_locked(inproc_stream* s) {
- if (!s->closed) {
- // Release the metadata that we would have written out
- grpc_metadata_batch_destroy(&s->write_buffer_initial_md);
- grpc_metadata_batch_destroy(&s->write_buffer_trailing_md);
-
- if (s->listed) {
- inproc_stream* p = s->stream_list_prev;
- inproc_stream* n = s->stream_list_next;
- if (p != nullptr) {
- p->stream_list_next = n;
- } else {
- s->t->stream_list = n;
- }
- if (n != nullptr) {
- n->stream_list_prev = p;
- }
- s->listed = false;
+ if (!s->closed) {
+ // Release the metadata that we would have written out
+ grpc_metadata_batch_destroy(&s->write_buffer_initial_md);
+ grpc_metadata_batch_destroy(&s->write_buffer_trailing_md);
+
+ if (s->listed) {
+ inproc_stream* p = s->stream_list_prev;
+ inproc_stream* n = s->stream_list_next;
+ if (p != nullptr) {
+ p->stream_list_next = n;
+ } else {
+ s->t->stream_list = n;
+ }
+ if (n != nullptr) {
+ n->stream_list_prev = p;
+ }
+ s->listed = false;
s->unref("close_stream:list");
- }
- s->closed = true;
+ }
+ s->closed = true;
s->unref("close_stream:closing");
- }
-}
-
-// This function means that we are done talking/listening to the other side
+ }
+}
+
+// This function means that we are done talking/listening to the other side
void close_other_side_locked(inproc_stream* s, const char* reason) {
- if (s->other_side != nullptr) {
- // First release the metadata that came from the other side's arena
- grpc_metadata_batch_destroy(&s->to_read_initial_md);
- grpc_metadata_batch_destroy(&s->to_read_trailing_md);
-
+ if (s->other_side != nullptr) {
+ // First release the metadata that came from the other side's arena
+ grpc_metadata_batch_destroy(&s->to_read_initial_md);
+ grpc_metadata_batch_destroy(&s->to_read_trailing_md);
+
s->other_side->unref(reason);
- s->other_side_closed = true;
- s->other_side = nullptr;
- } else if (!s->other_side_closed) {
- s->write_buffer_other_side_closed = true;
- }
-}
-
-// Call the on_complete closure associated with this stream_op_batch if
-// this stream_op_batch is only one of the pending operations for this
-// stream. This is called when one of the pending operations for the stream
-// is done and about to be NULLed out
+ s->other_side_closed = true;
+ s->other_side = nullptr;
+ } else if (!s->other_side_closed) {
+ s->write_buffer_other_side_closed = true;
+ }
+}
+
+// Call the on_complete closure associated with this stream_op_batch if
+// this stream_op_batch is only one of the pending operations for this
+// stream. This is called when one of the pending operations for the stream
+// is done and about to be NULLed out
void complete_if_batch_end_locked(inproc_stream* s, grpc_error* error,
grpc_transport_stream_op_batch* op,
const char* msg) {
- int is_sm = static_cast<int>(op == s->send_message_op);
- int is_stm = static_cast<int>(op == s->send_trailing_md_op);
+ int is_sm = static_cast<int>(op == s->send_message_op);
+ int is_stm = static_cast<int>(op == s->send_trailing_md_op);
// TODO(vjpai): We should not consider the recv ops here, since they
// have their own callbacks. We should invoke a batch's on_complete
// as soon as all of the batch's send ops are complete, even if there
// are still recv ops pending.
- int is_rim = static_cast<int>(op == s->recv_initial_md_op);
- int is_rm = static_cast<int>(op == s->recv_message_op);
- int is_rtm = static_cast<int>(op == s->recv_trailing_md_op);
-
- if ((is_sm + is_stm + is_rim + is_rm + is_rtm) == 1) {
- INPROC_LOG(GPR_INFO, "%s %p %p %p", msg, s, op, error);
+ int is_rim = static_cast<int>(op == s->recv_initial_md_op);
+ int is_rm = static_cast<int>(op == s->recv_message_op);
+ int is_rtm = static_cast<int>(op == s->recv_trailing_md_op);
+
+ 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));
- }
-}
-
+ }
+}
+
void maybe_process_ops_locked(inproc_stream* s, grpc_error* error) {
if (s && (error != GRPC_ERROR_NONE || s->ops_needed)) {
- s->ops_needed = false;
+ s->ops_needed = false;
op_state_machine_locked(s, error);
- }
-}
-
+ }
+}
+
void fail_helper_locked(inproc_stream* s, grpc_error* error) {
- INPROC_LOG(GPR_INFO, "op_state_machine %p fail_helper", s);
- // If we're failing this side, we need to make sure that
- // we also send or have already sent trailing metadata
- if (!s->trailing_md_sent) {
- // Send trailing md to the other side indicating cancellation
- s->trailing_md_sent = true;
-
- grpc_metadata_batch fake_md;
- grpc_metadata_batch_init(&fake_md);
-
- inproc_stream* other = s->other_side;
- grpc_metadata_batch* dest = (other == nullptr)
- ? &s->write_buffer_trailing_md
- : &other->to_read_trailing_md;
- bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled
- : &other->to_read_trailing_md_filled;
- fill_in_metadata(s, &fake_md, 0, dest, nullptr, destfilled);
- grpc_metadata_batch_destroy(&fake_md);
-
- if (other != nullptr) {
- if (other->cancel_other_error == GRPC_ERROR_NONE) {
- other->cancel_other_error = GRPC_ERROR_REF(error);
- }
+ INPROC_LOG(GPR_INFO, "op_state_machine %p fail_helper", s);
+ // If we're failing this side, we need to make sure that
+ // we also send or have already sent trailing metadata
+ if (!s->trailing_md_sent) {
+ // Send trailing md to the other side indicating cancellation
+ s->trailing_md_sent = true;
+
+ grpc_metadata_batch fake_md;
+ grpc_metadata_batch_init(&fake_md);
+
+ inproc_stream* other = s->other_side;
+ grpc_metadata_batch* dest = (other == nullptr)
+ ? &s->write_buffer_trailing_md
+ : &other->to_read_trailing_md;
+ bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled
+ : &other->to_read_trailing_md_filled;
+ fill_in_metadata(s, &fake_md, 0, dest, nullptr, destfilled);
+ grpc_metadata_batch_destroy(&fake_md);
+
+ if (other != nullptr) {
+ if (other->cancel_other_error == GRPC_ERROR_NONE) {
+ other->cancel_other_error = GRPC_ERROR_REF(error);
+ }
maybe_process_ops_locked(other, error);
- } else if (s->write_buffer_cancel_error == GRPC_ERROR_NONE) {
- s->write_buffer_cancel_error = GRPC_ERROR_REF(error);
- }
- }
- if (s->recv_initial_md_op) {
- grpc_error* err;
- if (!s->t->is_client) {
- // If this is a server, provide initial metadata with a path and authority
- // since it expects that as well as no error yet
- grpc_metadata_batch fake_md;
- grpc_metadata_batch_init(&fake_md);
+ } else if (s->write_buffer_cancel_error == GRPC_ERROR_NONE) {
+ s->write_buffer_cancel_error = GRPC_ERROR_REF(error);
+ }
+ }
+ if (s->recv_initial_md_op) {
+ grpc_error* err;
+ if (!s->t->is_client) {
+ // If this is a server, provide initial metadata with a path and authority
+ // 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)));
- 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);
+ 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)));
- 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);
-
- fill_in_metadata(
- s, &fake_md, 0,
- s->recv_initial_md_op->payload->recv_initial_metadata
- .recv_initial_metadata,
- s->recv_initial_md_op->payload->recv_initial_metadata.recv_flags,
- nullptr);
- grpc_metadata_batch_destroy(&fake_md);
- err = GRPC_ERROR_NONE;
- } else {
- err = GRPC_ERROR_REF(error);
- }
- if (s->recv_initial_md_op->payload->recv_initial_metadata
- .trailing_metadata_available != nullptr) {
- // Set to true unconditionally, because we're failing the call, so even
- // if we haven't actually seen the send_trailing_metadata op from the
- // other side, we're going to return trailing metadata anyway.
- *s->recv_initial_md_op->payload->recv_initial_metadata
- .trailing_metadata_available = true;
- }
- INPROC_LOG(GPR_INFO,
- "fail_helper %p scheduling initial-metadata-ready %p %p", s,
- error, err);
+ 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);
+
+ fill_in_metadata(
+ s, &fake_md, 0,
+ s->recv_initial_md_op->payload->recv_initial_metadata
+ .recv_initial_metadata,
+ s->recv_initial_md_op->payload->recv_initial_metadata.recv_flags,
+ nullptr);
+ grpc_metadata_batch_destroy(&fake_md);
+ err = GRPC_ERROR_NONE;
+ } else {
+ err = GRPC_ERROR_REF(error);
+ }
+ if (s->recv_initial_md_op->payload->recv_initial_metadata
+ .trailing_metadata_available != nullptr) {
+ // Set to true unconditionally, because we're failing the call, so even
+ // if we haven't actually seen the send_trailing_metadata op from the
+ // other side, we're going to return trailing metadata anyway.
+ *s->recv_initial_md_op->payload->recv_initial_metadata
+ .trailing_metadata_available = true;
+ }
+ 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);
- // Last use of err so no need to REF and then UNREF it
-
- complete_if_batch_end_locked(
- s, error, s->recv_initial_md_op,
- "fail_helper scheduling recv-initial-metadata-on-complete");
- s->recv_initial_md_op = nullptr;
- }
- if (s->recv_message_op) {
- INPROC_LOG(GPR_INFO, "fail_helper %p scheduling message-ready %p", s,
- error);
+ // Last use of err so no need to REF and then UNREF it
+
+ complete_if_batch_end_locked(
+ s, error, s->recv_initial_md_op,
+ "fail_helper scheduling recv-initial-metadata-on-complete");
+ s->recv_initial_md_op = nullptr;
+ }
+ if (s->recv_message_op) {
+ INPROC_LOG(GPR_INFO, "fail_helper %p scheduling message-ready %p", s,
+ error);
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(
- s, error, s->recv_message_op,
- "fail_helper scheduling recv-message-on-complete");
- s->recv_message_op = nullptr;
- }
- if (s->send_message_op) {
- s->send_message_op->payload->send_message.send_message.reset();
- complete_if_batch_end_locked(
- s, error, s->send_message_op,
- "fail_helper scheduling send-message-on-complete");
- s->send_message_op = nullptr;
- }
- if (s->send_trailing_md_op) {
- complete_if_batch_end_locked(
- s, error, s->send_trailing_md_op,
- "fail_helper scheduling send-trailng-md-on-complete");
- s->send_trailing_md_op = nullptr;
- }
- if (s->recv_trailing_md_op) {
+ s->recv_message_op->payload->recv_message.recv_message_ready,
+ GRPC_ERROR_REF(error));
+ complete_if_batch_end_locked(
+ s, error, s->recv_message_op,
+ "fail_helper scheduling recv-message-on-complete");
+ s->recv_message_op = nullptr;
+ }
+ if (s->send_message_op) {
+ s->send_message_op->payload->send_message.send_message.reset();
+ complete_if_batch_end_locked(
+ s, error, s->send_message_op,
+ "fail_helper scheduling send-message-on-complete");
+ s->send_message_op = nullptr;
+ }
+ if (s->send_trailing_md_op) {
+ complete_if_batch_end_locked(
+ s, error, s->send_trailing_md_op,
+ "fail_helper scheduling send-trailng-md-on-complete");
+ s->send_trailing_md_op = nullptr;
+ }
+ if (s->recv_trailing_md_op) {
INPROC_LOG(GPR_INFO, "fail_helper %p scheduling trailing-metadata-ready %p",
s, error);
grpc_core::ExecCtx::Run(
@@ -514,148 +514,148 @@ void fail_helper_locked(inproc_stream* s, grpc_error* error) {
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(
- s, error, s->recv_trailing_md_op,
- "fail_helper scheduling recv-trailing-metadata-on-complete");
- s->recv_trailing_md_op = nullptr;
- }
- close_other_side_locked(s, "fail_helper:other_side");
- close_stream_locked(s);
-
- GRPC_ERROR_UNREF(error);
-}
-
-// TODO(vjpai): It should not be necessary to drain the incoming byte
-// stream and create a new one; instead, we should simply pass the byte
-// stream from the sender directly to the receiver as-is.
-//
-// Note that fixing this will also avoid the assumption in this code
-// that the incoming byte stream's next() call will always return
-// synchronously. That assumption is true today but may not always be
-// true in the future.
+ INPROC_LOG(GPR_INFO, "fail_helper %p scheduling trailing-md-on-complete %p",
+ s, error);
+ complete_if_batch_end_locked(
+ s, error, s->recv_trailing_md_op,
+ "fail_helper scheduling recv-trailing-metadata-on-complete");
+ s->recv_trailing_md_op = nullptr;
+ }
+ close_other_side_locked(s, "fail_helper:other_side");
+ close_stream_locked(s);
+
+ GRPC_ERROR_UNREF(error);
+}
+
+// TODO(vjpai): It should not be necessary to drain the incoming byte
+// stream and create a new one; instead, we should simply pass the byte
+// stream from the sender directly to the receiver as-is.
+//
+// Note that fixing this will also avoid the assumption in this code
+// that the incoming byte stream's next() call will always return
+// synchronously. That assumption is true today but may not always be
+// true in the future.
void message_transfer_locked(inproc_stream* sender, inproc_stream* receiver) {
- size_t remaining =
- sender->send_message_op->payload->send_message.send_message->length();
- if (receiver->recv_inited) {
- grpc_slice_buffer_destroy_internal(&receiver->recv_message);
- }
- grpc_slice_buffer_init(&receiver->recv_message);
- receiver->recv_inited = true;
- do {
- grpc_slice message_slice;
- grpc_closure unused;
- GPR_ASSERT(
- sender->send_message_op->payload->send_message.send_message->Next(
- SIZE_MAX, &unused));
- grpc_error* error =
- sender->send_message_op->payload->send_message.send_message->Pull(
- &message_slice);
- if (error != GRPC_ERROR_NONE) {
- cancel_stream_locked(sender, GRPC_ERROR_REF(error));
- break;
- }
- GPR_ASSERT(error == GRPC_ERROR_NONE);
- remaining -= GRPC_SLICE_LENGTH(message_slice);
- grpc_slice_buffer_add(&receiver->recv_message, message_slice);
- } while (remaining > 0);
- sender->send_message_op->payload->send_message.send_message.reset();
-
- receiver->recv_stream.Init(&receiver->recv_message, 0);
- receiver->recv_message_op->payload->recv_message.recv_message->reset(
- receiver->recv_stream.get());
- INPROC_LOG(GPR_INFO, "message_transfer_locked %p scheduling message-ready",
- receiver);
+ size_t remaining =
+ sender->send_message_op->payload->send_message.send_message->length();
+ if (receiver->recv_inited) {
+ grpc_slice_buffer_destroy_internal(&receiver->recv_message);
+ }
+ grpc_slice_buffer_init(&receiver->recv_message);
+ receiver->recv_inited = true;
+ do {
+ grpc_slice message_slice;
+ grpc_closure unused;
+ GPR_ASSERT(
+ sender->send_message_op->payload->send_message.send_message->Next(
+ SIZE_MAX, &unused));
+ grpc_error* error =
+ sender->send_message_op->payload->send_message.send_message->Pull(
+ &message_slice);
+ if (error != GRPC_ERROR_NONE) {
+ cancel_stream_locked(sender, GRPC_ERROR_REF(error));
+ break;
+ }
+ GPR_ASSERT(error == GRPC_ERROR_NONE);
+ remaining -= GRPC_SLICE_LENGTH(message_slice);
+ grpc_slice_buffer_add(&receiver->recv_message, message_slice);
+ } while (remaining > 0);
+ sender->send_message_op->payload->send_message.send_message.reset();
+
+ receiver->recv_stream.Init(&receiver->recv_message, 0);
+ receiver->recv_message_op->payload->recv_message.recv_message->reset(
+ receiver->recv_stream.get());
+ INPROC_LOG(GPR_INFO, "message_transfer_locked %p scheduling message-ready",
+ receiver);
grpc_core::ExecCtx::Run(
DEBUG_LOCATION,
- receiver->recv_message_op->payload->recv_message.recv_message_ready,
- GRPC_ERROR_NONE);
- complete_if_batch_end_locked(
- sender, GRPC_ERROR_NONE, sender->send_message_op,
- "message_transfer scheduling sender on_complete");
- complete_if_batch_end_locked(
- receiver, GRPC_ERROR_NONE, receiver->recv_message_op,
- "message_transfer scheduling receiver on_complete");
-
- receiver->recv_message_op = nullptr;
- sender->send_message_op = nullptr;
-}
-
+ receiver->recv_message_op->payload->recv_message.recv_message_ready,
+ GRPC_ERROR_NONE);
+ complete_if_batch_end_locked(
+ sender, GRPC_ERROR_NONE, sender->send_message_op,
+ "message_transfer scheduling sender on_complete");
+ complete_if_batch_end_locked(
+ receiver, GRPC_ERROR_NONE, receiver->recv_message_op,
+ "message_transfer scheduling receiver on_complete");
+
+ receiver->recv_message_op = nullptr;
+ sender->send_message_op = nullptr;
+}
+
void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
- // This function gets called when we have contents in the unprocessed reads
- // Get what we want based on our ops wanted
- // Schedule our appropriate closures
- // and then return to ops_needed state if still needed
-
- grpc_error* new_err = GRPC_ERROR_NONE;
-
- bool needs_close = false;
-
+ // This function gets called when we have contents in the unprocessed reads
+ // Get what we want based on our ops wanted
+ // Schedule our appropriate closures
+ // and then return to ops_needed state if still needed
+
+ grpc_error* new_err = GRPC_ERROR_NONE;
+
+ bool needs_close = false;
+
INPROC_LOG(GPR_INFO, "op_state_machine %p", s);
- // cancellation takes precedence
- inproc_stream* other = s->other_side;
-
- if (s->cancel_self_error != GRPC_ERROR_NONE) {
- fail_helper_locked(s, GRPC_ERROR_REF(s->cancel_self_error));
- goto done;
- } else if (s->cancel_other_error != GRPC_ERROR_NONE) {
- fail_helper_locked(s, GRPC_ERROR_REF(s->cancel_other_error));
- goto done;
- } else if (error != GRPC_ERROR_NONE) {
- fail_helper_locked(s, GRPC_ERROR_REF(error));
- goto done;
- }
-
- if (s->send_message_op && other) {
- if (other->recv_message_op) {
- message_transfer_locked(s, other);
+ // cancellation takes precedence
+ inproc_stream* other = s->other_side;
+
+ if (s->cancel_self_error != GRPC_ERROR_NONE) {
+ fail_helper_locked(s, GRPC_ERROR_REF(s->cancel_self_error));
+ goto done;
+ } else if (s->cancel_other_error != GRPC_ERROR_NONE) {
+ fail_helper_locked(s, GRPC_ERROR_REF(s->cancel_other_error));
+ goto done;
+ } else if (error != GRPC_ERROR_NONE) {
+ fail_helper_locked(s, GRPC_ERROR_REF(error));
+ goto done;
+ }
+
+ if (s->send_message_op && other) {
+ if (other->recv_message_op) {
+ message_transfer_locked(s, other);
maybe_process_ops_locked(other, GRPC_ERROR_NONE);
} else if (!s->t->is_client && s->trailing_md_sent) {
// A server send will never be matched if the server already sent status
- s->send_message_op->payload->send_message.send_message.reset();
- complete_if_batch_end_locked(
- s, GRPC_ERROR_NONE, s->send_message_op,
+ s->send_message_op->payload->send_message.send_message.reset();
+ complete_if_batch_end_locked(
+ s, GRPC_ERROR_NONE, s->send_message_op,
"op_state_machine scheduling send-message-on-complete case 1");
- s->send_message_op = nullptr;
- }
- }
- // Pause a send trailing metadata if there is still an outstanding
- // send message unless we know that the send message will never get
- // matched to a receive. This happens on the client if the server has
+ s->send_message_op = nullptr;
+ }
+ }
+ // Pause a send trailing metadata if there is still an outstanding
+ // send message unless we know that the send message will never get
+ // matched to a receive. This happens on the client if the server has
// already sent status or on the server if the client has requested
// status
- if (s->send_trailing_md_op &&
- (!s->send_message_op ||
- (s->t->is_client &&
+ if (s->send_trailing_md_op &&
+ (!s->send_message_op ||
+ (s->t->is_client &&
(s->trailing_md_recvd || s->to_read_trailing_md_filled)) ||
(!s->t->is_client && other &&
(other->trailing_md_recvd || other->to_read_trailing_md_filled ||
other->recv_trailing_md_op)))) {
- grpc_metadata_batch* dest = (other == nullptr)
- ? &s->write_buffer_trailing_md
- : &other->to_read_trailing_md;
- bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled
- : &other->to_read_trailing_md_filled;
- if (*destfilled || s->trailing_md_sent) {
- // The buffer is already in use; that's an error!
- INPROC_LOG(GPR_INFO, "Extra trailing metadata %p", s);
- new_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Extra trailing metadata");
- fail_helper_locked(s, GRPC_ERROR_REF(new_err));
- goto done;
- } else {
- if (!other || !other->closed) {
- fill_in_metadata(s,
- s->send_trailing_md_op->payload->send_trailing_metadata
- .send_trailing_metadata,
- 0, dest, nullptr, destfilled);
- }
- s->trailing_md_sent = true;
+ grpc_metadata_batch* dest = (other == nullptr)
+ ? &s->write_buffer_trailing_md
+ : &other->to_read_trailing_md;
+ bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled
+ : &other->to_read_trailing_md_filled;
+ if (*destfilled || s->trailing_md_sent) {
+ // The buffer is already in use; that's an error!
+ INPROC_LOG(GPR_INFO, "Extra trailing metadata %p", s);
+ new_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Extra trailing metadata");
+ fail_helper_locked(s, GRPC_ERROR_REF(new_err));
+ goto done;
+ } else {
+ if (!other || !other->closed) {
+ fill_in_metadata(s,
+ s->send_trailing_md_op->payload->send_trailing_metadata
+ .send_trailing_metadata,
+ 0, dest, nullptr, destfilled);
+ }
+ s->trailing_md_sent = true;
if (s->send_trailing_md_op->payload->send_trailing_metadata.sent) {
*s->send_trailing_md_op->payload->send_trailing_metadata.sent = true;
}
- if (!s->t->is_client && s->trailing_md_recvd && s->recv_trailing_md_op) {
- INPROC_LOG(GPR_INFO,
+ 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,
@@ -663,81 +663,81 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
.recv_trailing_metadata_ready,
GRPC_ERROR_NONE);
INPROC_LOG(GPR_INFO,
- "op_state_machine %p scheduling trailing-md-on-complete", s);
+ "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);
- s->recv_trailing_md_op = nullptr;
- needs_close = true;
- }
- }
+ s->recv_trailing_md_op = nullptr;
+ needs_close = true;
+ }
+ }
maybe_process_ops_locked(other, GRPC_ERROR_NONE);
- complete_if_batch_end_locked(
- s, GRPC_ERROR_NONE, s->send_trailing_md_op,
- "op_state_machine scheduling send-trailing-metadata-on-complete");
- s->send_trailing_md_op = nullptr;
- }
- if (s->recv_initial_md_op) {
- if (s->initial_md_recvd) {
- new_err =
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Already recvd initial md");
- INPROC_LOG(
- GPR_INFO,
- "op_state_machine %p scheduling on_complete errors for already "
- "recvd initial md %p",
- s, new_err);
- fail_helper_locked(s, GRPC_ERROR_REF(new_err));
- goto done;
- }
-
- if (s->to_read_initial_md_filled) {
- s->initial_md_recvd = true;
- new_err = fill_in_metadata(
- s, &s->to_read_initial_md, s->to_read_initial_md_flags,
- s->recv_initial_md_op->payload->recv_initial_metadata
- .recv_initial_metadata,
- s->recv_initial_md_op->payload->recv_initial_metadata.recv_flags,
- nullptr);
- s->recv_initial_md_op->payload->recv_initial_metadata
- .recv_initial_metadata->deadline = s->deadline;
- if (s->recv_initial_md_op->payload->recv_initial_metadata
- .trailing_metadata_available != nullptr) {
- *s->recv_initial_md_op->payload->recv_initial_metadata
- .trailing_metadata_available =
- (other != nullptr && other->send_trailing_md_op != nullptr);
- }
- grpc_metadata_batch_clear(&s->to_read_initial_md);
- s->to_read_initial_md_filled = false;
- INPROC_LOG(GPR_INFO,
- "op_state_machine %p scheduling initial-metadata-ready %p", s,
- new_err);
+ complete_if_batch_end_locked(
+ s, GRPC_ERROR_NONE, s->send_trailing_md_op,
+ "op_state_machine scheduling send-trailing-metadata-on-complete");
+ s->send_trailing_md_op = nullptr;
+ }
+ if (s->recv_initial_md_op) {
+ if (s->initial_md_recvd) {
+ new_err =
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Already recvd initial md");
+ INPROC_LOG(
+ GPR_INFO,
+ "op_state_machine %p scheduling on_complete errors for already "
+ "recvd initial md %p",
+ s, new_err);
+ fail_helper_locked(s, GRPC_ERROR_REF(new_err));
+ goto done;
+ }
+
+ if (s->to_read_initial_md_filled) {
+ s->initial_md_recvd = true;
+ new_err = fill_in_metadata(
+ s, &s->to_read_initial_md, s->to_read_initial_md_flags,
+ s->recv_initial_md_op->payload->recv_initial_metadata
+ .recv_initial_metadata,
+ s->recv_initial_md_op->payload->recv_initial_metadata.recv_flags,
+ nullptr);
+ s->recv_initial_md_op->payload->recv_initial_metadata
+ .recv_initial_metadata->deadline = s->deadline;
+ if (s->recv_initial_md_op->payload->recv_initial_metadata
+ .trailing_metadata_available != nullptr) {
+ *s->recv_initial_md_op->payload->recv_initial_metadata
+ .trailing_metadata_available =
+ (other != nullptr && other->send_trailing_md_op != nullptr);
+ }
+ grpc_metadata_batch_clear(&s->to_read_initial_md);
+ s->to_read_initial_md_filled = false;
+ 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));
- complete_if_batch_end_locked(
- s, new_err, s->recv_initial_md_op,
- "op_state_machine scheduling recv-initial-metadata-on-complete");
- s->recv_initial_md_op = nullptr;
-
- if (new_err != GRPC_ERROR_NONE) {
- INPROC_LOG(GPR_INFO,
- "op_state_machine %p scheduling on_complete errors2 %p", s,
- new_err);
- fail_helper_locked(s, GRPC_ERROR_REF(new_err));
- goto done;
- }
- }
- }
- if (s->recv_message_op) {
- if (other && other->send_message_op) {
- message_transfer_locked(other, s);
+ complete_if_batch_end_locked(
+ s, new_err, s->recv_initial_md_op,
+ "op_state_machine scheduling recv-initial-metadata-on-complete");
+ s->recv_initial_md_op = nullptr;
+
+ if (new_err != GRPC_ERROR_NONE) {
+ INPROC_LOG(GPR_INFO,
+ "op_state_machine %p scheduling on_complete errors2 %p", s,
+ new_err);
+ fail_helper_locked(s, GRPC_ERROR_REF(new_err));
+ goto done;
+ }
+ }
+ }
+ if (s->recv_message_op) {
+ if (other && other->send_message_op) {
+ message_transfer_locked(other, s);
maybe_process_ops_locked(other, GRPC_ERROR_NONE);
- }
- }
- if (s->to_read_trailing_md_filled) {
- if (s->trailing_md_recvd) {
+ }
+ }
+ if (s->to_read_trailing_md_filled) {
+ if (s->trailing_md_recvd) {
if (s->trailing_md_recvd_implicit_only) {
INPROC_LOG(GPR_INFO,
"op_state_machine %p already implicitly received trailing "
@@ -757,51 +757,51 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
fail_helper_locked(s, GRPC_ERROR_REF(new_err));
goto done;
}
- }
- if (s->recv_message_op != nullptr) {
- // This message needs to be wrapped up because it will never be
- // satisfied
+ }
+ if (s->recv_message_op != nullptr) {
+ // This message needs to be wrapped up because it will never be
+ // satisfied
*s->recv_message_op->payload->recv_message.recv_message = nullptr;
- INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling message-ready", s);
+ INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling message-ready", s);
grpc_core::ExecCtx::Run(
DEBUG_LOCATION,
- s->recv_message_op->payload->recv_message.recv_message_ready,
- GRPC_ERROR_NONE);
- complete_if_batch_end_locked(
- s, new_err, s->recv_message_op,
- "op_state_machine scheduling recv-message-on-complete");
- s->recv_message_op = nullptr;
- }
- if ((s->trailing_md_sent || s->t->is_client) && s->send_message_op) {
- // Nothing further will try to receive from this stream, so finish off
- // any outstanding send_message op
- s->send_message_op->payload->send_message.send_message.reset();
+ s->recv_message_op->payload->recv_message.recv_message_ready,
+ GRPC_ERROR_NONE);
+ complete_if_batch_end_locked(
+ s, new_err, s->recv_message_op,
+ "op_state_machine scheduling recv-message-on-complete");
+ s->recv_message_op = nullptr;
+ }
+ if ((s->trailing_md_sent || s->t->is_client) && s->send_message_op) {
+ // Nothing further will try to receive from this stream, so finish off
+ // any outstanding send_message op
+ s->send_message_op->payload->send_message.send_message.reset();
s->send_message_op->payload->send_message.stream_write_closed = true;
- complete_if_batch_end_locked(
- s, new_err, s->send_message_op,
+ complete_if_batch_end_locked(
+ s, new_err, s->send_message_op,
"op_state_machine scheduling send-message-on-complete case 2");
- s->send_message_op = nullptr;
- }
- if (s->recv_trailing_md_op != nullptr) {
- // We wanted trailing metadata and we got it
- s->trailing_md_recvd = true;
- new_err =
- fill_in_metadata(s, &s->to_read_trailing_md, 0,
- s->recv_trailing_md_op->payload
- ->recv_trailing_metadata.recv_trailing_metadata,
- nullptr, nullptr);
- grpc_metadata_batch_clear(&s->to_read_trailing_md);
- s->to_read_trailing_md_filled = false;
-
- // We should schedule the recv_trailing_md_op completion if
- // 1. this stream is the client-side
- // 2. this stream is the server-side AND has already sent its trailing md
- // (If the server hasn't already sent its trailing md, it doesn't have
- // a final status, so don't mark this op complete)
- if (s->t->is_client || s->trailing_md_sent) {
- INPROC_LOG(GPR_INFO,
- "op_state_machine %p scheduling trailing-md-on-complete %p",
- s, new_err);
+ s->send_message_op = nullptr;
+ }
+ if (s->recv_trailing_md_op != nullptr) {
+ // We wanted trailing metadata and we got it
+ s->trailing_md_recvd = true;
+ new_err =
+ fill_in_metadata(s, &s->to_read_trailing_md, 0,
+ s->recv_trailing_md_op->payload
+ ->recv_trailing_metadata.recv_trailing_metadata,
+ nullptr, nullptr);
+ grpc_metadata_batch_clear(&s->to_read_trailing_md);
+ s->to_read_trailing_md_filled = false;
+
+ // We should schedule the recv_trailing_md_op completion if
+ // 1. this stream is the client-side
+ // 2. this stream is the server-side AND has already sent its trailing md
+ // (If the server hasn't already sent its trailing md, it doesn't have
+ // a final status, so don't mark this op complete)
+ if (s->t->is_client || s->trailing_md_sent) {
+ INPROC_LOG(GPR_INFO,
+ "op_state_machine %p scheduling trailing-md-on-complete %p",
+ s, new_err);
grpc_core::ExecCtx::Run(
DEBUG_LOCATION,
s->recv_trailing_md_op->payload->recv_trailing_metadata
@@ -810,20 +810,20 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
grpc_core::ExecCtx::Run(DEBUG_LOCATION,
s->recv_trailing_md_op->on_complete,
GRPC_ERROR_REF(new_err));
- s->recv_trailing_md_op = nullptr;
+ s->recv_trailing_md_op = nullptr;
needs_close = s->trailing_md_sent;
- } else {
- INPROC_LOG(GPR_INFO,
- "op_state_machine %p server needs to delay handling "
- "trailing-md-on-complete %p",
- s, new_err);
- }
+ } else {
+ INPROC_LOG(GPR_INFO,
+ "op_state_machine %p server needs to delay handling "
+ "trailing-md-on-complete %p",
+ s, new_err);
+ }
} else if (!s->trailing_md_recvd) {
- INPROC_LOG(
- GPR_INFO,
- "op_state_machine %p has trailing md but not yet waiting for it", s);
- }
- }
+ INPROC_LOG(
+ GPR_INFO,
+ "op_state_machine %p has trailing md but not yet waiting for it", s);
+ }
+ }
if (!s->t->is_client && s->trailing_md_sent &&
(s->recv_trailing_md_op != nullptr)) {
// In this case, we don't care to receive the write-close from the client
@@ -845,266 +845,266 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) {
// be ok (not an error) if the client actually sends it later.
s->trailing_md_recvd_implicit_only = true;
}
- if (s->trailing_md_recvd && s->recv_message_op) {
- // No further message will come on this stream, so finish off the
- // recv_message_op
- INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling message-ready", s);
+ if (s->trailing_md_recvd && s->recv_message_op) {
+ // No further message will come on this stream, so finish off the
+ // 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,
- s->recv_message_op->payload->recv_message.recv_message_ready,
- GRPC_ERROR_NONE);
- complete_if_batch_end_locked(
- s, new_err, s->recv_message_op,
- "op_state_machine scheduling recv-message-on-complete");
- s->recv_message_op = nullptr;
- }
+ s->recv_message_op->payload->recv_message.recv_message_ready,
+ GRPC_ERROR_NONE);
+ complete_if_batch_end_locked(
+ s, new_err, s->recv_message_op,
+ "op_state_machine scheduling recv-message-on-complete");
+ s->recv_message_op = nullptr;
+ }
if (s->trailing_md_recvd && s->send_message_op && s->t->is_client) {
- // Nothing further will try to receive from this stream, so finish off
- // any outstanding send_message op
- s->send_message_op->payload->send_message.send_message.reset();
- complete_if_batch_end_locked(
- s, new_err, s->send_message_op,
+ // Nothing further will try to receive from this stream, so finish off
+ // any outstanding send_message op
+ s->send_message_op->payload->send_message.send_message.reset();
+ complete_if_batch_end_locked(
+ s, new_err, s->send_message_op,
"op_state_machine scheduling send-message-on-complete case 3");
- s->send_message_op = nullptr;
- }
- if (s->send_message_op || s->send_trailing_md_op || s->recv_initial_md_op ||
- s->recv_message_op || s->recv_trailing_md_op) {
- // Didn't get the item we wanted so we still need to get
- // rescheduled
- INPROC_LOG(
- GPR_INFO, "op_state_machine %p still needs closure %p %p %p %p %p", s,
- s->send_message_op, s->send_trailing_md_op, s->recv_initial_md_op,
- s->recv_message_op, s->recv_trailing_md_op);
- s->ops_needed = true;
- }
-done:
- if (needs_close) {
- close_other_side_locked(s, "op_state_machine");
- close_stream_locked(s);
- }
- GRPC_ERROR_UNREF(new_err);
-}
-
+ s->send_message_op = nullptr;
+ }
+ if (s->send_message_op || s->send_trailing_md_op || s->recv_initial_md_op ||
+ s->recv_message_op || s->recv_trailing_md_op) {
+ // Didn't get the item we wanted so we still need to get
+ // rescheduled
+ INPROC_LOG(
+ GPR_INFO, "op_state_machine %p still needs closure %p %p %p %p %p", s,
+ s->send_message_op, s->send_trailing_md_op, s->recv_initial_md_op,
+ s->recv_message_op, s->recv_trailing_md_op);
+ s->ops_needed = true;
+ }
+done:
+ if (needs_close) {
+ close_other_side_locked(s, "op_state_machine");
+ close_stream_locked(s);
+ }
+ GRPC_ERROR_UNREF(new_err);
+}
+
bool cancel_stream_locked(inproc_stream* s, grpc_error* error) {
- bool ret = false; // was the cancel accepted
- INPROC_LOG(GPR_INFO, "cancel_stream %p with %s", s, grpc_error_string(error));
- if (s->cancel_self_error == GRPC_ERROR_NONE) {
- ret = true;
- s->cancel_self_error = GRPC_ERROR_REF(error);
+ bool ret = false; // was the cancel accepted
+ INPROC_LOG(GPR_INFO, "cancel_stream %p with %s", s, grpc_error_string(error));
+ if (s->cancel_self_error == GRPC_ERROR_NONE) {
+ ret = true;
+ s->cancel_self_error = GRPC_ERROR_REF(error);
// Catch current value of other before it gets closed off
inproc_stream* other = s->other_side;
maybe_process_ops_locked(s, s->cancel_self_error);
- // Send trailing md to the other side indicating cancellation, even if we
- // already have
- s->trailing_md_sent = true;
-
- grpc_metadata_batch cancel_md;
- grpc_metadata_batch_init(&cancel_md);
-
- grpc_metadata_batch* dest = (other == nullptr)
- ? &s->write_buffer_trailing_md
- : &other->to_read_trailing_md;
- bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled
- : &other->to_read_trailing_md_filled;
- fill_in_metadata(s, &cancel_md, 0, dest, nullptr, destfilled);
- grpc_metadata_batch_destroy(&cancel_md);
-
- if (other != nullptr) {
- if (other->cancel_other_error == GRPC_ERROR_NONE) {
- other->cancel_other_error = GRPC_ERROR_REF(s->cancel_self_error);
- }
+ // Send trailing md to the other side indicating cancellation, even if we
+ // already have
+ s->trailing_md_sent = true;
+
+ grpc_metadata_batch cancel_md;
+ grpc_metadata_batch_init(&cancel_md);
+
+ grpc_metadata_batch* dest = (other == nullptr)
+ ? &s->write_buffer_trailing_md
+ : &other->to_read_trailing_md;
+ bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled
+ : &other->to_read_trailing_md_filled;
+ fill_in_metadata(s, &cancel_md, 0, dest, nullptr, destfilled);
+ grpc_metadata_batch_destroy(&cancel_md);
+
+ if (other != nullptr) {
+ if (other->cancel_other_error == GRPC_ERROR_NONE) {
+ other->cancel_other_error = GRPC_ERROR_REF(s->cancel_self_error);
+ }
maybe_process_ops_locked(other, other->cancel_other_error);
- } else if (s->write_buffer_cancel_error == GRPC_ERROR_NONE) {
- s->write_buffer_cancel_error = GRPC_ERROR_REF(s->cancel_self_error);
- }
-
- // if we are a server and already received trailing md but
- // 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) {
+ } else if (s->write_buffer_cancel_error == GRPC_ERROR_NONE) {
+ s->write_buffer_cancel_error = GRPC_ERROR_REF(s->cancel_self_error);
+ }
+
+ // if we are a server and already received trailing md but
+ // 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));
- complete_if_batch_end_locked(
- s, s->cancel_self_error, s->recv_trailing_md_op,
- "cancel_stream scheduling trailing-md-on-complete");
- s->recv_trailing_md_op = nullptr;
- }
- }
-
- close_other_side_locked(s, "cancel_stream:other_side");
- close_stream_locked(s);
-
- GRPC_ERROR_UNREF(error);
- return ret;
-}
-
+ complete_if_batch_end_locked(
+ s, s->cancel_self_error, s->recv_trailing_md_op,
+ "cancel_stream scheduling trailing-md-on-complete");
+ s->recv_trailing_md_op = nullptr;
+ }
+ }
+
+ close_other_side_locked(s, "cancel_stream:other_side");
+ close_stream_locked(s);
+
+ GRPC_ERROR_UNREF(error);
+ return ret;
+}
+
void do_nothing(void* /*arg*/, grpc_error* /*error*/) {}
void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
grpc_transport_stream_op_batch* op) {
- INPROC_LOG(GPR_INFO, "perform_stream_op %p %p %p", gt, gs, op);
- inproc_stream* s = reinterpret_cast<inproc_stream*>(gs);
- gpr_mu* mu = &s->t->mu->mu; // save aside in case s gets closed
- gpr_mu_lock(mu);
-
+ INPROC_LOG(GPR_INFO, "perform_stream_op %p %p %p", gt, gs, op);
+ inproc_stream* s = reinterpret_cast<inproc_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 (op->send_initial_metadata) {
- log_metadata(op->payload->send_initial_metadata.send_initial_metadata,
- s->t->is_client, true);
- }
- if (op->send_trailing_metadata) {
- log_metadata(op->payload->send_trailing_metadata.send_trailing_metadata,
- s->t->is_client, false);
- }
- }
- grpc_error* error = GRPC_ERROR_NONE;
- grpc_closure* on_complete = op->on_complete;
+ if (op->send_initial_metadata) {
+ log_metadata(op->payload->send_initial_metadata.send_initial_metadata,
+ s->t->is_client, true);
+ }
+ if (op->send_trailing_metadata) {
+ log_metadata(op->payload->send_trailing_metadata.send_trailing_metadata,
+ s->t->is_client, false);
+ }
+ }
+ grpc_error* error = GRPC_ERROR_NONE;
+ grpc_closure* on_complete = op->on_complete;
// TODO(roth): This is a hack needed because we use data inside of the
// closure itself to do the barrier calculation (i.e., to ensure that
// we don't schedule the closure until all ops in the batch have been
// completed). This can go away once we move to a new C++ closure API
// that provides the ability to create a barrier closure.
- if (on_complete == nullptr) {
+ if (on_complete == nullptr) {
on_complete = GRPC_CLOSURE_INIT(&op->handler_private.closure, do_nothing,
nullptr, grpc_schedule_on_exec_ctx);
- }
-
- if (op->cancel_stream) {
- // Call cancel_stream_locked without ref'ing the cancel_error because
- // this function is responsible to make sure that that field gets unref'ed
- cancel_stream_locked(s, op->payload->cancel_stream.cancel_error);
- // this op can complete without an error
- } else if (s->cancel_self_error != GRPC_ERROR_NONE) {
- // already self-canceled so still give it an error
- error = GRPC_ERROR_REF(s->cancel_self_error);
- } else {
- INPROC_LOG(GPR_INFO, "perform_stream_op %p %s%s%s%s%s%s%s", s,
- s->t->is_client ? "client" : "server",
- op->send_initial_metadata ? " send_initial_metadata" : "",
- op->send_message ? " send_message" : "",
- op->send_trailing_metadata ? " send_trailing_metadata" : "",
- op->recv_initial_metadata ? " recv_initial_metadata" : "",
- op->recv_message ? " recv_message" : "",
- op->recv_trailing_metadata ? " recv_trailing_metadata" : "");
- }
-
- inproc_stream* other = s->other_side;
- if (error == GRPC_ERROR_NONE &&
- (op->send_initial_metadata || op->send_trailing_metadata)) {
- if (s->t->is_closed) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Endpoint already shutdown");
- }
- if (error == GRPC_ERROR_NONE && op->send_initial_metadata) {
- grpc_metadata_batch* dest = (other == nullptr)
- ? &s->write_buffer_initial_md
- : &other->to_read_initial_md;
- uint32_t* destflags = (other == nullptr)
- ? &s->write_buffer_initial_md_flags
- : &other->to_read_initial_md_flags;
- bool* destfilled = (other == nullptr) ? &s->write_buffer_initial_md_filled
- : &other->to_read_initial_md_filled;
- if (*destfilled || s->initial_md_sent) {
- // The buffer is already in use; that's an error!
- INPROC_LOG(GPR_INFO, "Extra initial metadata %p", s);
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Extra initial metadata");
- } else {
+ }
+
+ if (op->cancel_stream) {
+ // Call cancel_stream_locked without ref'ing the cancel_error because
+ // this function is responsible to make sure that that field gets unref'ed
+ cancel_stream_locked(s, op->payload->cancel_stream.cancel_error);
+ // this op can complete without an error
+ } else if (s->cancel_self_error != GRPC_ERROR_NONE) {
+ // already self-canceled so still give it an error
+ error = GRPC_ERROR_REF(s->cancel_self_error);
+ } else {
+ INPROC_LOG(GPR_INFO, "perform_stream_op %p %s%s%s%s%s%s%s", s,
+ s->t->is_client ? "client" : "server",
+ op->send_initial_metadata ? " send_initial_metadata" : "",
+ op->send_message ? " send_message" : "",
+ op->send_trailing_metadata ? " send_trailing_metadata" : "",
+ op->recv_initial_metadata ? " recv_initial_metadata" : "",
+ op->recv_message ? " recv_message" : "",
+ op->recv_trailing_metadata ? " recv_trailing_metadata" : "");
+ }
+
+ inproc_stream* other = s->other_side;
+ if (error == GRPC_ERROR_NONE &&
+ (op->send_initial_metadata || op->send_trailing_metadata)) {
+ if (s->t->is_closed) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Endpoint already shutdown");
+ }
+ if (error == GRPC_ERROR_NONE && op->send_initial_metadata) {
+ grpc_metadata_batch* dest = (other == nullptr)
+ ? &s->write_buffer_initial_md
+ : &other->to_read_initial_md;
+ uint32_t* destflags = (other == nullptr)
+ ? &s->write_buffer_initial_md_flags
+ : &other->to_read_initial_md_flags;
+ bool* destfilled = (other == nullptr) ? &s->write_buffer_initial_md_filled
+ : &other->to_read_initial_md_filled;
+ if (*destfilled || s->initial_md_sent) {
+ // The buffer is already in use; that's an error!
+ INPROC_LOG(GPR_INFO, "Extra initial metadata %p", s);
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Extra initial metadata");
+ } else {
if (!s->other_side_closed) {
- fill_in_metadata(
- s, op->payload->send_initial_metadata.send_initial_metadata,
- op->payload->send_initial_metadata.send_initial_metadata_flags,
- dest, destflags, destfilled);
- }
- if (s->t->is_client) {
- grpc_millis* dl =
- (other == nullptr) ? &s->write_buffer_deadline : &other->deadline;
- *dl = GPR_MIN(*dl, op->payload->send_initial_metadata
- .send_initial_metadata->deadline);
- s->initial_md_sent = true;
- }
- }
+ fill_in_metadata(
+ s, op->payload->send_initial_metadata.send_initial_metadata,
+ op->payload->send_initial_metadata.send_initial_metadata_flags,
+ dest, destflags, destfilled);
+ }
+ if (s->t->is_client) {
+ grpc_millis* dl =
+ (other == nullptr) ? &s->write_buffer_deadline : &other->deadline;
+ *dl = GPR_MIN(*dl, op->payload->send_initial_metadata
+ .send_initial_metadata->deadline);
+ s->initial_md_sent = true;
+ }
+ }
maybe_process_ops_locked(other, error);
- }
- }
-
- if (error == GRPC_ERROR_NONE &&
- (op->send_message || op->send_trailing_metadata ||
- op->recv_initial_metadata || op->recv_message ||
- op->recv_trailing_metadata)) {
+ }
+ }
+
+ if (error == GRPC_ERROR_NONE &&
+ (op->send_message || op->send_trailing_metadata ||
+ op->recv_initial_metadata || op->recv_message ||
+ op->recv_trailing_metadata)) {
// Mark ops that need to be processed by the state machine
- if (op->send_message) {
- s->send_message_op = op;
- }
- if (op->send_trailing_metadata) {
- s->send_trailing_md_op = op;
- }
- if (op->recv_initial_metadata) {
- s->recv_initial_md_op = op;
- }
- if (op->recv_message) {
- s->recv_message_op = op;
- }
- if (op->recv_trailing_metadata) {
- s->recv_trailing_md_op = op;
- }
-
+ if (op->send_message) {
+ s->send_message_op = op;
+ }
+ if (op->send_trailing_metadata) {
+ s->send_trailing_md_op = op;
+ }
+ if (op->recv_initial_metadata) {
+ s->recv_initial_md_op = op;
+ }
+ if (op->recv_message) {
+ s->recv_message_op = op;
+ }
+ if (op->recv_trailing_metadata) {
+ s->recv_trailing_md_op = op;
+ }
+
// We want to initiate the state machine if:
// 1. We want to send a message and the other side wants to receive
- // 2. We want to send trailing metadata and there isn't an unmatched send
+ // 2. We want to send trailing metadata and there isn't an unmatched send
// or the other side wants trailing metadata
- // 3. We want initial metadata and the other side has sent it
- // 4. We want to receive a message and there is a message ready
- // 5. There is trailing metadata, even if nothing specifically wants
- // that because that can shut down the receive message as well
+ // 3. We want initial metadata and the other side has sent it
+ // 4. We want to receive a message and there is a message ready
+ // 5. There is trailing metadata, even if nothing specifically wants
+ // that because that can shut down the receive message as well
if ((op->send_message && other && other->recv_message_op != nullptr) ||
(op->send_trailing_metadata &&
(!s->send_message_op || (other && other->recv_trailing_md_op))) ||
- (op->recv_initial_metadata && s->to_read_initial_md_filled) ||
+ (op->recv_initial_metadata && s->to_read_initial_md_filled) ||
(op->recv_message && other && other->send_message_op != nullptr) ||
- (s->to_read_trailing_md_filled || s->trailing_md_recvd)) {
+ (s->to_read_trailing_md_filled || s->trailing_md_recvd)) {
op_state_machine_locked(s, error);
- } else {
- s->ops_needed = true;
- }
- } else {
- if (error != GRPC_ERROR_NONE) {
+ } else {
+ s->ops_needed = true;
+ }
+ } 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();
}
- // 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 !=
- nullptr) {
- // Set to true unconditionally, because we're failing the call, so
- // even if we haven't actually seen the send_trailing_metadata op
- // from the other side, we're going to return trailing metadata
- // anyway.
- *op->payload->recv_initial_metadata.trailing_metadata_available =
- true;
- }
- INPROC_LOG(
- GPR_INFO,
- "perform_stream_op error %p scheduling initial-metadata-ready %p",
- s, error);
+ // 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 !=
+ nullptr) {
+ // Set to true unconditionally, because we're failing the call, so
+ // even if we haven't actually seen the send_trailing_metadata op
+ // from the other side, we're going to return trailing metadata
+ // anyway.
+ *op->payload->recv_initial_metadata.trailing_metadata_available =
+ true;
+ }
+ INPROC_LOG(
+ GPR_INFO,
+ "perform_stream_op error %p scheduling initial-metadata-ready %p",
+ s, error);
grpc_core::ExecCtx::Run(
DEBUG_LOCATION,
- op->payload->recv_initial_metadata.recv_initial_metadata_ready,
- GRPC_ERROR_REF(error));
- }
- if (op->recv_message) {
- INPROC_LOG(
- GPR_INFO,
- "perform_stream_op error %p scheduling recv message-ready %p", s,
- error);
+ op->payload->recv_initial_metadata.recv_initial_metadata_ready,
+ GRPC_ERROR_REF(error));
+ }
+ if (op->recv_message) {
+ INPROC_LOG(
+ 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));
- }
+ }
if (op->recv_trailing_metadata) {
INPROC_LOG(
GPR_INFO,
@@ -1115,114 +1115,114 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs,
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);
+ }
+ 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));
- }
- gpr_mu_unlock(mu);
- GRPC_ERROR_UNREF(error);
-}
-
+ }
+ gpr_mu_unlock(mu);
+ GRPC_ERROR_UNREF(error);
+}
+
void close_transport_locked(inproc_transport* t) {
- INPROC_LOG(GPR_INFO, "close_transport %p %d", t, t->is_closed);
+ INPROC_LOG(GPR_INFO, "close_transport %p %d", t, t->is_closed);
t->state_tracker.SetState(GRPC_CHANNEL_SHUTDOWN, y_absl::Status(),
"close transport");
- if (!t->is_closed) {
- t->is_closed = true;
- /* Also end all streams on this transport */
- while (t->stream_list != nullptr) {
- // cancel_stream_locked also adjusts stream list
- cancel_stream_locked(
- t->stream_list,
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport closed"),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
- }
- }
-}
-
+ if (!t->is_closed) {
+ t->is_closed = true;
+ /* Also end all streams on this transport */
+ while (t->stream_list != nullptr) {
+ // cancel_stream_locked also adjusts stream list
+ cancel_stream_locked(
+ t->stream_list,
+ grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport closed"),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE));
+ }
+ }
+}
+
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);
+ 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->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) {
+ 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);
- }
-
- bool do_close = false;
- if (op->goaway_error != GRPC_ERROR_NONE) {
- do_close = true;
- GRPC_ERROR_UNREF(op->goaway_error);
- }
- if (op->disconnect_with_error != GRPC_ERROR_NONE) {
- do_close = true;
- GRPC_ERROR_UNREF(op->disconnect_with_error);
- }
-
- if (do_close) {
- close_transport_locked(t);
- }
- gpr_mu_unlock(&t->mu->mu);
-}
-
+ }
+
+ bool do_close = false;
+ if (op->goaway_error != GRPC_ERROR_NONE) {
+ do_close = true;
+ GRPC_ERROR_UNREF(op->goaway_error);
+ }
+ if (op->disconnect_with_error != GRPC_ERROR_NONE) {
+ do_close = true;
+ GRPC_ERROR_UNREF(op->disconnect_with_error);
+ }
+
+ if (do_close) {
+ close_transport_locked(t);
+ }
+ gpr_mu_unlock(&t->mu->mu);
+}
+
void destroy_stream(grpc_transport* gt, grpc_stream* gs,
grpc_closure* then_schedule_closure) {
- INPROC_LOG(GPR_INFO, "destroy_stream %p %p", gs, then_schedule_closure);
+ INPROC_LOG(GPR_INFO, "destroy_stream %p %p", gs, then_schedule_closure);
inproc_transport* t = reinterpret_cast<inproc_transport*>(gt);
- inproc_stream* s = reinterpret_cast<inproc_stream*>(gs);
+ inproc_stream* s = reinterpret_cast<inproc_stream*>(gs);
gpr_mu_lock(&t->mu->mu);
close_stream_locked(s);
gpr_mu_unlock(&t->mu->mu);
s->~inproc_stream();
grpc_core::ExecCtx::Run(DEBUG_LOCATION, then_schedule_closure,
GRPC_ERROR_NONE);
-}
-
+}
+
void destroy_transport(grpc_transport* gt) {
- inproc_transport* t = reinterpret_cast<inproc_transport*>(gt);
- INPROC_LOG(GPR_INFO, "destroy_transport %p", t);
- gpr_mu_lock(&t->mu->mu);
- close_transport_locked(t);
- gpr_mu_unlock(&t->mu->mu);
+ inproc_transport* t = reinterpret_cast<inproc_transport*>(gt);
+ INPROC_LOG(GPR_INFO, "destroy_transport %p", t);
+ gpr_mu_lock(&t->mu->mu);
+ close_transport_locked(t);
+ gpr_mu_unlock(&t->mu->mu);
t->other_side->unref();
t->unref();
-}
-
-/*******************************************************************************
- * INTEGRATION GLUE
- */
-
+}
+
+/*******************************************************************************
+ * INTEGRATION GLUE
+ */
+
void set_pollset(grpc_transport* /*gt*/, grpc_stream* /*gs*/,
grpc_pollset* /*pollset*/) {
- // Nothing to do here
-}
-
+ // Nothing to do here
+}
+
void set_pollset_set(grpc_transport* /*gt*/, grpc_stream* /*gs*/,
grpc_pollset_set* /*pollset_set*/) {
- // Nothing to do here
-}
-
+ // Nothing to do here
+}
+
grpc_endpoint* get_endpoint(grpc_transport* /*t*/) { return nullptr; }
-
+
const grpc_transport_vtable inproc_vtable = {
sizeof(inproc_stream), "inproc", init_stream,
set_pollset, set_pollset_set, perform_stream_op,
perform_transport_op, destroy_stream, destroy_transport,
get_endpoint};
-/*******************************************************************************
+/*******************************************************************************
* Main inproc transport functions
*/
void inproc_transports_create(grpc_transport** server_transport,
@@ -1243,33 +1243,33 @@ void inproc_transports_create(grpc_transport** server_transport,
} // namespace
/*******************************************************************************
- * GLOBAL INIT AND DESTROY
- */
-void grpc_inproc_transport_init(void) {
- grpc_core::ExecCtx exec_ctx;
+ * GLOBAL INIT AND DESTROY
+ */
+void grpc_inproc_transport_init(void) {
+ grpc_core::ExecCtx exec_ctx;
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);
- grpc_slice_unref_internal(key_tmp);
-
- g_fake_path_value = grpc_slice_from_static_string("/");
-
- grpc_slice auth_tmp = grpc_slice_from_static_string(":authority");
- g_fake_auth_key = grpc_slice_intern(auth_tmp);
- grpc_slice_unref_internal(auth_tmp);
-
- g_fake_auth_value = grpc_slice_from_static_string("inproc-fail");
-}
-
-grpc_channel* grpc_inproc_channel_create(grpc_server* server,
- grpc_channel_args* args,
+
+ grpc_slice key_tmp = grpc_slice_from_static_string(":path");
+ g_fake_path_key = grpc_slice_intern(key_tmp);
+ grpc_slice_unref_internal(key_tmp);
+
+ g_fake_path_value = grpc_slice_from_static_string("/");
+
+ grpc_slice auth_tmp = grpc_slice_from_static_string(":authority");
+ g_fake_auth_key = grpc_slice_intern(auth_tmp);
+ grpc_slice_unref_internal(auth_tmp);
+
+ g_fake_auth_value = grpc_slice_from_static_string("inproc-fail");
+}
+
+grpc_channel* grpc_inproc_channel_create(grpc_server* server,
+ grpc_channel_args* args,
void* /*reserved*/) {
- GRPC_API_TRACE("grpc_inproc_channel_create(server=%p, args=%p)", 2,
- (server, args));
-
- grpc_core::ExecCtx exec_ctx;
-
+ 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,
@@ -1277,40 +1277,40 @@ grpc_channel* grpc_inproc_channel_create(grpc_server* server,
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));
-
- // Add a default authority channel argument for the client
- grpc_arg default_authority_arg;
- default_authority_arg.type = GRPC_ARG_STRING;
- default_authority_arg.key = (char*)GRPC_ARG_DEFAULT_AUTHORITY;
- default_authority_arg.value.string = (char*)"inproc.authority";
- grpc_channel_args* client_args =
- grpc_channel_args_copy_and_add(args, &default_authority_arg, 1);
-
- grpc_transport* server_transport;
- grpc_transport* client_transport;
- inproc_transports_create(&server_transport, server_args, &client_transport,
- client_args);
-
+
+ // Add a default authority channel argument for the client
+ grpc_arg default_authority_arg;
+ default_authority_arg.type = GRPC_ARG_STRING;
+ default_authority_arg.key = (char*)GRPC_ARG_DEFAULT_AUTHORITY;
+ default_authority_arg.value.string = (char*)"inproc.authority";
+ grpc_channel_args* client_args =
+ grpc_channel_args_copy_and_add(args, &default_authority_arg, 1);
+
+ grpc_transport* server_transport;
+ grpc_transport* client_transport;
+ inproc_transports_create(&server_transport, server_args, &client_transport,
+ client_args);
+
// TODO(ncteisen): design and support channelz GetSocket for inproc.
server->core_server->SetupTransport(server_transport, nullptr, server_args,
nullptr);
- grpc_channel* channel = grpc_channel_create(
- "inproc", client_args, GRPC_CLIENT_DIRECT_CHANNEL, client_transport);
-
- // Free up created channel args
+ grpc_channel* channel = grpc_channel_create(
+ "inproc", client_args, GRPC_CLIENT_DIRECT_CHANNEL, client_transport);
+
+ // Free up created channel args
grpc_channel_args_destroy(server_args);
- grpc_channel_args_destroy(client_args);
-
- // Now finish scheduled operations
-
- return channel;
-}
-
-void grpc_inproc_transport_shutdown(void) {
- grpc_core::ExecCtx exec_ctx;
- grpc_slice_unref_internal(g_empty_slice);
- grpc_slice_unref_internal(g_fake_path_key);
- grpc_slice_unref_internal(g_fake_path_value);
- grpc_slice_unref_internal(g_fake_auth_key);
- grpc_slice_unref_internal(g_fake_auth_value);
-}
+ grpc_channel_args_destroy(client_args);
+
+ // Now finish scheduled operations
+
+ return channel;
+}
+
+void grpc_inproc_transport_shutdown(void) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_slice_unref_internal(g_empty_slice);
+ grpc_slice_unref_internal(g_fake_path_key);
+ grpc_slice_unref_internal(g_fake_path_value);
+ grpc_slice_unref_internal(g_fake_auth_key);
+ grpc_slice_unref_internal(g_fake_auth_value);
+}
diff --git a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.h b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.h
index 049d1402afe..7bfb121a2ff 100644
--- a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.h
+++ b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.h
@@ -1,35 +1,35 @@
-/*
- *
- * 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_EXT_TRANSPORT_INPROC_INPROC_TRANSPORT_H
-#define GRPC_CORE_EXT_TRANSPORT_INPROC_INPROC_TRANSPORT_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/transport/transport_impl.h"
-
-grpc_channel* grpc_inproc_channel_create(grpc_server* server,
- grpc_channel_args* args,
- void* reserved);
-
-extern grpc_core::TraceFlag grpc_inproc_trace;
-
-void grpc_inproc_transport_init(void);
-void grpc_inproc_transport_shutdown(void);
-
-#endif /* GRPC_CORE_EXT_TRANSPORT_INPROC_INPROC_TRANSPORT_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.
+ *
+ */
+
+#ifndef GRPC_CORE_EXT_TRANSPORT_INPROC_INPROC_TRANSPORT_H
+#define GRPC_CORE_EXT_TRANSPORT_INPROC_INPROC_TRANSPORT_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/transport/transport_impl.h"
+
+grpc_channel* grpc_inproc_channel_create(grpc_server* server,
+ grpc_channel_args* args,
+ void* reserved);
+
+extern grpc_core::TraceFlag grpc_inproc_trace;
+
+void grpc_inproc_transport_init(void);
+void grpc_inproc_transport_shutdown(void);
+
+#endif /* GRPC_CORE_EXT_TRANSPORT_INPROC_INPROC_TRANSPORT_H */
diff --git a/contrib/libs/grpc/src/core/lib/avl/avl.cc b/contrib/libs/grpc/src/core/lib/avl/avl.cc
index e04fe35b197..6fee4197733 100644
--- a/contrib/libs/grpc/src/core/lib/avl/avl.cc
+++ b/contrib/libs/grpc/src/core/lib/avl/avl.cc
@@ -1,306 +1,306 @@
-/*
- *
- * 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/avl/avl.h"
-
-#include <assert.h>
-#include <stdlib.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-grpc_avl grpc_avl_create(const grpc_avl_vtable* vtable) {
- grpc_avl out;
- out.vtable = vtable;
- out.root = nullptr;
- return out;
-}
-
-static grpc_avl_node* ref_node(grpc_avl_node* node) {
- if (node) {
- gpr_ref(&node->refs);
- }
- return node;
-}
-
-static void unref_node(const grpc_avl_vtable* vtable, grpc_avl_node* node,
- void* user_data) {
- if (node == nullptr) {
- return;
- }
- if (gpr_unref(&node->refs)) {
- vtable->destroy_key(node->key, user_data);
- vtable->destroy_value(node->value, user_data);
- unref_node(vtable, node->left, user_data);
- unref_node(vtable, node->right, user_data);
- gpr_free(node);
- }
-}
-
-static long node_height(grpc_avl_node* node) {
- return node == nullptr ? 0 : node->height;
-}
-
-#ifndef NDEBUG
-static long calculate_height(grpc_avl_node* node) {
- return node == nullptr ? 0
- : 1 + GPR_MAX(calculate_height(node->left),
- calculate_height(node->right));
-}
-
-static grpc_avl_node* assert_invariants(grpc_avl_node* n) {
- if (n == nullptr) return nullptr;
- assert_invariants(n->left);
- assert_invariants(n->right);
- assert(calculate_height(n) == n->height);
- assert(labs(node_height(n->left) - node_height(n->right)) <= 1);
- return n;
-}
-#else
-static grpc_avl_node* assert_invariants(grpc_avl_node* n) { return n; }
-#endif
-
-grpc_avl_node* new_node(void* key, void* value, grpc_avl_node* left,
- grpc_avl_node* right) {
- grpc_avl_node* node = static_cast<grpc_avl_node*>(gpr_malloc(sizeof(*node)));
- gpr_ref_init(&node->refs, 1);
- node->key = key;
- node->value = value;
- node->left = assert_invariants(left);
- node->right = assert_invariants(right);
- node->height = 1 + GPR_MAX(node_height(left), node_height(right));
- return node;
-}
-
-static grpc_avl_node* get(const grpc_avl_vtable* vtable, grpc_avl_node* node,
- void* key, void* user_data) {
- long cmp;
-
- if (node == nullptr) {
- return nullptr;
- }
-
- cmp = vtable->compare_keys(node->key, key, user_data);
- if (cmp == 0) {
- return node;
- } else if (cmp > 0) {
- return get(vtable, node->left, key, user_data);
- } else {
- return get(vtable, node->right, key, user_data);
- }
-}
-
-void* grpc_avl_get(grpc_avl avl, void* key, void* user_data) {
- grpc_avl_node* node = get(avl.vtable, avl.root, key, user_data);
- return node ? node->value : nullptr;
-}
-
-int grpc_avl_maybe_get(grpc_avl avl, void* key, void** value, void* user_data) {
- grpc_avl_node* node = get(avl.vtable, avl.root, key, user_data);
- if (node != nullptr) {
- *value = node->value;
- return 1;
- }
- return 0;
-}
-
-static grpc_avl_node* rotate_left(const grpc_avl_vtable* vtable, void* key,
- void* value, grpc_avl_node* left,
- grpc_avl_node* right, void* user_data) {
- grpc_avl_node* n = new_node(vtable->copy_key(right->key, user_data),
- vtable->copy_value(right->value, user_data),
- new_node(key, value, left, ref_node(right->left)),
- ref_node(right->right));
- unref_node(vtable, right, user_data);
- return n;
-}
-
-static grpc_avl_node* rotate_right(const grpc_avl_vtable* vtable, void* key,
- void* value, grpc_avl_node* left,
- grpc_avl_node* right, void* user_data) {
- grpc_avl_node* n =
- new_node(vtable->copy_key(left->key, user_data),
- vtable->copy_value(left->value, user_data), ref_node(left->left),
- new_node(key, value, ref_node(left->right), right));
- unref_node(vtable, left, user_data);
- return n;
-}
-
-static grpc_avl_node* rotate_left_right(const grpc_avl_vtable* vtable,
- void* key, void* value,
- grpc_avl_node* left,
- grpc_avl_node* right, void* user_data) {
- /* rotate_right(..., rotate_left(left), right) */
- grpc_avl_node* n =
- new_node(vtable->copy_key(left->right->key, user_data),
- vtable->copy_value(left->right->value, user_data),
- new_node(vtable->copy_key(left->key, user_data),
- vtable->copy_value(left->value, user_data),
- ref_node(left->left), ref_node(left->right->left)),
- new_node(key, value, ref_node(left->right->right), right));
- unref_node(vtable, left, user_data);
- return n;
-}
-
-static grpc_avl_node* rotate_right_left(const grpc_avl_vtable* vtable,
- void* key, void* value,
- grpc_avl_node* left,
- grpc_avl_node* right, void* user_data) {
- /* rotate_left(..., left, rotate_right(right)) */
- grpc_avl_node* n =
- new_node(vtable->copy_key(right->left->key, user_data),
- vtable->copy_value(right->left->value, user_data),
- new_node(key, value, left, ref_node(right->left->left)),
- new_node(vtable->copy_key(right->key, user_data),
- vtable->copy_value(right->value, user_data),
- ref_node(right->left->right), ref_node(right->right)));
- unref_node(vtable, right, user_data);
- return n;
-}
-
-static grpc_avl_node* rebalance(const grpc_avl_vtable* vtable, void* key,
- void* value, grpc_avl_node* left,
- grpc_avl_node* right, void* user_data) {
- switch (node_height(left) - node_height(right)) {
- case 2:
- if (node_height(left->left) - node_height(left->right) == -1) {
- return assert_invariants(
- rotate_left_right(vtable, key, value, left, right, user_data));
- } else {
- return assert_invariants(
- rotate_right(vtable, key, value, left, right, user_data));
- }
- case -2:
- if (node_height(right->left) - node_height(right->right) == 1) {
- return assert_invariants(
- rotate_right_left(vtable, key, value, left, right, user_data));
- } else {
- return assert_invariants(
- rotate_left(vtable, key, value, left, right, user_data));
- }
- default:
- return assert_invariants(new_node(key, value, left, right));
- }
-}
-
-static grpc_avl_node* add_key(const grpc_avl_vtable* vtable,
- grpc_avl_node* node, void* key, void* value,
- void* user_data) {
- long cmp;
- if (node == nullptr) {
- return new_node(key, value, nullptr, nullptr);
- }
- cmp = vtable->compare_keys(node->key, key, user_data);
- if (cmp == 0) {
- return new_node(key, value, ref_node(node->left), ref_node(node->right));
- } else if (cmp > 0) {
- return rebalance(vtable, vtable->copy_key(node->key, user_data),
- vtable->copy_value(node->value, user_data),
- add_key(vtable, node->left, key, value, user_data),
- ref_node(node->right), user_data);
- } else {
- return rebalance(
- vtable, vtable->copy_key(node->key, user_data),
- vtable->copy_value(node->value, user_data), ref_node(node->left),
- add_key(vtable, node->right, key, value, user_data), user_data);
- }
-}
-
-grpc_avl grpc_avl_add(grpc_avl avl, void* key, void* value, void* user_data) {
- grpc_avl_node* old_root = avl.root;
- avl.root = add_key(avl.vtable, avl.root, key, value, user_data);
- assert_invariants(avl.root);
- unref_node(avl.vtable, old_root, user_data);
- return avl;
-}
-
-static grpc_avl_node* in_order_head(grpc_avl_node* node) {
- while (node->left != nullptr) {
- node = node->left;
- }
- return node;
-}
-
-static grpc_avl_node* in_order_tail(grpc_avl_node* node) {
- while (node->right != nullptr) {
- node = node->right;
- }
- return node;
-}
-
-static grpc_avl_node* remove_key(const grpc_avl_vtable* vtable,
- grpc_avl_node* node, void* key,
- void* user_data) {
- long cmp;
- if (node == nullptr) {
- return nullptr;
- }
- cmp = vtable->compare_keys(node->key, key, user_data);
- if (cmp == 0) {
- if (node->left == nullptr) {
- return ref_node(node->right);
- } else if (node->right == nullptr) {
- return ref_node(node->left);
- } else if (node->left->height < node->right->height) {
- grpc_avl_node* h = in_order_head(node->right);
- return rebalance(
- vtable, vtable->copy_key(h->key, user_data),
- vtable->copy_value(h->value, user_data), ref_node(node->left),
- remove_key(vtable, node->right, h->key, user_data), user_data);
- } else {
- grpc_avl_node* h = in_order_tail(node->left);
- return rebalance(vtable, vtable->copy_key(h->key, user_data),
- vtable->copy_value(h->value, user_data),
- remove_key(vtable, node->left, h->key, user_data),
- ref_node(node->right), user_data);
- }
- } else if (cmp > 0) {
- return rebalance(vtable, vtable->copy_key(node->key, user_data),
- vtable->copy_value(node->value, user_data),
- remove_key(vtable, node->left, key, user_data),
- ref_node(node->right), user_data);
- } else {
- return rebalance(
- vtable, vtable->copy_key(node->key, user_data),
- vtable->copy_value(node->value, user_data), ref_node(node->left),
- remove_key(vtable, node->right, key, user_data), user_data);
- }
-}
-
-grpc_avl grpc_avl_remove(grpc_avl avl, void* key, void* user_data) {
- grpc_avl_node* old_root = avl.root;
- avl.root = remove_key(avl.vtable, avl.root, key, user_data);
- assert_invariants(avl.root);
- unref_node(avl.vtable, old_root, user_data);
- return avl;
-}
-
+/*
+ *
+ * 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/avl/avl.h"
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+grpc_avl grpc_avl_create(const grpc_avl_vtable* vtable) {
+ grpc_avl out;
+ out.vtable = vtable;
+ out.root = nullptr;
+ return out;
+}
+
+static grpc_avl_node* ref_node(grpc_avl_node* node) {
+ if (node) {
+ gpr_ref(&node->refs);
+ }
+ return node;
+}
+
+static void unref_node(const grpc_avl_vtable* vtable, grpc_avl_node* node,
+ void* user_data) {
+ if (node == nullptr) {
+ return;
+ }
+ if (gpr_unref(&node->refs)) {
+ vtable->destroy_key(node->key, user_data);
+ vtable->destroy_value(node->value, user_data);
+ unref_node(vtable, node->left, user_data);
+ unref_node(vtable, node->right, user_data);
+ gpr_free(node);
+ }
+}
+
+static long node_height(grpc_avl_node* node) {
+ return node == nullptr ? 0 : node->height;
+}
+
+#ifndef NDEBUG
+static long calculate_height(grpc_avl_node* node) {
+ return node == nullptr ? 0
+ : 1 + GPR_MAX(calculate_height(node->left),
+ calculate_height(node->right));
+}
+
+static grpc_avl_node* assert_invariants(grpc_avl_node* n) {
+ if (n == nullptr) return nullptr;
+ assert_invariants(n->left);
+ assert_invariants(n->right);
+ assert(calculate_height(n) == n->height);
+ assert(labs(node_height(n->left) - node_height(n->right)) <= 1);
+ return n;
+}
+#else
+static grpc_avl_node* assert_invariants(grpc_avl_node* n) { return n; }
+#endif
+
+grpc_avl_node* new_node(void* key, void* value, grpc_avl_node* left,
+ grpc_avl_node* right) {
+ grpc_avl_node* node = static_cast<grpc_avl_node*>(gpr_malloc(sizeof(*node)));
+ gpr_ref_init(&node->refs, 1);
+ node->key = key;
+ node->value = value;
+ node->left = assert_invariants(left);
+ node->right = assert_invariants(right);
+ node->height = 1 + GPR_MAX(node_height(left), node_height(right));
+ return node;
+}
+
+static grpc_avl_node* get(const grpc_avl_vtable* vtable, grpc_avl_node* node,
+ void* key, void* user_data) {
+ long cmp;
+
+ if (node == nullptr) {
+ return nullptr;
+ }
+
+ cmp = vtable->compare_keys(node->key, key, user_data);
+ if (cmp == 0) {
+ return node;
+ } else if (cmp > 0) {
+ return get(vtable, node->left, key, user_data);
+ } else {
+ return get(vtable, node->right, key, user_data);
+ }
+}
+
+void* grpc_avl_get(grpc_avl avl, void* key, void* user_data) {
+ grpc_avl_node* node = get(avl.vtable, avl.root, key, user_data);
+ return node ? node->value : nullptr;
+}
+
+int grpc_avl_maybe_get(grpc_avl avl, void* key, void** value, void* user_data) {
+ grpc_avl_node* node = get(avl.vtable, avl.root, key, user_data);
+ if (node != nullptr) {
+ *value = node->value;
+ return 1;
+ }
+ return 0;
+}
+
+static grpc_avl_node* rotate_left(const grpc_avl_vtable* vtable, void* key,
+ void* value, grpc_avl_node* left,
+ grpc_avl_node* right, void* user_data) {
+ grpc_avl_node* n = new_node(vtable->copy_key(right->key, user_data),
+ vtable->copy_value(right->value, user_data),
+ new_node(key, value, left, ref_node(right->left)),
+ ref_node(right->right));
+ unref_node(vtable, right, user_data);
+ return n;
+}
+
+static grpc_avl_node* rotate_right(const grpc_avl_vtable* vtable, void* key,
+ void* value, grpc_avl_node* left,
+ grpc_avl_node* right, void* user_data) {
+ grpc_avl_node* n =
+ new_node(vtable->copy_key(left->key, user_data),
+ vtable->copy_value(left->value, user_data), ref_node(left->left),
+ new_node(key, value, ref_node(left->right), right));
+ unref_node(vtable, left, user_data);
+ return n;
+}
+
+static grpc_avl_node* rotate_left_right(const grpc_avl_vtable* vtable,
+ void* key, void* value,
+ grpc_avl_node* left,
+ grpc_avl_node* right, void* user_data) {
+ /* rotate_right(..., rotate_left(left), right) */
+ grpc_avl_node* n =
+ new_node(vtable->copy_key(left->right->key, user_data),
+ vtable->copy_value(left->right->value, user_data),
+ new_node(vtable->copy_key(left->key, user_data),
+ vtable->copy_value(left->value, user_data),
+ ref_node(left->left), ref_node(left->right->left)),
+ new_node(key, value, ref_node(left->right->right), right));
+ unref_node(vtable, left, user_data);
+ return n;
+}
+
+static grpc_avl_node* rotate_right_left(const grpc_avl_vtable* vtable,
+ void* key, void* value,
+ grpc_avl_node* left,
+ grpc_avl_node* right, void* user_data) {
+ /* rotate_left(..., left, rotate_right(right)) */
+ grpc_avl_node* n =
+ new_node(vtable->copy_key(right->left->key, user_data),
+ vtable->copy_value(right->left->value, user_data),
+ new_node(key, value, left, ref_node(right->left->left)),
+ new_node(vtable->copy_key(right->key, user_data),
+ vtable->copy_value(right->value, user_data),
+ ref_node(right->left->right), ref_node(right->right)));
+ unref_node(vtable, right, user_data);
+ return n;
+}
+
+static grpc_avl_node* rebalance(const grpc_avl_vtable* vtable, void* key,
+ void* value, grpc_avl_node* left,
+ grpc_avl_node* right, void* user_data) {
+ switch (node_height(left) - node_height(right)) {
+ case 2:
+ if (node_height(left->left) - node_height(left->right) == -1) {
+ return assert_invariants(
+ rotate_left_right(vtable, key, value, left, right, user_data));
+ } else {
+ return assert_invariants(
+ rotate_right(vtable, key, value, left, right, user_data));
+ }
+ case -2:
+ if (node_height(right->left) - node_height(right->right) == 1) {
+ return assert_invariants(
+ rotate_right_left(vtable, key, value, left, right, user_data));
+ } else {
+ return assert_invariants(
+ rotate_left(vtable, key, value, left, right, user_data));
+ }
+ default:
+ return assert_invariants(new_node(key, value, left, right));
+ }
+}
+
+static grpc_avl_node* add_key(const grpc_avl_vtable* vtable,
+ grpc_avl_node* node, void* key, void* value,
+ void* user_data) {
+ long cmp;
+ if (node == nullptr) {
+ return new_node(key, value, nullptr, nullptr);
+ }
+ cmp = vtable->compare_keys(node->key, key, user_data);
+ if (cmp == 0) {
+ return new_node(key, value, ref_node(node->left), ref_node(node->right));
+ } else if (cmp > 0) {
+ return rebalance(vtable, vtable->copy_key(node->key, user_data),
+ vtable->copy_value(node->value, user_data),
+ add_key(vtable, node->left, key, value, user_data),
+ ref_node(node->right), user_data);
+ } else {
+ return rebalance(
+ vtable, vtable->copy_key(node->key, user_data),
+ vtable->copy_value(node->value, user_data), ref_node(node->left),
+ add_key(vtable, node->right, key, value, user_data), user_data);
+ }
+}
+
+grpc_avl grpc_avl_add(grpc_avl avl, void* key, void* value, void* user_data) {
+ grpc_avl_node* old_root = avl.root;
+ avl.root = add_key(avl.vtable, avl.root, key, value, user_data);
+ assert_invariants(avl.root);
+ unref_node(avl.vtable, old_root, user_data);
+ return avl;
+}
+
+static grpc_avl_node* in_order_head(grpc_avl_node* node) {
+ while (node->left != nullptr) {
+ node = node->left;
+ }
+ return node;
+}
+
+static grpc_avl_node* in_order_tail(grpc_avl_node* node) {
+ while (node->right != nullptr) {
+ node = node->right;
+ }
+ return node;
+}
+
+static grpc_avl_node* remove_key(const grpc_avl_vtable* vtable,
+ grpc_avl_node* node, void* key,
+ void* user_data) {
+ long cmp;
+ if (node == nullptr) {
+ return nullptr;
+ }
+ cmp = vtable->compare_keys(node->key, key, user_data);
+ if (cmp == 0) {
+ if (node->left == nullptr) {
+ return ref_node(node->right);
+ } else if (node->right == nullptr) {
+ return ref_node(node->left);
+ } else if (node->left->height < node->right->height) {
+ grpc_avl_node* h = in_order_head(node->right);
+ return rebalance(
+ vtable, vtable->copy_key(h->key, user_data),
+ vtable->copy_value(h->value, user_data), ref_node(node->left),
+ remove_key(vtable, node->right, h->key, user_data), user_data);
+ } else {
+ grpc_avl_node* h = in_order_tail(node->left);
+ return rebalance(vtable, vtable->copy_key(h->key, user_data),
+ vtable->copy_value(h->value, user_data),
+ remove_key(vtable, node->left, h->key, user_data),
+ ref_node(node->right), user_data);
+ }
+ } else if (cmp > 0) {
+ return rebalance(vtable, vtable->copy_key(node->key, user_data),
+ vtable->copy_value(node->value, user_data),
+ remove_key(vtable, node->left, key, user_data),
+ ref_node(node->right), user_data);
+ } else {
+ return rebalance(
+ vtable, vtable->copy_key(node->key, user_data),
+ vtable->copy_value(node->value, user_data), ref_node(node->left),
+ remove_key(vtable, node->right, key, user_data), user_data);
+ }
+}
+
+grpc_avl grpc_avl_remove(grpc_avl avl, void* key, void* user_data) {
+ grpc_avl_node* old_root = avl.root;
+ avl.root = remove_key(avl.vtable, avl.root, key, user_data);
+ assert_invariants(avl.root);
+ unref_node(avl.vtable, old_root, user_data);
+ return avl;
+}
+
grpc_avl grpc_avl_ref(grpc_avl avl, void* /*user_data*/) {
- ref_node(avl.root);
- return avl;
-}
-
-void grpc_avl_unref(grpc_avl avl, void* user_data) {
- unref_node(avl.vtable, avl.root, user_data);
-}
-
-int grpc_avl_is_empty(grpc_avl avl) { return avl.root == nullptr; }
+ ref_node(avl.root);
+ return avl;
+}
+
+void grpc_avl_unref(grpc_avl avl, void* user_data) {
+ unref_node(avl.vtable, avl.root, user_data);
+}
+
+int grpc_avl_is_empty(grpc_avl avl) { return avl.root == nullptr; }
diff --git a/contrib/libs/grpc/src/core/lib/avl/avl.h b/contrib/libs/grpc/src/core/lib/avl/avl.h
index 15a9d569471..14a6d33cecf 100644
--- a/contrib/libs/grpc/src/core/lib/avl/avl.h
+++ b/contrib/libs/grpc/src/core/lib/avl/avl.h
@@ -1,94 +1,94 @@
-/*
- *
- * 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_AVL_AVL_H
-#define GRPC_CORE_LIB_AVL_AVL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/sync.h>
-
-/** internal node of an AVL tree */
-typedef struct grpc_avl_node {
- gpr_refcount refs;
- void* key;
- void* value;
- struct grpc_avl_node* left;
- struct grpc_avl_node* right;
- long height;
-} grpc_avl_node;
-
-/** vtable for the AVL tree
- * The optional user_data is propagated from the top level grpc_avl_XXX API.
- * From the same API call, multiple vtable functions may be called multiple
- * times.
- */
-typedef struct grpc_avl_vtable {
- /** destroy a key */
- void (*destroy_key)(void* key, void* user_data);
- /** copy a key, returning new value */
- void* (*copy_key)(void* key, void* user_data);
- /** compare key1, key2; return <0 if key1 < key2,
- >0 if key1 > key2, 0 if key1 == key2 */
- long (*compare_keys)(void* key1, void* key2, void* user_data);
- /** destroy a value */
- void (*destroy_value)(void* value, void* user_data);
- /** copy a value */
- void* (*copy_value)(void* value, void* user_data);
-} grpc_avl_vtable;
-
-/** "pointer" to an AVL tree - this is a reference
- counted object - use grpc_avl_ref to add a reference,
- grpc_avl_unref when done with a reference */
-typedef struct grpc_avl {
- const grpc_avl_vtable* vtable;
- grpc_avl_node* root;
-} grpc_avl;
-
-/** Create an immutable AVL tree. */
-grpc_avl grpc_avl_create(const grpc_avl_vtable* vtable);
-/** Add a reference to an existing tree - returns
- the tree as a convenience. The optional user_data will be passed to vtable
- functions. */
-grpc_avl grpc_avl_ref(grpc_avl avl, void* user_data);
-/** Remove a reference to a tree - destroying it if there
- are no references left. The optional user_data will be passed to vtable
- functions. */
-void grpc_avl_unref(grpc_avl avl, void* user_data);
-/** Return a new tree with (key, value) added to avl.
- implicitly unrefs avl to allow easy chaining.
- if key exists in avl, the new tree's key entry updated
- (i.e. a duplicate is not created). The optional user_data will be passed to
- vtable functions. */
-grpc_avl grpc_avl_add(grpc_avl avl, void* key, void* value, void* user_data);
-/** Return a new tree with key deleted
- implicitly unrefs avl to allow easy chaining. The optional user_data will be
- passed to vtable functions. */
-grpc_avl grpc_avl_remove(grpc_avl avl, void* key, void* user_data);
-/** Lookup key, and return the associated value.
- Does not mutate avl.
- Returns NULL if key is not found. The optional user_data will be passed to
- vtable functions.*/
-void* grpc_avl_get(grpc_avl avl, void* key, void* user_data);
-/** Return 1 if avl contains key, 0 otherwise; if it has the key, sets *value to
- its value. The optional user_data will be passed to vtable functions. */
-int grpc_avl_maybe_get(grpc_avl avl, void* key, void** value, void* user_data);
-/** Return 1 if avl is empty, 0 otherwise */
-int grpc_avl_is_empty(grpc_avl avl);
-
-#endif /* GRPC_CORE_LIB_AVL_AVL_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_AVL_AVL_H
+#define GRPC_CORE_LIB_AVL_AVL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/sync.h>
+
+/** internal node of an AVL tree */
+typedef struct grpc_avl_node {
+ gpr_refcount refs;
+ void* key;
+ void* value;
+ struct grpc_avl_node* left;
+ struct grpc_avl_node* right;
+ long height;
+} grpc_avl_node;
+
+/** vtable for the AVL tree
+ * The optional user_data is propagated from the top level grpc_avl_XXX API.
+ * From the same API call, multiple vtable functions may be called multiple
+ * times.
+ */
+typedef struct grpc_avl_vtable {
+ /** destroy a key */
+ void (*destroy_key)(void* key, void* user_data);
+ /** copy a key, returning new value */
+ void* (*copy_key)(void* key, void* user_data);
+ /** compare key1, key2; return <0 if key1 < key2,
+ >0 if key1 > key2, 0 if key1 == key2 */
+ long (*compare_keys)(void* key1, void* key2, void* user_data);
+ /** destroy a value */
+ void (*destroy_value)(void* value, void* user_data);
+ /** copy a value */
+ void* (*copy_value)(void* value, void* user_data);
+} grpc_avl_vtable;
+
+/** "pointer" to an AVL tree - this is a reference
+ counted object - use grpc_avl_ref to add a reference,
+ grpc_avl_unref when done with a reference */
+typedef struct grpc_avl {
+ const grpc_avl_vtable* vtable;
+ grpc_avl_node* root;
+} grpc_avl;
+
+/** Create an immutable AVL tree. */
+grpc_avl grpc_avl_create(const grpc_avl_vtable* vtable);
+/** Add a reference to an existing tree - returns
+ the tree as a convenience. The optional user_data will be passed to vtable
+ functions. */
+grpc_avl grpc_avl_ref(grpc_avl avl, void* user_data);
+/** Remove a reference to a tree - destroying it if there
+ are no references left. The optional user_data will be passed to vtable
+ functions. */
+void grpc_avl_unref(grpc_avl avl, void* user_data);
+/** Return a new tree with (key, value) added to avl.
+ implicitly unrefs avl to allow easy chaining.
+ if key exists in avl, the new tree's key entry updated
+ (i.e. a duplicate is not created). The optional user_data will be passed to
+ vtable functions. */
+grpc_avl grpc_avl_add(grpc_avl avl, void* key, void* value, void* user_data);
+/** Return a new tree with key deleted
+ implicitly unrefs avl to allow easy chaining. The optional user_data will be
+ passed to vtable functions. */
+grpc_avl grpc_avl_remove(grpc_avl avl, void* key, void* user_data);
+/** Lookup key, and return the associated value.
+ Does not mutate avl.
+ Returns NULL if key is not found. The optional user_data will be passed to
+ vtable functions.*/
+void* grpc_avl_get(grpc_avl avl, void* key, void* user_data);
+/** Return 1 if avl contains key, 0 otherwise; if it has the key, sets *value to
+ its value. The optional user_data will be passed to vtable functions. */
+int grpc_avl_maybe_get(grpc_avl avl, void* key, void** value, void* user_data);
+/** Return 1 if avl is empty, 0 otherwise */
+int grpc_avl_is_empty(grpc_avl avl);
+
+#endif /* GRPC_CORE_LIB_AVL_AVL_H */
diff --git a/contrib/libs/grpc/src/core/lib/backoff/backoff.cc b/contrib/libs/grpc/src/core/lib/backoff/backoff.cc
index e536abde0a2..4d313666116 100644
--- a/contrib/libs/grpc/src/core/lib/backoff/backoff.cc
+++ b/contrib/libs/grpc/src/core/lib/backoff/backoff.cc
@@ -1,78 +1,78 @@
-/*
- *
- * 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/backoff/backoff.h"
-
-#include <algorithm>
-
-#include "src/core/lib/gpr/useful.h"
-
-namespace grpc_core {
-
-namespace {
-
-/* Generate a random number between 0 and 1. We roll our own RNG because seeding
- * rand() modifies a global variable we have no control over. */
-double generate_uniform_random_number(uint32_t* rng_state) {
- constexpr uint32_t two_raise_31 = uint32_t(1) << 31;
- *rng_state = (1103515245 * *rng_state + 12345) % two_raise_31;
- return *rng_state / static_cast<double>(two_raise_31);
-}
-
-double generate_uniform_random_number_between(uint32_t* rng_state, double a,
- double b) {
- if (a == b) return a;
- if (a > b) GPR_SWAP(double, a, b); // make sure a < b
- const double range = b - a;
- return a + generate_uniform_random_number(rng_state) * range;
-}
-
-} // namespace
-
-BackOff::BackOff(const Options& options)
- : options_(options),
- rng_state_(static_cast<uint32_t>(gpr_now(GPR_CLOCK_REALTIME).tv_nsec)) {
- Reset();
-}
-
-grpc_millis BackOff::NextAttemptTime() {
- if (initial_) {
- initial_ = false;
- return current_backoff_ + grpc_core::ExecCtx::Get()->Now();
- }
- current_backoff_ = static_cast<grpc_millis>(
- std::min(current_backoff_ * options_.multiplier(),
- static_cast<double>(options_.max_backoff())));
- const double jitter = generate_uniform_random_number_between(
- &rng_state_, -options_.jitter() * current_backoff_,
- options_.jitter() * current_backoff_);
- const grpc_millis next_timeout =
- static_cast<grpc_millis>(current_backoff_ + jitter);
- return next_timeout + grpc_core::ExecCtx::Get()->Now();
-}
-
-void BackOff::Reset() {
- current_backoff_ = options_.initial_backoff();
- initial_ = true;
-}
-
-void BackOff::SetRandomSeed(uint32_t seed) { rng_state_ = seed; }
-
-} // 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/backoff/backoff.h"
+
+#include <algorithm>
+
+#include "src/core/lib/gpr/useful.h"
+
+namespace grpc_core {
+
+namespace {
+
+/* Generate a random number between 0 and 1. We roll our own RNG because seeding
+ * rand() modifies a global variable we have no control over. */
+double generate_uniform_random_number(uint32_t* rng_state) {
+ constexpr uint32_t two_raise_31 = uint32_t(1) << 31;
+ *rng_state = (1103515245 * *rng_state + 12345) % two_raise_31;
+ return *rng_state / static_cast<double>(two_raise_31);
+}
+
+double generate_uniform_random_number_between(uint32_t* rng_state, double a,
+ double b) {
+ if (a == b) return a;
+ if (a > b) GPR_SWAP(double, a, b); // make sure a < b
+ const double range = b - a;
+ return a + generate_uniform_random_number(rng_state) * range;
+}
+
+} // namespace
+
+BackOff::BackOff(const Options& options)
+ : options_(options),
+ rng_state_(static_cast<uint32_t>(gpr_now(GPR_CLOCK_REALTIME).tv_nsec)) {
+ Reset();
+}
+
+grpc_millis BackOff::NextAttemptTime() {
+ if (initial_) {
+ initial_ = false;
+ return current_backoff_ + grpc_core::ExecCtx::Get()->Now();
+ }
+ current_backoff_ = static_cast<grpc_millis>(
+ std::min(current_backoff_ * options_.multiplier(),
+ static_cast<double>(options_.max_backoff())));
+ const double jitter = generate_uniform_random_number_between(
+ &rng_state_, -options_.jitter() * current_backoff_,
+ options_.jitter() * current_backoff_);
+ const grpc_millis next_timeout =
+ static_cast<grpc_millis>(current_backoff_ + jitter);
+ return next_timeout + grpc_core::ExecCtx::Get()->Now();
+}
+
+void BackOff::Reset() {
+ current_backoff_ = options_.initial_backoff();
+ initial_ = true;
+}
+
+void BackOff::SetRandomSeed(uint32_t seed) { rng_state_ = seed; }
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/backoff/backoff.h b/contrib/libs/grpc/src/core/lib/backoff/backoff.h
index e769d150ef4..f2a90447cf2 100644
--- a/contrib/libs/grpc/src/core/lib/backoff/backoff.h
+++ b/contrib/libs/grpc/src/core/lib/backoff/backoff.h
@@ -1,89 +1,89 @@
-/*
- *
- * 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_BACKOFF_BACKOFF_H
-#define GRPC_CORE_LIB_BACKOFF_BACKOFF_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/exec_ctx.h"
-
-namespace grpc_core {
-
-/// Implementation of the backoff mechanism described in
-/// doc/connection-backoff.md
-class BackOff {
- public:
- class Options;
-
- /// Initialize backoff machinery - does not need to be destroyed
- explicit BackOff(const Options& options);
-
- /// Returns the time at which the next attempt should start.
- grpc_millis NextAttemptTime();
-
- /// Reset the backoff, so the next value returned by NextAttemptTime()
- /// will be the time of the second attempt (rather than the Nth).
- void Reset();
-
- void SetRandomSeed(unsigned int seed);
-
- class Options {
- public:
- Options& set_initial_backoff(grpc_millis initial_backoff) {
- initial_backoff_ = initial_backoff;
- return *this;
- }
- Options& set_multiplier(double multiplier) {
- multiplier_ = multiplier;
- return *this;
- }
- Options& set_jitter(double jitter) {
- jitter_ = jitter;
- return *this;
- }
- Options& set_max_backoff(grpc_millis max_backoff) {
- max_backoff_ = max_backoff;
- return *this;
- }
- /// how long to wait after the first failure before retrying
- grpc_millis initial_backoff() const { return initial_backoff_; }
- /// factor with which to multiply backoff after a failed retry
- double multiplier() const { return multiplier_; }
- /// amount to randomize backoffs
- double jitter() const { return jitter_; }
- /// maximum time between retries
- grpc_millis max_backoff() const { return max_backoff_; }
-
- private:
- grpc_millis initial_backoff_;
- double multiplier_;
- double jitter_;
- grpc_millis max_backoff_;
- }; // class Options
-
- private:
- const Options options_;
- uint32_t rng_state_;
- bool initial_;
- /// current delay before retries
- grpc_millis current_backoff_;
-};
-
-} // namespace grpc_core
-#endif /* GRPC_CORE_LIB_BACKOFF_BACKOFF_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_BACKOFF_BACKOFF_H
+#define GRPC_CORE_LIB_BACKOFF_BACKOFF_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/exec_ctx.h"
+
+namespace grpc_core {
+
+/// Implementation of the backoff mechanism described in
+/// doc/connection-backoff.md
+class BackOff {
+ public:
+ class Options;
+
+ /// Initialize backoff machinery - does not need to be destroyed
+ explicit BackOff(const Options& options);
+
+ /// Returns the time at which the next attempt should start.
+ grpc_millis NextAttemptTime();
+
+ /// Reset the backoff, so the next value returned by NextAttemptTime()
+ /// will be the time of the second attempt (rather than the Nth).
+ void Reset();
+
+ void SetRandomSeed(unsigned int seed);
+
+ class Options {
+ public:
+ Options& set_initial_backoff(grpc_millis initial_backoff) {
+ initial_backoff_ = initial_backoff;
+ return *this;
+ }
+ Options& set_multiplier(double multiplier) {
+ multiplier_ = multiplier;
+ return *this;
+ }
+ Options& set_jitter(double jitter) {
+ jitter_ = jitter;
+ return *this;
+ }
+ Options& set_max_backoff(grpc_millis max_backoff) {
+ max_backoff_ = max_backoff;
+ return *this;
+ }
+ /// how long to wait after the first failure before retrying
+ grpc_millis initial_backoff() const { return initial_backoff_; }
+ /// factor with which to multiply backoff after a failed retry
+ double multiplier() const { return multiplier_; }
+ /// amount to randomize backoffs
+ double jitter() const { return jitter_; }
+ /// maximum time between retries
+ grpc_millis max_backoff() const { return max_backoff_; }
+
+ private:
+ grpc_millis initial_backoff_;
+ double multiplier_;
+ double jitter_;
+ grpc_millis max_backoff_;
+ }; // class Options
+
+ private:
+ const Options options_;
+ uint32_t rng_state_;
+ bool initial_;
+ /// current delay before retries
+ grpc_millis current_backoff_;
+};
+
+} // namespace grpc_core
+#endif /* GRPC_CORE_LIB_BACKOFF_BACKOFF_H */
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 cb3d61fc4dc..ba7962aadf3 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_args.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_args.cc
@@ -1,269 +1,269 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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 <vector>
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/grpc.h>
+#include <grpc/grpc.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>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
-
-static grpc_arg copy_arg(const grpc_arg* src) {
- grpc_arg dst;
- dst.type = src->type;
- dst.key = gpr_strdup(src->key);
- switch (dst.type) {
- case GRPC_ARG_STRING:
- dst.value.string = gpr_strdup(src->value.string);
- break;
- case GRPC_ARG_INTEGER:
- dst.value.integer = src->value.integer;
- break;
- case GRPC_ARG_POINTER:
- dst.value.pointer = src->value.pointer;
- dst.value.pointer.p =
- src->value.pointer.vtable->copy(src->value.pointer.p);
- break;
- }
- return dst;
-}
-
-grpc_channel_args* grpc_channel_args_copy_and_add(const grpc_channel_args* src,
- const grpc_arg* to_add,
- size_t num_to_add) {
- return grpc_channel_args_copy_and_add_and_remove(src, nullptr, 0, to_add,
- num_to_add);
-}
-
-grpc_channel_args* grpc_channel_args_copy_and_remove(
- const grpc_channel_args* src, const char** to_remove,
- size_t num_to_remove) {
- return grpc_channel_args_copy_and_add_and_remove(src, to_remove,
- num_to_remove, nullptr, 0);
-}
-
-static bool should_remove_arg(const grpc_arg* arg, const char** to_remove,
- size_t num_to_remove) {
- for (size_t i = 0; i < num_to_remove; ++i) {
- if (strcmp(arg->key, to_remove[i]) == 0) return true;
- }
- return false;
-}
-
-grpc_channel_args* grpc_channel_args_copy_and_add_and_remove(
- const grpc_channel_args* src, const char** to_remove, size_t num_to_remove,
- const grpc_arg* to_add, size_t num_to_add) {
- // Figure out how many args we'll be copying.
- size_t num_args_to_copy = 0;
- if (src != nullptr) {
- for (size_t i = 0; i < src->num_args; ++i) {
- if (!should_remove_arg(&src->args[i], to_remove, num_to_remove)) {
- ++num_args_to_copy;
- }
- }
- }
- // Create result.
- grpc_channel_args* dst =
- static_cast<grpc_channel_args*>(gpr_malloc(sizeof(grpc_channel_args)));
- dst->num_args = num_args_to_copy + num_to_add;
- if (dst->num_args == 0) {
- dst->args = nullptr;
- return dst;
- }
- dst->args =
- static_cast<grpc_arg*>(gpr_malloc(sizeof(grpc_arg) * dst->num_args));
- // Copy args from src that are not being removed.
- size_t dst_idx = 0;
- if (src != nullptr) {
- for (size_t i = 0; i < src->num_args; ++i) {
- if (!should_remove_arg(&src->args[i], to_remove, num_to_remove)) {
- dst->args[dst_idx++] = copy_arg(&src->args[i]);
- }
- }
- }
- // Add args from to_add.
- for (size_t i = 0; i < num_to_add; ++i) {
- dst->args[dst_idx++] = copy_arg(&to_add[i]);
- }
- GPR_ASSERT(dst_idx == dst->num_args);
- return dst;
-}
-
-grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src) {
- return grpc_channel_args_copy_and_add(src, nullptr, 0);
-}
-
-grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a,
- const grpc_channel_args* b) {
+#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/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
+
+static grpc_arg copy_arg(const grpc_arg* src) {
+ grpc_arg dst;
+ dst.type = src->type;
+ dst.key = gpr_strdup(src->key);
+ switch (dst.type) {
+ case GRPC_ARG_STRING:
+ dst.value.string = gpr_strdup(src->value.string);
+ break;
+ case GRPC_ARG_INTEGER:
+ dst.value.integer = src->value.integer;
+ break;
+ case GRPC_ARG_POINTER:
+ dst.value.pointer = src->value.pointer;
+ dst.value.pointer.p =
+ src->value.pointer.vtable->copy(src->value.pointer.p);
+ break;
+ }
+ return dst;
+}
+
+grpc_channel_args* grpc_channel_args_copy_and_add(const grpc_channel_args* src,
+ const grpc_arg* to_add,
+ size_t num_to_add) {
+ return grpc_channel_args_copy_and_add_and_remove(src, nullptr, 0, to_add,
+ num_to_add);
+}
+
+grpc_channel_args* grpc_channel_args_copy_and_remove(
+ const grpc_channel_args* src, const char** to_remove,
+ size_t num_to_remove) {
+ return grpc_channel_args_copy_and_add_and_remove(src, to_remove,
+ num_to_remove, nullptr, 0);
+}
+
+static bool should_remove_arg(const grpc_arg* arg, const char** to_remove,
+ size_t num_to_remove) {
+ for (size_t i = 0; i < num_to_remove; ++i) {
+ if (strcmp(arg->key, to_remove[i]) == 0) return true;
+ }
+ return false;
+}
+
+grpc_channel_args* grpc_channel_args_copy_and_add_and_remove(
+ const grpc_channel_args* src, const char** to_remove, size_t num_to_remove,
+ const grpc_arg* to_add, size_t num_to_add) {
+ // Figure out how many args we'll be copying.
+ size_t num_args_to_copy = 0;
+ if (src != nullptr) {
+ for (size_t i = 0; i < src->num_args; ++i) {
+ if (!should_remove_arg(&src->args[i], to_remove, num_to_remove)) {
+ ++num_args_to_copy;
+ }
+ }
+ }
+ // Create result.
+ grpc_channel_args* dst =
+ static_cast<grpc_channel_args*>(gpr_malloc(sizeof(grpc_channel_args)));
+ dst->num_args = num_args_to_copy + num_to_add;
+ if (dst->num_args == 0) {
+ dst->args = nullptr;
+ return dst;
+ }
+ dst->args =
+ static_cast<grpc_arg*>(gpr_malloc(sizeof(grpc_arg) * dst->num_args));
+ // Copy args from src that are not being removed.
+ size_t dst_idx = 0;
+ if (src != nullptr) {
+ for (size_t i = 0; i < src->num_args; ++i) {
+ if (!should_remove_arg(&src->args[i], to_remove, num_to_remove)) {
+ dst->args[dst_idx++] = copy_arg(&src->args[i]);
+ }
+ }
+ }
+ // Add args from to_add.
+ for (size_t i = 0; i < num_to_add; ++i) {
+ dst->args[dst_idx++] = copy_arg(&to_add[i]);
+ }
+ GPR_ASSERT(dst_idx == dst->num_args);
+ return dst;
+}
+
+grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src) {
+ return grpc_channel_args_copy_and_add(src, nullptr, 0);
+}
+
+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);
- const size_t max_out = (a->num_args + b->num_args);
- grpc_arg* uniques =
- static_cast<grpc_arg*>(gpr_malloc(sizeof(*uniques) * max_out));
- for (size_t i = 0; i < a->num_args; ++i) uniques[i] = a->args[i];
-
- size_t uniques_idx = a->num_args;
- for (size_t i = 0; i < b->num_args; ++i) {
- const char* b_key = b->args[i].key;
- if (grpc_channel_args_find(a, b_key) == nullptr) { // not found
- uniques[uniques_idx++] = b->args[i];
- }
- }
- grpc_channel_args* result =
- grpc_channel_args_copy_and_add(nullptr, uniques, uniques_idx);
- gpr_free(uniques);
- return result;
-}
-
-static int cmp_arg(const grpc_arg* a, const grpc_arg* b) {
- int c = GPR_ICMP(a->type, b->type);
- if (c != 0) return c;
- c = strcmp(a->key, b->key);
- if (c != 0) return c;
- switch (a->type) {
- case GRPC_ARG_STRING:
- return strcmp(a->value.string, b->value.string);
- case GRPC_ARG_INTEGER:
- return GPR_ICMP(a->value.integer, b->value.integer);
- case GRPC_ARG_POINTER:
- c = GPR_ICMP(a->value.pointer.p, b->value.pointer.p);
- if (c != 0) {
- c = GPR_ICMP(a->value.pointer.vtable, b->value.pointer.vtable);
- if (c == 0) {
- c = a->value.pointer.vtable->cmp(a->value.pointer.p,
- b->value.pointer.p);
- }
- }
- return c;
- }
- GPR_UNREACHABLE_CODE(return 0);
-}
-
-/* stabilizing comparison function: since channel_args ordering matters for
- * keys with the same name, we need to preserve that ordering */
-static int cmp_key_stable(const void* ap, const void* bp) {
- const grpc_arg* const* a = static_cast<const grpc_arg* const*>(ap);
- const grpc_arg* const* b = static_cast<const grpc_arg* const*>(bp);
- int c = strcmp((*a)->key, (*b)->key);
- if (c == 0) c = GPR_ICMP(*a, *b);
- return c;
-}
-
-grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* a) {
- grpc_arg** args =
- static_cast<grpc_arg**>(gpr_malloc(sizeof(grpc_arg*) * a->num_args));
- for (size_t i = 0; i < a->num_args; i++) {
- args[i] = &a->args[i];
- }
- if (a->num_args > 1)
- qsort(args, a->num_args, sizeof(grpc_arg*), cmp_key_stable);
-
- grpc_channel_args* b =
- static_cast<grpc_channel_args*>(gpr_malloc(sizeof(grpc_channel_args)));
- b->num_args = a->num_args;
- b->args = static_cast<grpc_arg*>(gpr_malloc(sizeof(grpc_arg) * b->num_args));
- for (size_t i = 0; i < a->num_args; i++) {
- b->args[i] = copy_arg(args[i]);
- }
-
- gpr_free(args);
- return b;
-}
-
-void grpc_channel_args_destroy(grpc_channel_args* a) {
- size_t i;
- if (!a) return;
- for (i = 0; i < a->num_args; i++) {
- switch (a->args[i].type) {
- case GRPC_ARG_STRING:
- gpr_free(a->args[i].value.string);
- break;
- case GRPC_ARG_INTEGER:
- break;
- case GRPC_ARG_POINTER:
- a->args[i].value.pointer.vtable->destroy(a->args[i].value.pointer.p);
- break;
- }
- gpr_free(a->args[i].key);
- }
- gpr_free(a->args);
- gpr_free(a);
-}
-
-int grpc_channel_args_compare(const grpc_channel_args* a,
- const grpc_channel_args* b) {
+ const size_t max_out = (a->num_args + b->num_args);
+ grpc_arg* uniques =
+ static_cast<grpc_arg*>(gpr_malloc(sizeof(*uniques) * max_out));
+ for (size_t i = 0; i < a->num_args; ++i) uniques[i] = a->args[i];
+
+ size_t uniques_idx = a->num_args;
+ for (size_t i = 0; i < b->num_args; ++i) {
+ const char* b_key = b->args[i].key;
+ if (grpc_channel_args_find(a, b_key) == nullptr) { // not found
+ uniques[uniques_idx++] = b->args[i];
+ }
+ }
+ grpc_channel_args* result =
+ grpc_channel_args_copy_and_add(nullptr, uniques, uniques_idx);
+ gpr_free(uniques);
+ return result;
+}
+
+static int cmp_arg(const grpc_arg* a, const grpc_arg* b) {
+ int c = GPR_ICMP(a->type, b->type);
+ if (c != 0) return c;
+ c = strcmp(a->key, b->key);
+ if (c != 0) return c;
+ switch (a->type) {
+ case GRPC_ARG_STRING:
+ return strcmp(a->value.string, b->value.string);
+ case GRPC_ARG_INTEGER:
+ return GPR_ICMP(a->value.integer, b->value.integer);
+ case GRPC_ARG_POINTER:
+ c = GPR_ICMP(a->value.pointer.p, b->value.pointer.p);
+ if (c != 0) {
+ c = GPR_ICMP(a->value.pointer.vtable, b->value.pointer.vtable);
+ if (c == 0) {
+ c = a->value.pointer.vtable->cmp(a->value.pointer.p,
+ b->value.pointer.p);
+ }
+ }
+ return c;
+ }
+ GPR_UNREACHABLE_CODE(return 0);
+}
+
+/* stabilizing comparison function: since channel_args ordering matters for
+ * keys with the same name, we need to preserve that ordering */
+static int cmp_key_stable(const void* ap, const void* bp) {
+ const grpc_arg* const* a = static_cast<const grpc_arg* const*>(ap);
+ const grpc_arg* const* b = static_cast<const grpc_arg* const*>(bp);
+ int c = strcmp((*a)->key, (*b)->key);
+ if (c == 0) c = GPR_ICMP(*a, *b);
+ return c;
+}
+
+grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* a) {
+ grpc_arg** args =
+ static_cast<grpc_arg**>(gpr_malloc(sizeof(grpc_arg*) * a->num_args));
+ for (size_t i = 0; i < a->num_args; i++) {
+ args[i] = &a->args[i];
+ }
+ if (a->num_args > 1)
+ qsort(args, a->num_args, sizeof(grpc_arg*), cmp_key_stable);
+
+ grpc_channel_args* b =
+ static_cast<grpc_channel_args*>(gpr_malloc(sizeof(grpc_channel_args)));
+ b->num_args = a->num_args;
+ b->args = static_cast<grpc_arg*>(gpr_malloc(sizeof(grpc_arg) * b->num_args));
+ for (size_t i = 0; i < a->num_args; i++) {
+ b->args[i] = copy_arg(args[i]);
+ }
+
+ gpr_free(args);
+ return b;
+}
+
+void grpc_channel_args_destroy(grpc_channel_args* a) {
+ size_t i;
+ if (!a) return;
+ for (i = 0; i < a->num_args; i++) {
+ switch (a->args[i].type) {
+ case GRPC_ARG_STRING:
+ gpr_free(a->args[i].value.string);
+ break;
+ case GRPC_ARG_INTEGER:
+ break;
+ case GRPC_ARG_POINTER:
+ a->args[i].value.pointer.vtable->destroy(a->args[i].value.pointer.p);
+ break;
+ }
+ gpr_free(a->args[i].key);
+ }
+ gpr_free(a->args);
+ gpr_free(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;
- 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++) {
- c = cmp_arg(&a->args[i], &b->args[i]);
- if (c != 0) return c;
- }
- return 0;
-}
-
-const grpc_arg* grpc_channel_args_find(const grpc_channel_args* args,
- const char* name) {
- if (args != nullptr) {
- for (size_t i = 0; i < args->num_args; ++i) {
- if (strcmp(args->args[i].key, name) == 0) {
- return &args->args[i];
- }
- }
- }
- return nullptr;
-}
-
-int grpc_channel_arg_get_integer(const grpc_arg* arg,
- const grpc_integer_options options) {
- if (arg == nullptr) return options.default_value;
- if (arg->type != GRPC_ARG_INTEGER) {
- gpr_log(GPR_ERROR, "%s ignored: it must be an integer", arg->key);
- return options.default_value;
- }
- if (arg->value.integer < options.min_value) {
- gpr_log(GPR_ERROR, "%s ignored: it must be >= %d", arg->key,
- options.min_value);
- return options.default_value;
- }
- if (arg->value.integer > options.max_value) {
- gpr_log(GPR_ERROR, "%s ignored: it must be <= %d", arg->key,
- options.max_value);
- return options.default_value;
- }
- return arg->value.integer;
-}
-
+ 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++) {
+ c = cmp_arg(&a->args[i], &b->args[i]);
+ if (c != 0) return c;
+ }
+ return 0;
+}
+
+const grpc_arg* grpc_channel_args_find(const grpc_channel_args* args,
+ const char* name) {
+ if (args != nullptr) {
+ for (size_t i = 0; i < args->num_args; ++i) {
+ if (strcmp(args->args[i].key, name) == 0) {
+ return &args->args[i];
+ }
+ }
+ }
+ return nullptr;
+}
+
+int grpc_channel_arg_get_integer(const grpc_arg* arg,
+ const grpc_integer_options options) {
+ if (arg == nullptr) return options.default_value;
+ if (arg->type != GRPC_ARG_INTEGER) {
+ gpr_log(GPR_ERROR, "%s ignored: it must be an integer", arg->key);
+ return options.default_value;
+ }
+ if (arg->value.integer < options.min_value) {
+ gpr_log(GPR_ERROR, "%s ignored: it must be >= %d", arg->key,
+ options.min_value);
+ return options.default_value;
+ }
+ if (arg->value.integer > options.max_value) {
+ gpr_log(GPR_ERROR, "%s ignored: it must be <= %d", arg->key,
+ options.max_value);
+ return options.default_value;
+ }
+ return arg->value.integer;
+}
+
int grpc_channel_args_find_integer(const grpc_channel_args* args,
const char* name,
const grpc_integer_options options) {
@@ -271,99 +271,99 @@ int grpc_channel_args_find_integer(const grpc_channel_args* args,
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) {
- gpr_log(GPR_ERROR, "%s ignored: it must be an string", arg->key);
- return nullptr;
- }
- return arg->value.string;
-}
-
+char* grpc_channel_arg_get_string(const grpc_arg* arg) {
+ if (arg == nullptr) return nullptr;
+ if (arg->type != GRPC_ARG_STRING) {
+ gpr_log(GPR_ERROR, "%s ignored: it must be an string", arg->key);
+ return nullptr;
+ }
+ 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);
}
-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) {
- gpr_log(GPR_ERROR, "%s ignored: it must be an integer", arg->key);
- return default_value;
- }
- switch (arg->value.integer) {
- case 0:
- return false;
- case 1:
- return true;
- default:
- gpr_log(GPR_ERROR, "%s treated as bool but set to %d (assuming true)",
- arg->key, arg->value.integer);
- return true;
- }
-}
-
+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) {
+ gpr_log(GPR_ERROR, "%s ignored: it must be an integer", arg->key);
+ return default_value;
+ }
+ switch (arg->value.integer) {
+ case 0:
+ return false;
+ case 1:
+ return true;
+ default:
+ gpr_log(GPR_ERROR, "%s treated as bool but set to %d (assuming true)",
+ arg->key, arg->value.integer);
+ return true;
+ }
+}
+
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);
-}
-
-grpc_arg grpc_channel_arg_string_create(char* name, char* value) {
- grpc_arg arg;
- arg.type = GRPC_ARG_STRING;
- arg.key = name;
- arg.value.string = value;
- return arg;
-}
-
-grpc_arg grpc_channel_arg_integer_create(char* name, int value) {
- grpc_arg arg;
- arg.type = GRPC_ARG_INTEGER;
- arg.key = name;
- arg.value.integer = value;
- return arg;
-}
-
-grpc_arg grpc_channel_arg_pointer_create(
- char* name, void* value, const grpc_arg_pointer_vtable* vtable) {
- grpc_arg arg;
- arg.type = GRPC_ARG_POINTER;
- arg.key = name;
- arg.value.pointer.p = value;
- arg.value.pointer.vtable = vtable;
- return arg;
-}
-
+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);
+}
+
+grpc_arg grpc_channel_arg_string_create(char* name, char* value) {
+ grpc_arg arg;
+ arg.type = GRPC_ARG_STRING;
+ arg.key = name;
+ arg.value.string = value;
+ return arg;
+}
+
+grpc_arg grpc_channel_arg_integer_create(char* name, int value) {
+ grpc_arg arg;
+ arg.type = GRPC_ARG_INTEGER;
+ arg.key = name;
+ arg.value.integer = value;
+ return arg;
+}
+
+grpc_arg grpc_channel_arg_pointer_create(
+ char* name, void* value, const grpc_arg_pointer_vtable* vtable) {
+ grpc_arg arg;
+ arg.type = GRPC_ARG_POINTER;
+ arg.key = name;
+ arg.value.pointer.p = value;
+ arg.value.pointer.vtable = vtable;
+ return arg;
+}
+
TString grpc_channel_args_string(const grpc_channel_args* args) {
if (args == nullptr) return "";
std::vector<TString> arg_strings;
- for (size_t i = 0; i < args->num_args; ++i) {
- const grpc_arg& arg = args->args[i];
+ for (size_t i = 0; i < args->num_args; ++i) {
+ const grpc_arg& arg = args->args[i];
TString arg_string;
- switch (arg.type) {
- case GRPC_ARG_INTEGER:
+ switch (arg.type) {
+ case GRPC_ARG_INTEGER:
arg_string = y_absl::StrFormat("%s=%d", arg.key, arg.value.integer);
- break;
- case GRPC_ARG_STRING:
+ break;
+ case GRPC_ARG_STRING:
arg_string = y_absl::StrFormat("%s=%s", arg.key, arg.value.string);
- break;
- case GRPC_ARG_POINTER:
+ break;
+ case GRPC_ARG_POINTER:
arg_string = y_absl::StrFormat("%s=%p", arg.key, arg.value.pointer.p);
- break;
- default:
+ break;
+ default:
arg_string = "arg with unknown type";
- }
+ }
arg_strings.push_back(arg_string);
- }
+ }
return y_absl::StrJoin(arg_strings, ", ");
-}
+}
namespace {
grpc_channel_args_client_channel_creation_mutator g_mutator = nullptr;
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 6b973aa94d3..08afc6d9f97 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_args.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_args.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CHANNEL_CHANNEL_ARGS_H
#define GRPC_CORE_LIB_CHANNEL_CHANNEL_ARGS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include <grpc/grpc.h>
@@ -30,78 +30,78 @@
// Channel args are intentionally immutable, to avoid the need for locking.
/** Copy the arguments in \a src into a new instance */
-grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src);
+grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src);
/** Copy the arguments in \a src into a new instance, stably sorting keys */
-grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* src);
+grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* src);
/** Copy the arguments in \a src and append \a to_add. If \a to_add is NULL, it
* is equivalent to calling \a grpc_channel_args_copy. */
-grpc_channel_args* grpc_channel_args_copy_and_add(const grpc_channel_args* src,
- const grpc_arg* to_add,
+grpc_channel_args* grpc_channel_args_copy_and_add(const grpc_channel_args* src,
+ const grpc_arg* to_add,
size_t num_to_add);
/** Copies the arguments in \a src except for those whose keys are in
\a to_remove. */
-grpc_channel_args* grpc_channel_args_copy_and_remove(
- const grpc_channel_args* src, const char** to_remove, size_t num_to_remove);
+grpc_channel_args* grpc_channel_args_copy_and_remove(
+ const grpc_channel_args* src, const char** to_remove, size_t num_to_remove);
/** Copies the arguments from \a src except for those whose keys are in
\a to_remove and appends the arguments in \a to_add. */
-grpc_channel_args* grpc_channel_args_copy_and_add_and_remove(
- const grpc_channel_args* src, const char** to_remove, size_t num_to_remove,
- const grpc_arg* to_add, size_t num_to_add);
+grpc_channel_args* grpc_channel_args_copy_and_add_and_remove(
+ const grpc_channel_args* src, const char** to_remove, size_t num_to_remove,
+ const grpc_arg* to_add, size_t num_to_add);
-/** Perform the union of \a a and \a b, prioritizing \a a entries */
-grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a,
- const grpc_channel_args* b);
+/** Perform the union of \a a and \a b, prioritizing \a a entries */
+grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a,
+ const grpc_channel_args* b);
/** Destroy arguments created by \a grpc_channel_args_copy */
-void grpc_channel_args_destroy(grpc_channel_args* a);
+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));
}
-int grpc_channel_args_compare(const grpc_channel_args* a,
- const grpc_channel_args* b);
+int grpc_channel_args_compare(const grpc_channel_args* a,
+ const grpc_channel_args* b);
/** Returns the value of argument \a name from \a args, or NULL if not found. */
-const grpc_arg* grpc_channel_args_find(const grpc_channel_args* args,
- const char* name);
-
-bool grpc_channel_args_want_minimal_stack(const grpc_channel_args* args);
+const grpc_arg* grpc_channel_args_find(const grpc_channel_args* args,
+ const char* name);
+bool grpc_channel_args_want_minimal_stack(const grpc_channel_args* args);
+
typedef struct grpc_integer_options {
int default_value; // Return this if value is outside of expected bounds.
int min_value;
int max_value;
} grpc_integer_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);
+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);
-/** 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);
+/** 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. */
-bool grpc_channel_arg_get_bool(const grpc_arg* arg, bool default_value);
+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) {
@@ -110,15 +110,15 @@ T* grpc_channel_args_find_pointer(const grpc_channel_args* args,
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);
-grpc_arg grpc_channel_arg_pointer_create(char* name, void* value,
- const grpc_arg_pointer_vtable* vtable);
-
-// Returns a string representing channel args in human-readable form.
+// 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);
+grpc_arg grpc_channel_arg_pointer_create(char* name, void* value,
+ const grpc_arg_pointer_vtable* vtable);
+
+// 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,
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 e9b348972f2..bb93b3c715b 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc
@@ -1,252 +1,252 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include "src/core/lib/channel/channel_stack.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 <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/gpr/alloc.h"
-
-#include <stdlib.h>
-#include <string.h>
-
-grpc_core::TraceFlag grpc_trace_channel(false, "channel");
-
-/* Memory layouts.
-
- Channel stack is laid out as: {
- grpc_channel_stack stk;
- padding to GPR_MAX_ALIGNMENT
- grpc_channel_element[stk.count];
- per-filter memory, aligned to GPR_MAX_ALIGNMENT
- }
-
- Call stack is laid out as: {
- grpc_call_stack stk;
- padding to GPR_MAX_ALIGNMENT
- grpc_call_element[stk.count];
- per-filter memory, aligned to GPR_MAX_ALIGNMENT
- } */
-
-size_t grpc_channel_stack_size(const grpc_channel_filter** filters,
- size_t filter_count) {
- /* always need the header, and size for the channel elements */
+
+#include <stdlib.h>
+#include <string.h>
+
+grpc_core::TraceFlag grpc_trace_channel(false, "channel");
+
+/* Memory layouts.
+
+ Channel stack is laid out as: {
+ grpc_channel_stack stk;
+ padding to GPR_MAX_ALIGNMENT
+ grpc_channel_element[stk.count];
+ per-filter memory, aligned to GPR_MAX_ALIGNMENT
+ }
+
+ Call stack is laid out as: {
+ grpc_call_stack stk;
+ padding to GPR_MAX_ALIGNMENT
+ grpc_call_element[stk.count];
+ per-filter memory, aligned to GPR_MAX_ALIGNMENT
+ } */
+
+size_t grpc_channel_stack_size(const grpc_channel_filter** filters,
+ size_t filter_count) {
+ /* always need the header, and size for the channel elements */
size_t size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count *
sizeof(grpc_channel_element));
- size_t i;
-
- GPR_ASSERT((GPR_MAX_ALIGNMENT & (GPR_MAX_ALIGNMENT - 1)) == 0 &&
- "GPR_MAX_ALIGNMENT must be a power of two");
-
- /* add the size for each filter */
- for (i = 0; i < filter_count; i++) {
+ size_t i;
+
+ GPR_ASSERT((GPR_MAX_ALIGNMENT & (GPR_MAX_ALIGNMENT - 1)) == 0 &&
+ "GPR_MAX_ALIGNMENT must be a power of two");
+
+ /* add the size for each filter */
+ for (i = 0; i < filter_count; i++) {
size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data);
- }
-
- return size;
-}
-
+ }
+
+ return size;
+}
+
#define CHANNEL_ELEMS_FROM_STACK(stk) \
((grpc_channel_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \
- sizeof(grpc_channel_stack))))
-
+ sizeof(grpc_channel_stack))))
+
#define CALL_ELEMS_FROM_STACK(stk) \
((grpc_call_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \
sizeof(grpc_call_stack))))
-
-grpc_channel_element* grpc_channel_stack_element(
- grpc_channel_stack* channel_stack, size_t index) {
- return CHANNEL_ELEMS_FROM_STACK(channel_stack) + index;
-}
-
-grpc_channel_element* grpc_channel_stack_last_element(
- grpc_channel_stack* channel_stack) {
- return grpc_channel_stack_element(channel_stack, channel_stack->count - 1);
-}
-
-grpc_call_element* grpc_call_stack_element(grpc_call_stack* call_stack,
- size_t index) {
- return CALL_ELEMS_FROM_STACK(call_stack) + index;
-}
-
-grpc_error* grpc_channel_stack_init(
- int initial_refs, grpc_iomgr_cb_func destroy, void* destroy_arg,
- const grpc_channel_filter** filters, size_t filter_count,
- const grpc_channel_args* channel_args, grpc_transport* optional_transport,
- const char* name, grpc_channel_stack* stack) {
- size_t call_size =
+
+grpc_channel_element* grpc_channel_stack_element(
+ grpc_channel_stack* channel_stack, size_t index) {
+ return CHANNEL_ELEMS_FROM_STACK(channel_stack) + index;
+}
+
+grpc_channel_element* grpc_channel_stack_last_element(
+ grpc_channel_stack* channel_stack) {
+ return grpc_channel_stack_element(channel_stack, channel_stack->count - 1);
+}
+
+grpc_call_element* grpc_call_stack_element(grpc_call_stack* call_stack,
+ size_t index) {
+ return CALL_ELEMS_FROM_STACK(call_stack) + index;
+}
+
+grpc_error* grpc_channel_stack_init(
+ int initial_refs, grpc_iomgr_cb_func destroy, void* destroy_arg,
+ const grpc_channel_filter** filters, size_t filter_count,
+ const grpc_channel_args* channel_args, grpc_transport* optional_transport,
+ const char* name, grpc_channel_stack* stack) {
+ size_t call_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * sizeof(grpc_call_element));
- grpc_channel_element* elems;
- grpc_channel_element_args args;
- char* user_data;
- size_t i;
-
- stack->count = filter_count;
- GRPC_STREAM_REF_INIT(&stack->refcount, initial_refs, destroy, destroy_arg,
- name);
- elems = CHANNEL_ELEMS_FROM_STACK(stack);
+ grpc_channel_element* elems;
+ grpc_channel_element_args args;
+ char* user_data;
+ size_t i;
+
+ stack->count = filter_count;
+ GRPC_STREAM_REF_INIT(&stack->refcount, initial_refs, destroy, destroy_arg,
+ name);
+ elems = CHANNEL_ELEMS_FROM_STACK(stack);
user_data = (reinterpret_cast<char*>(elems)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count *
sizeof(grpc_channel_element));
-
- /* init per-filter data */
- grpc_error* first_error = GRPC_ERROR_NONE;
- for (i = 0; i < filter_count; i++) {
- args.channel_stack = stack;
- args.channel_args = channel_args;
- args.optional_transport = optional_transport;
- args.is_first = i == 0;
- args.is_last = i == (filter_count - 1);
- elems[i].filter = filters[i];
- elems[i].channel_data = user_data;
- grpc_error* error = elems[i].filter->init_channel_elem(&elems[i], &args);
- if (error != GRPC_ERROR_NONE) {
- if (first_error == GRPC_ERROR_NONE) {
- first_error = error;
- } else {
- GRPC_ERROR_UNREF(error);
- }
- }
+
+ /* init per-filter data */
+ grpc_error* first_error = GRPC_ERROR_NONE;
+ for (i = 0; i < filter_count; i++) {
+ args.channel_stack = stack;
+ args.channel_args = channel_args;
+ args.optional_transport = optional_transport;
+ args.is_first = i == 0;
+ args.is_last = i == (filter_count - 1);
+ elems[i].filter = filters[i];
+ elems[i].channel_data = user_data;
+ grpc_error* error = elems[i].filter->init_channel_elem(&elems[i], &args);
+ if (error != GRPC_ERROR_NONE) {
+ if (first_error == GRPC_ERROR_NONE) {
+ first_error = error;
+ } else {
+ GRPC_ERROR_UNREF(error);
+ }
+ }
user_data +=
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data);
call_size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_call_data);
- }
-
- GPR_ASSERT(user_data > (char*)stack);
- GPR_ASSERT((uintptr_t)(user_data - (char*)stack) ==
- grpc_channel_stack_size(filters, filter_count));
-
- stack->call_stack_size = call_size;
- return first_error;
-}
-
-void grpc_channel_stack_destroy(grpc_channel_stack* stack) {
- grpc_channel_element* channel_elems = CHANNEL_ELEMS_FROM_STACK(stack);
- size_t count = stack->count;
- size_t i;
-
- /* destroy per-filter data */
- for (i = 0; i < count; i++) {
- channel_elems[i].filter->destroy_channel_elem(&channel_elems[i]);
- }
-}
-
-grpc_error* grpc_call_stack_init(grpc_channel_stack* channel_stack,
- int initial_refs, grpc_iomgr_cb_func destroy,
- void* destroy_arg,
- const grpc_call_element_args* elem_args) {
- grpc_channel_element* channel_elems = CHANNEL_ELEMS_FROM_STACK(channel_stack);
- size_t count = channel_stack->count;
- grpc_call_element* call_elems;
- char* user_data;
-
- elem_args->call_stack->count = count;
- GRPC_STREAM_REF_INIT(&elem_args->call_stack->refcount, initial_refs, destroy,
- destroy_arg, "CALL_STACK");
- call_elems = CALL_ELEMS_FROM_STACK(elem_args->call_stack);
- user_data = (reinterpret_cast<char*>(call_elems)) +
+ }
+
+ GPR_ASSERT(user_data > (char*)stack);
+ GPR_ASSERT((uintptr_t)(user_data - (char*)stack) ==
+ grpc_channel_stack_size(filters, filter_count));
+
+ stack->call_stack_size = call_size;
+ return first_error;
+}
+
+void grpc_channel_stack_destroy(grpc_channel_stack* stack) {
+ grpc_channel_element* channel_elems = CHANNEL_ELEMS_FROM_STACK(stack);
+ size_t count = stack->count;
+ size_t i;
+
+ /* destroy per-filter data */
+ for (i = 0; i < count; i++) {
+ channel_elems[i].filter->destroy_channel_elem(&channel_elems[i]);
+ }
+}
+
+grpc_error* grpc_call_stack_init(grpc_channel_stack* channel_stack,
+ int initial_refs, grpc_iomgr_cb_func destroy,
+ void* destroy_arg,
+ const grpc_call_element_args* elem_args) {
+ grpc_channel_element* channel_elems = CHANNEL_ELEMS_FROM_STACK(channel_stack);
+ size_t count = channel_stack->count;
+ grpc_call_element* call_elems;
+ char* user_data;
+
+ elem_args->call_stack->count = count;
+ GRPC_STREAM_REF_INIT(&elem_args->call_stack->refcount, initial_refs, destroy,
+ destroy_arg, "CALL_STACK");
+ call_elems = CALL_ELEMS_FROM_STACK(elem_args->call_stack);
+ user_data = (reinterpret_cast<char*>(call_elems)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(count * sizeof(grpc_call_element));
-
- /* init per-filter data */
- grpc_error* first_error = GRPC_ERROR_NONE;
+
+ /* init per-filter data */
+ grpc_error* first_error = GRPC_ERROR_NONE;
for (size_t i = 0; i < count; i++) {
- call_elems[i].filter = channel_elems[i].filter;
- call_elems[i].channel_data = channel_elems[i].channel_data;
- call_elems[i].call_data = user_data;
+ call_elems[i].filter = channel_elems[i].filter;
+ call_elems[i].channel_data = channel_elems[i].channel_data;
+ call_elems[i].call_data = user_data;
user_data +=
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(call_elems[i].filter->sizeof_call_data);
}
for (size_t i = 0; i < count; i++) {
- grpc_error* error =
- call_elems[i].filter->init_call_elem(&call_elems[i], elem_args);
- if (error != GRPC_ERROR_NONE) {
- if (first_error == GRPC_ERROR_NONE) {
- first_error = error;
- } else {
- GRPC_ERROR_UNREF(error);
- }
- }
- }
- return first_error;
-}
-
-void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
- grpc_polling_entity* pollent) {
- size_t count = call_stack->count;
- grpc_call_element* call_elems;
- size_t i;
-
- call_elems = CALL_ELEMS_FROM_STACK(call_stack);
-
- /* init per-filter data */
- for (i = 0; i < count; i++) {
- call_elems[i].filter->set_pollset_or_pollset_set(&call_elems[i], pollent);
- }
-}
-
-void grpc_call_stack_ignore_set_pollset_or_pollset_set(
+ grpc_error* error =
+ call_elems[i].filter->init_call_elem(&call_elems[i], elem_args);
+ if (error != GRPC_ERROR_NONE) {
+ if (first_error == GRPC_ERROR_NONE) {
+ first_error = error;
+ } else {
+ GRPC_ERROR_UNREF(error);
+ }
+ }
+ }
+ return first_error;
+}
+
+void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
+ grpc_polling_entity* pollent) {
+ size_t count = call_stack->count;
+ grpc_call_element* call_elems;
+ size_t i;
+
+ call_elems = CALL_ELEMS_FROM_STACK(call_stack);
+
+ /* init per-filter data */
+ for (i = 0; i < count; i++) {
+ call_elems[i].filter->set_pollset_or_pollset_set(&call_elems[i], pollent);
+ }
+}
+
+void grpc_call_stack_ignore_set_pollset_or_pollset_set(
grpc_call_element* /*elem*/, grpc_polling_entity* /*pollent*/) {}
-
-void grpc_call_stack_destroy(grpc_call_stack* stack,
- const grpc_call_final_info* final_info,
- grpc_closure* then_schedule_closure) {
- grpc_call_element* elems = CALL_ELEMS_FROM_STACK(stack);
- size_t count = stack->count;
- size_t i;
-
- /* destroy per-filter data */
- for (i = 0; i < count; i++) {
- elems[i].filter->destroy_call_elem(
- &elems[i], final_info,
- i == count - 1 ? then_schedule_closure : nullptr);
- }
-}
-
-void grpc_call_next_op(grpc_call_element* elem,
- grpc_transport_stream_op_batch* op) {
- grpc_call_element* next_elem = elem + 1;
- GRPC_CALL_LOG_OP(GPR_INFO, next_elem, op);
- next_elem->filter->start_transport_stream_op_batch(next_elem, op);
-}
-
-void grpc_channel_next_get_info(grpc_channel_element* elem,
- const grpc_channel_info* channel_info) {
- grpc_channel_element* next_elem = elem + 1;
- next_elem->filter->get_channel_info(next_elem, channel_info);
-}
-
-void grpc_channel_next_op(grpc_channel_element* elem, grpc_transport_op* op) {
- grpc_channel_element* next_elem = elem + 1;
- next_elem->filter->start_transport_op(next_elem, op);
-}
-
-grpc_channel_stack* grpc_channel_stack_from_top_element(
- grpc_channel_element* elem) {
- return reinterpret_cast<grpc_channel_stack*>(
- reinterpret_cast<char*>(elem) -
+
+void grpc_call_stack_destroy(grpc_call_stack* stack,
+ const grpc_call_final_info* final_info,
+ grpc_closure* then_schedule_closure) {
+ grpc_call_element* elems = CALL_ELEMS_FROM_STACK(stack);
+ size_t count = stack->count;
+ size_t i;
+
+ /* destroy per-filter data */
+ for (i = 0; i < count; i++) {
+ elems[i].filter->destroy_call_elem(
+ &elems[i], final_info,
+ i == count - 1 ? then_schedule_closure : nullptr);
+ }
+}
+
+void grpc_call_next_op(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* op) {
+ grpc_call_element* next_elem = elem + 1;
+ GRPC_CALL_LOG_OP(GPR_INFO, next_elem, op);
+ next_elem->filter->start_transport_stream_op_batch(next_elem, op);
+}
+
+void grpc_channel_next_get_info(grpc_channel_element* elem,
+ const grpc_channel_info* channel_info) {
+ grpc_channel_element* next_elem = elem + 1;
+ next_elem->filter->get_channel_info(next_elem, channel_info);
+}
+
+void grpc_channel_next_op(grpc_channel_element* elem, grpc_transport_op* op) {
+ grpc_channel_element* next_elem = elem + 1;
+ next_elem->filter->start_transport_op(next_elem, op);
+}
+
+grpc_channel_stack* grpc_channel_stack_from_top_element(
+ grpc_channel_element* elem) {
+ return reinterpret_cast<grpc_channel_stack*>(
+ reinterpret_cast<char*>(elem) -
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)));
-}
-
-grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem) {
- return reinterpret_cast<grpc_call_stack*>(
- reinterpret_cast<char*>(elem) -
+}
+
+grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem) {
+ return reinterpret_cast<grpc_call_stack*>(
+ reinterpret_cast<char*>(elem) -
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)));
-}
+}
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 e297df9488d..7dae4309bdf 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_stack.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -44,8 +44,8 @@
it can have an effect on the call status.
*/
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stddef.h>
#include <grpc/grpc.h>
@@ -55,7 +55,7 @@
#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/iomgr/call_combiner.h"
+#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/transport/transport.h"
@@ -66,20 +66,20 @@ typedef struct grpc_channel_stack grpc_channel_stack;
typedef struct grpc_call_stack grpc_call_stack;
struct grpc_channel_element_args {
- grpc_channel_stack* channel_stack;
- const grpc_channel_args* channel_args;
+ grpc_channel_stack* channel_stack;
+ const grpc_channel_args* channel_args;
/** Transport, iff it is known */
- grpc_transport* optional_transport;
+ grpc_transport* optional_transport;
int is_first;
int is_last;
};
struct grpc_call_element_args {
- grpc_call_stack* call_stack;
- const void* server_transport_data;
- grpc_call_context_element* context;
+ grpc_call_stack* call_stack;
+ const void* server_transport_data;
+ grpc_call_context_element* context;
const grpc_slice& path;
gpr_cycle_counter start_time;
- grpc_millis deadline;
+ grpc_millis deadline;
grpc_core::Arena* arena;
grpc_core::CallCombiner* call_combiner;
};
@@ -107,12 +107,12 @@ struct grpc_call_final_info {
struct grpc_channel_filter {
/* Called to eg. send/receive data on a call.
See grpc_call_next_op on how to call the next element in the stack */
- void (*start_transport_stream_op_batch)(grpc_call_element* elem,
- grpc_transport_stream_op_batch* op);
+ void (*start_transport_stream_op_batch)(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* op);
/* Called to handle channel level operations - e.g. new calls, or transport
closure.
See grpc_channel_next_op on how to call the next element in the stack */
- void (*start_transport_op)(grpc_channel_element* elem, grpc_transport_op* op);
+ void (*start_transport_op)(grpc_channel_element* elem, grpc_transport_op* op);
/* sizeof(per call data) */
size_t sizeof_call_data;
@@ -123,21 +123,21 @@ struct grpc_channel_filter {
server_transport_data is an opaque pointer. If it is NULL, this call is
on a client; if it is non-NULL, then it points to memory owned by the
transport and is on the server. Most filters want to ignore this
- argument.
- Implementations may assume that elem->call_data is all zeros. */
- grpc_error* (*init_call_elem)(grpc_call_element* elem,
- const grpc_call_element_args* args);
- void (*set_pollset_or_pollset_set)(grpc_call_element* elem,
- grpc_polling_entity* pollent);
+ argument.
+ Implementations may assume that elem->call_data is all zeros. */
+ grpc_error* (*init_call_elem)(grpc_call_element* elem,
+ const grpc_call_element_args* args);
+ void (*set_pollset_or_pollset_set)(grpc_call_element* elem,
+ grpc_polling_entity* pollent);
/* Destroy per call data.
The filter does not need to do any chaining.
The bottom filter of a stack will be passed a non-NULL pointer to
- \a then_schedule_closure that should be passed to GRPC_CLOSURE_SCHED when
- destruction is complete. \a final_info contains data about the completed
- call, mainly for reporting purposes. */
- void (*destroy_call_elem)(grpc_call_element* elem,
- const grpc_call_final_info* final_info,
- grpc_closure* then_schedule_closure);
+ \a then_schedule_closure that should be passed to GRPC_CLOSURE_SCHED when
+ destruction is complete. \a final_info contains data about the completed
+ call, mainly for reporting purposes. */
+ void (*destroy_call_elem)(grpc_call_element* elem,
+ const grpc_call_final_info* final_info,
+ grpc_closure* then_schedule_closure);
/* sizeof(per channel data) */
size_t sizeof_channel_data;
@@ -146,35 +146,35 @@ struct grpc_channel_filter {
is what needs initializing.
is_first, is_last designate this elements position in the stack, and are
useful for asserting correct configuration by upper layer code.
- The filter does not need to do any chaining.
+ The filter does not need to do any chaining.
Implementations may assume that elem->channel_data is all zeros. */
- grpc_error* (*init_channel_elem)(grpc_channel_element* elem,
- grpc_channel_element_args* args);
+ grpc_error* (*init_channel_elem)(grpc_channel_element* elem,
+ grpc_channel_element_args* args);
/* Destroy per channel data.
The filter does not need to do any chaining */
- void (*destroy_channel_elem)(grpc_channel_element* elem);
+ void (*destroy_channel_elem)(grpc_channel_element* elem);
/* Implement grpc_channel_get_info() */
- void (*get_channel_info)(grpc_channel_element* elem,
- const grpc_channel_info* channel_info);
+ void (*get_channel_info)(grpc_channel_element* elem,
+ const grpc_channel_info* channel_info);
/* The name of this filter */
- const char* name;
+ const char* name;
};
/* A channel_element tracks its filter and the filter requested memory within
a channel allocation */
struct grpc_channel_element {
- const grpc_channel_filter* filter;
- void* channel_data;
+ const grpc_channel_filter* filter;
+ void* channel_data;
};
/* A call_element tracks its filter, the filter requested memory within
a channel allocation, and the filter requested memory within a call
allocation */
struct grpc_call_element {
- const grpc_channel_filter* filter;
- void* channel_data;
- void* call_data;
+ const grpc_channel_filter* filter;
+ void* channel_data;
+ void* call_data;
};
/* A channel stack tracks a set of related filters for one channel, and
@@ -199,54 +199,54 @@ struct grpc_call_stack {
};
/* Get a channel element given a channel stack and its index */
-grpc_channel_element* grpc_channel_stack_element(grpc_channel_stack* stack,
+grpc_channel_element* grpc_channel_stack_element(grpc_channel_stack* stack,
size_t i);
/* Get the last channel element in a channel stack */
-grpc_channel_element* grpc_channel_stack_last_element(
- grpc_channel_stack* stack);
+grpc_channel_element* grpc_channel_stack_last_element(
+ grpc_channel_stack* stack);
/* Get a call stack element given a call stack and an index */
-grpc_call_element* grpc_call_stack_element(grpc_call_stack* stack, size_t i);
+grpc_call_element* grpc_call_stack_element(grpc_call_stack* stack, size_t i);
/* Determine memory required for a channel stack containing a set of filters */
-size_t grpc_channel_stack_size(const grpc_channel_filter** filters,
+size_t grpc_channel_stack_size(const grpc_channel_filter** filters,
size_t filter_count);
/* Initialize a channel stack given some filters */
-grpc_error* grpc_channel_stack_init(
- int initial_refs, grpc_iomgr_cb_func destroy, void* destroy_arg,
- const grpc_channel_filter** filters, size_t filter_count,
- const grpc_channel_args* args, grpc_transport* optional_transport,
- const char* name, grpc_channel_stack* stack);
+grpc_error* grpc_channel_stack_init(
+ int initial_refs, grpc_iomgr_cb_func destroy, void* destroy_arg,
+ const grpc_channel_filter** filters, size_t filter_count,
+ const grpc_channel_args* args, grpc_transport* optional_transport,
+ const char* name, grpc_channel_stack* stack);
/* Destroy a channel stack */
-void grpc_channel_stack_destroy(grpc_channel_stack* stack);
+void grpc_channel_stack_destroy(grpc_channel_stack* stack);
/* Initialize a call stack given a channel stack. transport_server_data is
expected to be NULL on a client, or an opaque transport owned pointer on the
server. */
-grpc_error* grpc_call_stack_init(grpc_channel_stack* channel_stack,
- int initial_refs, grpc_iomgr_cb_func destroy,
- void* destroy_arg,
- const grpc_call_element_args* elem_args);
+grpc_error* grpc_call_stack_init(grpc_channel_stack* channel_stack,
+ int initial_refs, grpc_iomgr_cb_func destroy,
+ void* destroy_arg,
+ const grpc_call_element_args* elem_args);
/* Set a pollset or a pollset_set for a call stack: must occur before the first
* op is started */
-void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
- grpc_polling_entity* pollent);
+void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
+ grpc_polling_entity* pollent);
-#ifndef NDEBUG
+#ifndef NDEBUG
#define GRPC_CALL_STACK_REF(call_stack, reason) \
grpc_stream_ref(&(call_stack)->refcount, reason)
-#define GRPC_CALL_STACK_UNREF(call_stack, reason) \
- grpc_stream_unref(&(call_stack)->refcount, reason)
+#define GRPC_CALL_STACK_UNREF(call_stack, reason) \
+ grpc_stream_unref(&(call_stack)->refcount, reason)
#define GRPC_CHANNEL_STACK_REF(channel_stack, reason) \
grpc_stream_ref(&(channel_stack)->refcount, reason)
-#define GRPC_CHANNEL_STACK_UNREF(channel_stack, reason) \
- grpc_stream_unref(&(channel_stack)->refcount, reason)
+#define GRPC_CHANNEL_STACK_UNREF(channel_stack, reason) \
+ 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);
-#define GRPC_CALL_STACK_UNREF(call_stack, reason) \
+#define GRPC_CALL_STACK_UNREF(call_stack, reason) \
do { \
grpc_stream_unref(&(call_stack)->refcount); \
(void)(reason); \
@@ -256,7 +256,7 @@ void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
grpc_stream_ref(&(channel_stack)->refcount); \
(void)(reason); \
} while (0);
-#define GRPC_CHANNEL_STACK_UNREF(channel_stack, reason) \
+#define GRPC_CHANNEL_STACK_UNREF(channel_stack, reason) \
do { \
grpc_stream_unref(&(channel_stack)->refcount); \
(void)(reason); \
@@ -264,35 +264,35 @@ void grpc_call_stack_set_pollset_or_pollset_set(grpc_call_stack* call_stack,
#endif
/* Destroy a call stack */
-void grpc_call_stack_destroy(grpc_call_stack* stack,
- const grpc_call_final_info* final_info,
- grpc_closure* then_schedule_closure);
+void grpc_call_stack_destroy(grpc_call_stack* stack,
+ const grpc_call_final_info* final_info,
+ grpc_closure* then_schedule_closure);
/* Ignore set pollset{_set} - used by filters if they don't care about pollsets
* at all. Does nothing. */
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);
/* Call the next operation in a call stack */
-void grpc_call_next_op(grpc_call_element* elem,
- grpc_transport_stream_op_batch* op);
+void grpc_call_next_op(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* op);
/* Call the next operation (depending on call directionality) in a channel
stack */
-void grpc_channel_next_op(grpc_channel_element* elem, grpc_transport_op* op);
+void grpc_channel_next_op(grpc_channel_element* elem, grpc_transport_op* op);
/* Pass through a request to get_channel_info() to the next child element */
-void grpc_channel_next_get_info(grpc_channel_element* elem,
- const grpc_channel_info* channel_info);
+void grpc_channel_next_get_info(grpc_channel_element* elem,
+ const grpc_channel_info* channel_info);
/* Given the top element of a channel stack, get the channel stack itself */
-grpc_channel_stack* grpc_channel_stack_from_top_element(
- grpc_channel_element* elem);
+grpc_channel_stack* grpc_channel_stack_from_top_element(
+ grpc_channel_element* elem);
/* Given the top element of a call stack, get the call stack itself */
-grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem);
+grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem);
-void grpc_call_log_op(const char* file, int line, gpr_log_severity severity,
- grpc_call_element* elem,
- grpc_transport_stream_op_batch* op);
+void grpc_call_log_op(const char* file, int line, gpr_log_severity severity,
+ grpc_call_element* elem,
+ grpc_transport_stream_op_batch* op);
-extern grpc_core::TraceFlag grpc_trace_channel;
+extern grpc_core::TraceFlag grpc_trace_channel;
#define GRPC_CALL_LOG_OP(sev, elem, op) \
do { \
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc
index 8b3008f2217..fb5ec195536 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc
@@ -1,179 +1,179 @@
-/*
- *
- * 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/channel/channel_stack_builder.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-typedef struct filter_node {
- struct filter_node* next;
- struct filter_node* prev;
- const grpc_channel_filter* filter;
- grpc_post_filter_create_init_func init;
- void* init_arg;
-} filter_node;
-
-struct grpc_channel_stack_builder {
- // sentinel nodes for filters that have been added
- filter_node begin;
- filter_node end;
- // various set/get-able parameters
- grpc_channel_args* args;
- grpc_transport* transport;
+/*
+ *
+ * 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/channel/channel_stack_builder.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+typedef struct filter_node {
+ struct filter_node* next;
+ struct filter_node* prev;
+ const grpc_channel_filter* filter;
+ grpc_post_filter_create_init_func init;
+ void* init_arg;
+} filter_node;
+
+struct grpc_channel_stack_builder {
+ // sentinel nodes for filters that have been added
+ filter_node begin;
+ filter_node end;
+ // various set/get-able parameters
+ grpc_channel_args* args;
+ grpc_transport* transport;
grpc_resource_user* resource_user;
- char* target;
- const char* name;
-};
-
-struct grpc_channel_stack_builder_iterator {
- grpc_channel_stack_builder* builder;
- filter_node* node;
-};
-
-grpc_channel_stack_builder* grpc_channel_stack_builder_create(void) {
- grpc_channel_stack_builder* b =
- static_cast<grpc_channel_stack_builder*>(gpr_zalloc(sizeof(*b)));
-
- b->begin.filter = nullptr;
- b->end.filter = nullptr;
- b->begin.next = &b->end;
- b->begin.prev = &b->end;
- b->end.next = &b->begin;
- b->end.prev = &b->begin;
-
- return b;
-}
-
-void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder* b,
- const char* target) {
- gpr_free(b->target);
- b->target = gpr_strdup(target);
-}
-
-const char* grpc_channel_stack_builder_get_target(
- grpc_channel_stack_builder* b) {
- return b->target;
-}
-
-static grpc_channel_stack_builder_iterator* create_iterator_at_filter_node(
- grpc_channel_stack_builder* builder, filter_node* node) {
- grpc_channel_stack_builder_iterator* it =
- static_cast<grpc_channel_stack_builder_iterator*>(
- gpr_malloc(sizeof(*it)));
- it->builder = builder;
- it->node = node;
- return it;
-}
-
-void grpc_channel_stack_builder_iterator_destroy(
- grpc_channel_stack_builder_iterator* it) {
- gpr_free(it);
-}
-
-grpc_channel_stack_builder_iterator*
-grpc_channel_stack_builder_create_iterator_at_first(
- grpc_channel_stack_builder* builder) {
- return create_iterator_at_filter_node(builder, &builder->begin);
-}
-
-grpc_channel_stack_builder_iterator*
-grpc_channel_stack_builder_create_iterator_at_last(
- grpc_channel_stack_builder* builder) {
- return create_iterator_at_filter_node(builder, &builder->end);
-}
-
-bool grpc_channel_stack_builder_iterator_is_end(
- grpc_channel_stack_builder_iterator* iterator) {
- return iterator->node == &iterator->builder->end;
-}
-
-const char* grpc_channel_stack_builder_iterator_filter_name(
- grpc_channel_stack_builder_iterator* iterator) {
- if (iterator->node->filter == nullptr) return nullptr;
- return iterator->node->filter->name;
-}
-
-bool grpc_channel_stack_builder_move_next(
- grpc_channel_stack_builder_iterator* iterator) {
- if (iterator->node == &iterator->builder->end) return false;
- iterator->node = iterator->node->next;
- return true;
-}
-
-bool grpc_channel_stack_builder_move_prev(
- grpc_channel_stack_builder_iterator* iterator) {
- if (iterator->node == &iterator->builder->begin) return false;
- iterator->node = iterator->node->prev;
- return true;
-}
-
-grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_iterator_find(
- grpc_channel_stack_builder* builder, const char* filter_name) {
- GPR_ASSERT(filter_name != nullptr);
- grpc_channel_stack_builder_iterator* it =
- grpc_channel_stack_builder_create_iterator_at_first(builder);
- while (grpc_channel_stack_builder_move_next(it)) {
- if (grpc_channel_stack_builder_iterator_is_end(it)) break;
- const char* filter_name_at_it =
- grpc_channel_stack_builder_iterator_filter_name(it);
- if (strcmp(filter_name, filter_name_at_it) == 0) break;
- }
- return it;
-}
-
-bool grpc_channel_stack_builder_move_prev(
- grpc_channel_stack_builder_iterator* iterator);
-
-void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder* builder,
- const char* name) {
- GPR_ASSERT(builder->name == nullptr);
- builder->name = name;
-}
-
-void grpc_channel_stack_builder_set_channel_arguments(
- grpc_channel_stack_builder* builder, const grpc_channel_args* args) {
- if (builder->args != nullptr) {
- grpc_channel_args_destroy(builder->args);
- }
- builder->args = grpc_channel_args_copy(args);
-}
-
+ char* target;
+ const char* name;
+};
+
+struct grpc_channel_stack_builder_iterator {
+ grpc_channel_stack_builder* builder;
+ filter_node* node;
+};
+
+grpc_channel_stack_builder* grpc_channel_stack_builder_create(void) {
+ grpc_channel_stack_builder* b =
+ static_cast<grpc_channel_stack_builder*>(gpr_zalloc(sizeof(*b)));
+
+ b->begin.filter = nullptr;
+ b->end.filter = nullptr;
+ b->begin.next = &b->end;
+ b->begin.prev = &b->end;
+ b->end.next = &b->begin;
+ b->end.prev = &b->begin;
+
+ return b;
+}
+
+void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder* b,
+ const char* target) {
+ gpr_free(b->target);
+ b->target = gpr_strdup(target);
+}
+
+const char* grpc_channel_stack_builder_get_target(
+ grpc_channel_stack_builder* b) {
+ return b->target;
+}
+
+static grpc_channel_stack_builder_iterator* create_iterator_at_filter_node(
+ grpc_channel_stack_builder* builder, filter_node* node) {
+ grpc_channel_stack_builder_iterator* it =
+ static_cast<grpc_channel_stack_builder_iterator*>(
+ gpr_malloc(sizeof(*it)));
+ it->builder = builder;
+ it->node = node;
+ return it;
+}
+
+void grpc_channel_stack_builder_iterator_destroy(
+ grpc_channel_stack_builder_iterator* it) {
+ gpr_free(it);
+}
+
+grpc_channel_stack_builder_iterator*
+grpc_channel_stack_builder_create_iterator_at_first(
+ grpc_channel_stack_builder* builder) {
+ return create_iterator_at_filter_node(builder, &builder->begin);
+}
+
+grpc_channel_stack_builder_iterator*
+grpc_channel_stack_builder_create_iterator_at_last(
+ grpc_channel_stack_builder* builder) {
+ return create_iterator_at_filter_node(builder, &builder->end);
+}
+
+bool grpc_channel_stack_builder_iterator_is_end(
+ grpc_channel_stack_builder_iterator* iterator) {
+ return iterator->node == &iterator->builder->end;
+}
+
+const char* grpc_channel_stack_builder_iterator_filter_name(
+ grpc_channel_stack_builder_iterator* iterator) {
+ if (iterator->node->filter == nullptr) return nullptr;
+ return iterator->node->filter->name;
+}
+
+bool grpc_channel_stack_builder_move_next(
+ grpc_channel_stack_builder_iterator* iterator) {
+ if (iterator->node == &iterator->builder->end) return false;
+ iterator->node = iterator->node->next;
+ return true;
+}
+
+bool grpc_channel_stack_builder_move_prev(
+ grpc_channel_stack_builder_iterator* iterator) {
+ if (iterator->node == &iterator->builder->begin) return false;
+ iterator->node = iterator->node->prev;
+ return true;
+}
+
+grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_iterator_find(
+ grpc_channel_stack_builder* builder, const char* filter_name) {
+ GPR_ASSERT(filter_name != nullptr);
+ grpc_channel_stack_builder_iterator* it =
+ grpc_channel_stack_builder_create_iterator_at_first(builder);
+ while (grpc_channel_stack_builder_move_next(it)) {
+ if (grpc_channel_stack_builder_iterator_is_end(it)) break;
+ const char* filter_name_at_it =
+ grpc_channel_stack_builder_iterator_filter_name(it);
+ if (strcmp(filter_name, filter_name_at_it) == 0) break;
+ }
+ return it;
+}
+
+bool grpc_channel_stack_builder_move_prev(
+ grpc_channel_stack_builder_iterator* iterator);
+
+void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder* builder,
+ const char* name) {
+ GPR_ASSERT(builder->name == nullptr);
+ builder->name = name;
+}
+
+void grpc_channel_stack_builder_set_channel_arguments(
+ grpc_channel_stack_builder* builder, const grpc_channel_args* args) {
+ if (builder->args != nullptr) {
+ grpc_channel_args_destroy(builder->args);
+ }
+ builder->args = grpc_channel_args_copy(args);
+}
+
const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments(
grpc_channel_stack_builder* builder) {
return builder->args;
}
-void grpc_channel_stack_builder_set_transport(
- grpc_channel_stack_builder* builder, grpc_transport* transport) {
- GPR_ASSERT(builder->transport == nullptr);
- builder->transport = transport;
-}
-
-grpc_transport* grpc_channel_stack_builder_get_transport(
- grpc_channel_stack_builder* builder) {
- return builder->transport;
-}
-
+void grpc_channel_stack_builder_set_transport(
+ grpc_channel_stack_builder* builder, grpc_transport* transport) {
+ GPR_ASSERT(builder->transport == nullptr);
+ builder->transport = transport;
+}
+
+grpc_transport* grpc_channel_stack_builder_get_transport(
+ grpc_channel_stack_builder* builder) {
+ return builder->transport;
+}
+
void grpc_channel_stack_builder_set_resource_user(
grpc_channel_stack_builder* builder, grpc_resource_user* resource_user) {
GPR_ASSERT(builder->resource_user == nullptr);
@@ -181,143 +181,143 @@ void grpc_channel_stack_builder_set_resource_user(
}
grpc_resource_user* grpc_channel_stack_builder_get_resource_user(
- grpc_channel_stack_builder* builder) {
+ grpc_channel_stack_builder* builder) {
return builder->resource_user;
-}
-
-bool grpc_channel_stack_builder_append_filter(
- grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
- grpc_post_filter_create_init_func post_init_func, void* user_data) {
- grpc_channel_stack_builder_iterator* it =
- grpc_channel_stack_builder_create_iterator_at_last(builder);
- bool ok = grpc_channel_stack_builder_add_filter_before(
- it, filter, post_init_func, user_data);
- grpc_channel_stack_builder_iterator_destroy(it);
- return ok;
-}
-
-bool grpc_channel_stack_builder_remove_filter(
- grpc_channel_stack_builder* builder, const char* filter_name) {
- grpc_channel_stack_builder_iterator* it =
- grpc_channel_stack_builder_iterator_find(builder, filter_name);
- if (grpc_channel_stack_builder_iterator_is_end(it)) {
- grpc_channel_stack_builder_iterator_destroy(it);
- return false;
- }
- it->node->prev->next = it->node->next;
- it->node->next->prev = it->node->prev;
- gpr_free(it->node);
- grpc_channel_stack_builder_iterator_destroy(it);
- return true;
-}
-
-bool grpc_channel_stack_builder_prepend_filter(
- grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
- grpc_post_filter_create_init_func post_init_func, void* user_data) {
- grpc_channel_stack_builder_iterator* it =
- grpc_channel_stack_builder_create_iterator_at_first(builder);
- bool ok = grpc_channel_stack_builder_add_filter_after(
- it, filter, post_init_func, user_data);
- grpc_channel_stack_builder_iterator_destroy(it);
- return ok;
-}
-
-static void add_after(filter_node* before, const grpc_channel_filter* filter,
- grpc_post_filter_create_init_func post_init_func,
- void* user_data) {
- filter_node* new_node =
- static_cast<filter_node*>(gpr_malloc(sizeof(*new_node)));
- new_node->next = before->next;
- new_node->prev = before;
- new_node->next->prev = new_node->prev->next = new_node;
- new_node->filter = filter;
- new_node->init = post_init_func;
- new_node->init_arg = user_data;
-}
-
-bool grpc_channel_stack_builder_add_filter_before(
- grpc_channel_stack_builder_iterator* iterator,
- const grpc_channel_filter* filter,
- grpc_post_filter_create_init_func post_init_func, void* user_data) {
- if (iterator->node == &iterator->builder->begin) return false;
- add_after(iterator->node->prev, filter, post_init_func, user_data);
- return true;
-}
-
-bool grpc_channel_stack_builder_add_filter_after(
- grpc_channel_stack_builder_iterator* iterator,
- const grpc_channel_filter* filter,
- grpc_post_filter_create_init_func post_init_func, void* user_data) {
- if (iterator->node == &iterator->builder->end) return false;
- add_after(iterator->node, filter, post_init_func, user_data);
- return true;
-}
-
-void grpc_channel_stack_builder_destroy(grpc_channel_stack_builder* builder) {
- filter_node* p = builder->begin.next;
- while (p != &builder->end) {
- filter_node* next = p->next;
- gpr_free(p);
- p = next;
- }
- if (builder->args != nullptr) {
- grpc_channel_args_destroy(builder->args);
- }
- gpr_free(builder->target);
- gpr_free(builder);
-}
-
-grpc_error* grpc_channel_stack_builder_finish(
- grpc_channel_stack_builder* builder, size_t prefix_bytes, int initial_refs,
- grpc_iomgr_cb_func destroy, void* destroy_arg, void** result) {
- // count the number of filters
- size_t num_filters = 0;
- for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) {
- num_filters++;
- }
-
- // create an array of filters
- const grpc_channel_filter** filters =
- static_cast<const grpc_channel_filter**>(
- gpr_malloc(sizeof(*filters) * num_filters));
- size_t i = 0;
- for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) {
- filters[i++] = p->filter;
- }
-
- // calculate the size of the channel stack
- size_t channel_stack_size = grpc_channel_stack_size(filters, num_filters);
-
- // allocate memory, with prefix_bytes followed by channel_stack_size
- *result = gpr_zalloc(prefix_bytes + channel_stack_size);
- // fetch a pointer to the channel stack
- grpc_channel_stack* channel_stack = reinterpret_cast<grpc_channel_stack*>(
- static_cast<char*>(*result) + prefix_bytes);
- // and initialize it
- grpc_error* error = grpc_channel_stack_init(
- initial_refs, destroy, destroy_arg == nullptr ? *result : destroy_arg,
- filters, num_filters, builder->args, builder->transport, builder->name,
- channel_stack);
-
- if (error != GRPC_ERROR_NONE) {
- grpc_channel_stack_destroy(channel_stack);
- gpr_free(*result);
- *result = nullptr;
- } else {
- // run post-initialization functions
- i = 0;
- for (filter_node* p = builder->begin.next; p != &builder->end;
- p = p->next) {
- if (p->init != nullptr) {
- p->init(channel_stack, grpc_channel_stack_element(channel_stack, i),
- p->init_arg);
- }
- i++;
- }
- }
-
- grpc_channel_stack_builder_destroy(builder);
- gpr_free(const_cast<grpc_channel_filter**>(filters));
-
- return error;
-}
+}
+
+bool grpc_channel_stack_builder_append_filter(
+ grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
+ grpc_post_filter_create_init_func post_init_func, void* user_data) {
+ grpc_channel_stack_builder_iterator* it =
+ grpc_channel_stack_builder_create_iterator_at_last(builder);
+ bool ok = grpc_channel_stack_builder_add_filter_before(
+ it, filter, post_init_func, user_data);
+ grpc_channel_stack_builder_iterator_destroy(it);
+ return ok;
+}
+
+bool grpc_channel_stack_builder_remove_filter(
+ grpc_channel_stack_builder* builder, const char* filter_name) {
+ grpc_channel_stack_builder_iterator* it =
+ grpc_channel_stack_builder_iterator_find(builder, filter_name);
+ if (grpc_channel_stack_builder_iterator_is_end(it)) {
+ grpc_channel_stack_builder_iterator_destroy(it);
+ return false;
+ }
+ it->node->prev->next = it->node->next;
+ it->node->next->prev = it->node->prev;
+ gpr_free(it->node);
+ grpc_channel_stack_builder_iterator_destroy(it);
+ return true;
+}
+
+bool grpc_channel_stack_builder_prepend_filter(
+ grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
+ grpc_post_filter_create_init_func post_init_func, void* user_data) {
+ grpc_channel_stack_builder_iterator* it =
+ grpc_channel_stack_builder_create_iterator_at_first(builder);
+ bool ok = grpc_channel_stack_builder_add_filter_after(
+ it, filter, post_init_func, user_data);
+ grpc_channel_stack_builder_iterator_destroy(it);
+ return ok;
+}
+
+static void add_after(filter_node* before, const grpc_channel_filter* filter,
+ grpc_post_filter_create_init_func post_init_func,
+ void* user_data) {
+ filter_node* new_node =
+ static_cast<filter_node*>(gpr_malloc(sizeof(*new_node)));
+ new_node->next = before->next;
+ new_node->prev = before;
+ new_node->next->prev = new_node->prev->next = new_node;
+ new_node->filter = filter;
+ new_node->init = post_init_func;
+ new_node->init_arg = user_data;
+}
+
+bool grpc_channel_stack_builder_add_filter_before(
+ grpc_channel_stack_builder_iterator* iterator,
+ const grpc_channel_filter* filter,
+ grpc_post_filter_create_init_func post_init_func, void* user_data) {
+ if (iterator->node == &iterator->builder->begin) return false;
+ add_after(iterator->node->prev, filter, post_init_func, user_data);
+ return true;
+}
+
+bool grpc_channel_stack_builder_add_filter_after(
+ grpc_channel_stack_builder_iterator* iterator,
+ const grpc_channel_filter* filter,
+ grpc_post_filter_create_init_func post_init_func, void* user_data) {
+ if (iterator->node == &iterator->builder->end) return false;
+ add_after(iterator->node, filter, post_init_func, user_data);
+ return true;
+}
+
+void grpc_channel_stack_builder_destroy(grpc_channel_stack_builder* builder) {
+ filter_node* p = builder->begin.next;
+ while (p != &builder->end) {
+ filter_node* next = p->next;
+ gpr_free(p);
+ p = next;
+ }
+ if (builder->args != nullptr) {
+ grpc_channel_args_destroy(builder->args);
+ }
+ gpr_free(builder->target);
+ gpr_free(builder);
+}
+
+grpc_error* grpc_channel_stack_builder_finish(
+ grpc_channel_stack_builder* builder, size_t prefix_bytes, int initial_refs,
+ grpc_iomgr_cb_func destroy, void* destroy_arg, void** result) {
+ // count the number of filters
+ size_t num_filters = 0;
+ for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) {
+ num_filters++;
+ }
+
+ // create an array of filters
+ const grpc_channel_filter** filters =
+ static_cast<const grpc_channel_filter**>(
+ gpr_malloc(sizeof(*filters) * num_filters));
+ size_t i = 0;
+ for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) {
+ filters[i++] = p->filter;
+ }
+
+ // calculate the size of the channel stack
+ size_t channel_stack_size = grpc_channel_stack_size(filters, num_filters);
+
+ // allocate memory, with prefix_bytes followed by channel_stack_size
+ *result = gpr_zalloc(prefix_bytes + channel_stack_size);
+ // fetch a pointer to the channel stack
+ grpc_channel_stack* channel_stack = reinterpret_cast<grpc_channel_stack*>(
+ static_cast<char*>(*result) + prefix_bytes);
+ // and initialize it
+ grpc_error* error = grpc_channel_stack_init(
+ initial_refs, destroy, destroy_arg == nullptr ? *result : destroy_arg,
+ filters, num_filters, builder->args, builder->transport, builder->name,
+ channel_stack);
+
+ if (error != GRPC_ERROR_NONE) {
+ grpc_channel_stack_destroy(channel_stack);
+ gpr_free(*result);
+ *result = nullptr;
+ } else {
+ // run post-initialization functions
+ i = 0;
+ for (filter_node* p = builder->begin.next; p != &builder->end;
+ p = p->next) {
+ if (p->init != nullptr) {
+ p->init(channel_stack, grpc_channel_stack_element(channel_stack, i),
+ p->init_arg);
+ }
+ i++;
+ }
+ }
+
+ grpc_channel_stack_builder_destroy(builder);
+ gpr_free(const_cast<grpc_channel_filter**>(filters));
+
+ return error;
+}
diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h
index 89c30e0c5ea..9734e3df26b 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CHANNEL_CHANNEL_STACK_BUILDER_H
#define GRPC_CORE_LIB_CHANNEL_CHANNEL_STACK_BUILDER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdbool.h>
#include "src/core/lib/channel/channel_args.h"
@@ -33,26 +33,26 @@ typedef struct grpc_channel_stack_builder_iterator
grpc_channel_stack_builder_iterator;
/// Create a new channel stack builder
-grpc_channel_stack_builder* grpc_channel_stack_builder_create(void);
+grpc_channel_stack_builder* grpc_channel_stack_builder_create(void);
/// Assign a name to the channel stack: \a name must be statically allocated
-void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder* builder,
- const char* name);
+void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder* builder,
+ const char* name);
/// Set the target uri
-void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder* b,
- const char* target);
+void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder* b,
+ const char* target);
-const char* grpc_channel_stack_builder_get_target(
- grpc_channel_stack_builder* b);
+const char* grpc_channel_stack_builder_get_target(
+ grpc_channel_stack_builder* b);
/// Attach \a transport to the builder (does not take ownership)
void grpc_channel_stack_builder_set_transport(
- grpc_channel_stack_builder* builder, grpc_transport* transport);
+ grpc_channel_stack_builder* builder, grpc_transport* transport);
/// Fetch attached transport
-grpc_transport* grpc_channel_stack_builder_get_transport(
- grpc_channel_stack_builder* builder);
+grpc_transport* grpc_channel_stack_builder_get_transport(
+ grpc_channel_stack_builder* builder);
/// Attach \a resource_user to the builder (does not take ownership)
void grpc_channel_stack_builder_set_resource_user(
@@ -64,103 +64,103 @@ grpc_resource_user* grpc_channel_stack_builder_get_resource_user(
/// Set channel arguments: copies args
void grpc_channel_stack_builder_set_channel_arguments(
- grpc_channel_stack_builder* builder, const grpc_channel_args* args);
+ grpc_channel_stack_builder* builder, const grpc_channel_args* args);
/// Return a borrowed pointer to the channel arguments
-const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments(
- grpc_channel_stack_builder* builder);
+const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments(
+ grpc_channel_stack_builder* builder);
/// Begin iterating over already defined filters in the builder at the beginning
-grpc_channel_stack_builder_iterator*
+grpc_channel_stack_builder_iterator*
grpc_channel_stack_builder_create_iterator_at_first(
- grpc_channel_stack_builder* builder);
+ grpc_channel_stack_builder* builder);
/// Begin iterating over already defined filters in the builder at the end
-grpc_channel_stack_builder_iterator*
+grpc_channel_stack_builder_iterator*
grpc_channel_stack_builder_create_iterator_at_last(
- grpc_channel_stack_builder* builder);
+ grpc_channel_stack_builder* builder);
/// Is an iterator at the first element?
bool grpc_channel_stack_builder_iterator_is_first(
- grpc_channel_stack_builder_iterator* iterator);
+ grpc_channel_stack_builder_iterator* iterator);
/// Is an iterator at the end?
bool grpc_channel_stack_builder_iterator_is_end(
- grpc_channel_stack_builder_iterator* iterator);
-
-/// What is the name of the filter at this iterator position?
-const char* grpc_channel_stack_builder_iterator_filter_name(
- grpc_channel_stack_builder_iterator* iterator);
+ grpc_channel_stack_builder_iterator* iterator);
+/// What is the name of the filter at this iterator position?
+const char* grpc_channel_stack_builder_iterator_filter_name(
+ grpc_channel_stack_builder_iterator* iterator);
+
/// Move an iterator to the next item
bool grpc_channel_stack_builder_move_next(
- grpc_channel_stack_builder_iterator* iterator);
+ grpc_channel_stack_builder_iterator* iterator);
/// Move an iterator to the previous item
bool grpc_channel_stack_builder_move_prev(
- grpc_channel_stack_builder_iterator* iterator);
-
-/// Return an iterator at \a filter_name, or at the end of the list if not
-/// found.
-grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_iterator_find(
- grpc_channel_stack_builder* builder, const char* filter_name);
+ grpc_channel_stack_builder_iterator* iterator);
+/// Return an iterator at \a filter_name, or at the end of the list if not
+/// found.
+grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_iterator_find(
+ grpc_channel_stack_builder* builder, const char* filter_name);
+
typedef void (*grpc_post_filter_create_init_func)(
- grpc_channel_stack* channel_stack, grpc_channel_element* elem, void* arg);
+ grpc_channel_stack* channel_stack, grpc_channel_element* elem, void* arg);
/// Add \a filter to the stack, after \a iterator.
/// Call \a post_init_func(..., \a user_data) once the channel stack is
/// created.
bool grpc_channel_stack_builder_add_filter_after(
- grpc_channel_stack_builder_iterator* iterator,
- const grpc_channel_filter* filter,
+ grpc_channel_stack_builder_iterator* iterator,
+ const grpc_channel_filter* filter,
grpc_post_filter_create_init_func post_init_func,
- void* user_data) GRPC_MUST_USE_RESULT;
+ void* user_data) GRPC_MUST_USE_RESULT;
/// Add \a filter to the stack, before \a iterator.
/// Call \a post_init_func(..., \a user_data) once the channel stack is
/// created.
bool grpc_channel_stack_builder_add_filter_before(
- grpc_channel_stack_builder_iterator* iterator,
- const grpc_channel_filter* filter,
+ grpc_channel_stack_builder_iterator* iterator,
+ const grpc_channel_filter* filter,
grpc_post_filter_create_init_func post_init_func,
- void* user_data) GRPC_MUST_USE_RESULT;
+ void* user_data) GRPC_MUST_USE_RESULT;
/// Add \a filter to the beginning of the filter list.
/// Call \a post_init_func(..., \a user_data) once the channel stack is
/// created.
bool grpc_channel_stack_builder_prepend_filter(
- grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
+ grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
grpc_post_filter_create_init_func post_init_func,
- void* user_data) GRPC_MUST_USE_RESULT;
+ void* user_data) GRPC_MUST_USE_RESULT;
/// Add \a filter to the end of the filter list.
/// Call \a post_init_func(..., \a user_data) once the channel stack is
/// created.
bool grpc_channel_stack_builder_append_filter(
- grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
+ grpc_channel_stack_builder* builder, const grpc_channel_filter* filter,
grpc_post_filter_create_init_func post_init_func,
- void* user_data) GRPC_MUST_USE_RESULT;
-
-/// Remove any filter whose name is \a filter_name from \a builder. Returns true
-/// if \a filter_name was not found.
-bool grpc_channel_stack_builder_remove_filter(
- grpc_channel_stack_builder* builder, const char* filter_name);
+ void* user_data) GRPC_MUST_USE_RESULT;
+/// Remove any filter whose name is \a filter_name from \a builder. Returns true
+/// if \a filter_name was not found.
+bool grpc_channel_stack_builder_remove_filter(
+ grpc_channel_stack_builder* builder, const char* filter_name);
+
/// Terminate iteration and destroy \a iterator
void grpc_channel_stack_builder_iterator_destroy(
- grpc_channel_stack_builder_iterator* iterator);
+ grpc_channel_stack_builder_iterator* iterator);
/// Destroy the builder, return the freshly minted channel stack in \a result.
/// Allocates \a prefix_bytes bytes before the channel stack
/// Returns the base pointer of the allocated block
/// \a initial_refs, \a destroy, \a destroy_arg are as per
/// grpc_channel_stack_init
-grpc_error* grpc_channel_stack_builder_finish(
- grpc_channel_stack_builder* builder, size_t prefix_bytes, int initial_refs,
- grpc_iomgr_cb_func destroy, void* destroy_arg, void** result);
+grpc_error* grpc_channel_stack_builder_finish(
+ grpc_channel_stack_builder* builder, size_t prefix_bytes, int initial_refs,
+ grpc_iomgr_cb_func destroy, void* destroy_arg, void** result);
/// Destroy the builder without creating a channel stack
-void grpc_channel_stack_builder_destroy(grpc_channel_stack_builder* builder);
+void grpc_channel_stack_builder_destroy(grpc_channel_stack_builder* builder);
#endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_STACK_BUILDER_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 dbc33af2d4f..a8118c63795 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc
@@ -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.
- *
- */
-
-#include <grpc/impl/codegen/port_platform.h>
-
-#include "src/core/lib/channel/channel_trace.h"
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#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/memory.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/channel.h"
-#include "src/core/lib/transport/connectivity_state.h"
-#include "src/core/lib/transport/error_utils.h"
-
-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/impl/codegen/port_platform.h>
+
+#include "src/core/lib/channel/channel_trace.h"
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#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/memory.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/error_utils.h"
+
+namespace grpc_core {
namespace channelz {
-
+
ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_entity)
- : severity_(severity),
- data_(data),
- timestamp_(grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(),
- GPR_CLOCK_REALTIME)),
- next_(nullptr),
+ : severity_(severity),
+ data_(data),
+ timestamp_(grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(),
+ GPR_CLOCK_REALTIME)),
+ next_(nullptr),
referenced_entity_(std::move(referenced_entity)),
memory_usage_(sizeof(TraceEvent) + grpc_slice_memory_usage(data)) {}
-
+
ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data)
- : severity_(severity),
- data_(data),
- timestamp_(grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(),
- GPR_CLOCK_REALTIME)),
+ : severity_(severity),
+ data_(data),
+ timestamp_(grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(),
+ GPR_CLOCK_REALTIME)),
next_(nullptr),
memory_usage_(sizeof(TraceEvent) + grpc_slice_memory_usage(data)) {}
-
-ChannelTrace::TraceEvent::~TraceEvent() { grpc_slice_unref_internal(data_); }
-
+
+ChannelTrace::TraceEvent::~TraceEvent() { grpc_slice_unref_internal(data_); }
+
ChannelTrace::ChannelTrace(size_t max_event_memory)
: num_events_logged_(0),
event_list_memory_usage_(0),
max_event_memory_(max_event_memory),
- head_trace_(nullptr),
- tail_trace_(nullptr) {
+ head_trace_(nullptr),
+ tail_trace_(nullptr) {
if (max_event_memory_ == 0)
return; // tracing is disabled if max_event_memory_ == 0
- gpr_mu_init(&tracer_mu_);
- time_created_ = grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(),
- GPR_CLOCK_REALTIME);
-}
-
-ChannelTrace::~ChannelTrace() {
+ gpr_mu_init(&tracer_mu_);
+ time_created_ = grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(),
+ GPR_CLOCK_REALTIME);
+}
+
+ChannelTrace::~ChannelTrace() {
if (max_event_memory_ == 0)
return; // tracing is disabled if max_event_memory_ == 0
- TraceEvent* it = head_trace_;
- while (it != nullptr) {
- TraceEvent* to_free = it;
- it = it->next();
+ TraceEvent* it = head_trace_;
+ while (it != nullptr) {
+ TraceEvent* to_free = it;
+ it = it->next();
delete to_free;
- }
- gpr_mu_destroy(&tracer_mu_);
-}
-
-void ChannelTrace::AddTraceEventHelper(TraceEvent* new_trace_event) {
- ++num_events_logged_;
- // first event case
- if (head_trace_ == nullptr) {
- head_trace_ = tail_trace_ = new_trace_event;
- }
- // regular event add case
- else {
- tail_trace_->set_next(new_trace_event);
- tail_trace_ = tail_trace_->next();
- }
+ }
+ gpr_mu_destroy(&tracer_mu_);
+}
+
+void ChannelTrace::AddTraceEventHelper(TraceEvent* new_trace_event) {
+ ++num_events_logged_;
+ // first event case
+ if (head_trace_ == nullptr) {
+ head_trace_ = tail_trace_ = new_trace_event;
+ }
+ // regular event add case
+ else {
+ tail_trace_->set_next(new_trace_event);
+ tail_trace_ = tail_trace_->next();
+ }
event_list_memory_usage_ += new_trace_event->memory_usage();
// maybe garbage collect the tail until we are under the memory limit.
while (event_list_memory_usage_ > max_event_memory_) {
- TraceEvent* to_free = head_trace_;
+ TraceEvent* to_free = head_trace_;
event_list_memory_usage_ -= to_free->memory_usage();
- head_trace_ = head_trace_->next();
+ head_trace_ = head_trace_->next();
delete to_free;
- }
-}
-
+ }
+}
+
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));
-}
-
+}
+
void ChannelTrace::AddTraceEventWithReference(
Severity severity, const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_entity) {
@@ -122,28 +122,28 @@ void ChannelTrace::AddTraceEventWithReference(
grpc_slice_unref_internal(data);
return; // tracing is disabled if max_event_memory_ == 0
}
- // create and fill up the new event
- AddTraceEventHelper(
+ // create and fill up the new event
+ AddTraceEventHelper(
new TraceEvent(severity, data, std::move(referenced_entity)));
-}
-
-namespace {
-
-const char* severity_string(ChannelTrace::Severity severity) {
- switch (severity) {
- case ChannelTrace::Severity::Info:
- return "CT_INFO";
- case ChannelTrace::Severity::Warning:
- return "CT_WARNING";
- case ChannelTrace::Severity::Error:
- return "CT_ERROR";
- default:
- GPR_UNREACHABLE_CODE(return "CT_UNKNOWN");
- }
-}
-
-} // anonymous namespace
-
+}
+
+namespace {
+
+const char* severity_string(ChannelTrace::Severity severity) {
+ switch (severity) {
+ case ChannelTrace::Severity::Info:
+ return "CT_INFO";
+ case ChannelTrace::Severity::Warning:
+ return "CT_WARNING";
+ case ChannelTrace::Severity::Error:
+ return "CT_ERROR";
+ default:
+ GPR_UNREACHABLE_CODE(return "CT_UNKNOWN");
+ }
+}
+
+} // anonymous namespace
+
Json ChannelTrace::TraceEvent::RenderTraceEvent() const {
char* description = grpc_slice_to_c_string(data_);
Json::Object object = {
@@ -160,10 +160,10 @@ Json ChannelTrace::TraceEvent::RenderTraceEvent() const {
{(is_channel ? "channelId" : "subchannelId"),
ToString(referenced_entity_->uuid())},
};
- }
+ }
return object;
-}
-
+}
+
Json ChannelTrace::RenderJson() const {
// Tracing is disabled if max_event_memory_ == 0.
if (max_event_memory_ == 0) {
@@ -174,7 +174,7 @@ Json ChannelTrace::RenderJson() const {
};
if (num_events_logged_ > 0) {
object["numEventsLogged"] = ToString(num_events_logged_);
- }
+ }
// Only add in the event list if it is non-empty.
if (head_trace_ != nullptr) {
Json::Array array;
@@ -184,7 +184,7 @@ Json ChannelTrace::RenderJson() const {
object["events"] = std::move(array);
}
return object;
-}
-
+}
+
} // namespace channelz
-} // namespace grpc_core
+} // namespace grpc_core
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 c26e3016da7..5e5d4b98653 100644
--- a/contrib/libs/grpc/src/core/lib/channel/channel_trace.h
+++ b/contrib/libs/grpc/src/core/lib/channel/channel_trace.h
@@ -1,134 +1,134 @@
-/*
- *
- * 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_CHANNEL_CHANNEL_TRACE_H
-#define GRPC_CORE_LIB_CHANNEL_CHANNEL_TRACE_H
-
-#include <grpc/impl/codegen/port_platform.h>
-
-#include <grpc/grpc.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"
-
-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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_CHANNEL_CHANNEL_TRACE_H
+#define GRPC_CORE_LIB_CHANNEL_CHANNEL_TRACE_H
+
+#include <grpc/impl/codegen/port_platform.h>
+
+#include <grpc/grpc.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"
+
+namespace grpc_core {
namespace channelz {
-
+
namespace testing {
size_t GetSizeofTraceEvent(void);
}
class BaseNode;
-// Object used to hold live data for a channel. This data is exposed via the
-// channelz service:
-// https://github.com/grpc/proposal/blob/master/A14-channelz.md
+// Object used to hold live data for a channel. This data is exposed via the
+// channelz service:
+// https://github.com/grpc/proposal/blob/master/A14-channelz.md
class ChannelTrace {
- public:
+ public:
ChannelTrace(size_t max_event_memory);
- ~ChannelTrace();
-
- enum Severity {
- Unset = 0, // never to be used
- Info, // we start at 1 to avoid using proto default values
- Warning,
- Error
- };
-
- // Adds a new trace event to the tracing object
- //
+ ~ChannelTrace();
+
+ enum Severity {
+ Unset = 0, // never to be used
+ Info, // we start at 1 to avoid using proto default values
+ Warning,
+ Error
+ };
+
+ // Adds a new trace event to the tracing object
+ //
// NOTE: each ChannelTrace tracks the memory used by its list of trace
// events, so adding an event with a large amount of data could cause other
// trace event to be evicted. If a single trace is larger than the limit, it
// will cause all events to be evicted. The limit is set with the arg:
// GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE.
//
- // 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.
+ // 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);
-
- // Adds a new trace event to the tracing object. This trace event refers to a
+
+ // 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
// channel has created a new subchannel, then it would record that with
// a TraceEvent referencing the new subchannel.
- //
+ //
// 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,
RefCountedPtr<BaseNode> referenced_entity);
-
+
// Creates and returns the raw Json object, so a parent channelz
// object may incorporate the json before rendering.
Json RenderJson() const;
-
- private:
+
+ private:
friend size_t testing::GetSizeofTraceEvent(void);
- // Private class to encapsulate all the data and bookkeeping needed for a
- // a trace event.
- class TraceEvent {
- public:
+ // Private class to encapsulate all the data and bookkeeping needed for a
+ // a trace event.
+ class TraceEvent {
+ public:
// Constructor for a TraceEvent that references a channel.
TraceEvent(Severity severity, const grpc_slice& data,
RefCountedPtr<BaseNode> referenced_entity_);
-
- // Constructor for a TraceEvent that does not reverence a different
- // channel.
+
+ // Constructor for a TraceEvent that does not reverence a different
+ // channel.
TraceEvent(Severity severity, const grpc_slice& data);
-
- ~TraceEvent();
-
- // Renders the data inside of this TraceEvent into a json object. This is
- // used by the ChannelTrace, when it is rendering itself.
+
+ ~TraceEvent();
+
+ // Renders the data inside of this TraceEvent into a json object. This is
+ // used by the ChannelTrace, when it is rendering itself.
Json RenderTraceEvent() const;
-
- // set and get for the next_ pointer.
- TraceEvent* next() const { return next_; }
- void set_next(TraceEvent* next) { next_ = next; }
-
+
+ // set and get for the next_ pointer.
+ TraceEvent* next() const { return next_; }
+ void set_next(TraceEvent* next) { next_ = next; }
+
size_t memory_usage() const { return memory_usage_; }
- private:
- Severity severity_;
- grpc_slice data_;
- gpr_timespec timestamp_;
- TraceEvent* next_;
- // the tracer object for the (sub)channel that this trace event refers to.
+ private:
+ Severity severity_;
+ grpc_slice data_;
+ gpr_timespec timestamp_;
+ TraceEvent* next_;
+ // the tracer object for the (sub)channel that this trace event refers to.
RefCountedPtr<BaseNode> referenced_entity_;
size_t memory_usage_;
- }; // TraceEvent
-
- // Internal helper to add and link in a trace event
- void AddTraceEventHelper(TraceEvent* new_trace_event);
-
- gpr_mu tracer_mu_;
- uint64_t num_events_logged_;
+ }; // TraceEvent
+
+ // Internal helper to add and link in a trace event
+ void AddTraceEventHelper(TraceEvent* new_trace_event);
+
+ gpr_mu tracer_mu_;
+ uint64_t num_events_logged_;
size_t event_list_memory_usage_;
size_t max_event_memory_;
- TraceEvent* head_trace_;
- TraceEvent* tail_trace_;
- gpr_timespec time_created_;
-};
-
+ TraceEvent* head_trace_;
+ TraceEvent* tail_trace_;
+ gpr_timespec time_created_;
+};
+
} // namespace channelz
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_TRACE_H */
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_TRACE_H */
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 be74d9e88bb..21afd821fa1 100644
--- a/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc
@@ -1,246 +1,246 @@
-/*
- *
- * 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/channel/connected_channel.h"
-
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/byte_buffer.h>
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/transport/transport.h"
-
-#define MAX_BUFFER_LENGTH 8192
-
-typedef struct connected_channel_channel_data {
- grpc_transport* transport;
-} channel_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 <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/connected_channel.h"
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/byte_buffer.h>
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/transport/transport.h"
+
+#define MAX_BUFFER_LENGTH 8192
+
+typedef struct connected_channel_channel_data {
+ grpc_transport* transport;
+} channel_data;
+
struct callback_state {
- grpc_closure closure;
- grpc_closure* original_closure;
+ grpc_closure closure;
+ grpc_closure* original_closure;
grpc_core::CallCombiner* call_combiner;
- const char* reason;
+ const char* reason;
};
-typedef struct connected_channel_call_data {
+typedef struct connected_channel_call_data {
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;
- callback_state recv_message_ready;
+ // 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;
+ callback_state recv_message_ready;
callback_state recv_trailing_metadata_ready;
-} call_data;
-
-static void run_in_call_combiner(void* arg, grpc_error* error) {
- callback_state* state = static_cast<callback_state*>(arg);
- GRPC_CALL_COMBINER_START(state->call_combiner, state->original_closure,
- GRPC_ERROR_REF(error), state->reason);
-}
-
-static void run_cancel_in_call_combiner(void* arg, grpc_error* error) {
- run_in_call_combiner(arg, error);
- gpr_free(arg);
-}
-
-static void intercept_callback(call_data* calld, callback_state* state,
- bool free_when_done, const char* reason,
- grpc_closure** original_closure) {
- state->original_closure = *original_closure;
- state->call_combiner = calld->call_combiner;
- state->reason = reason;
- *original_closure = GRPC_CLOSURE_INIT(
- &state->closure,
- free_when_done ? run_cancel_in_call_combiner : run_in_call_combiner,
- state, grpc_schedule_on_exec_ctx);
-}
-
-static callback_state* get_state_for_batch(
- call_data* calld, grpc_transport_stream_op_batch* batch) {
- if (batch->send_initial_metadata) return &calld->on_complete[0];
- if (batch->send_message) return &calld->on_complete[1];
- if (batch->send_trailing_metadata) return &calld->on_complete[2];
- if (batch->recv_initial_metadata) return &calld->on_complete[3];
- if (batch->recv_message) return &calld->on_complete[4];
- if (batch->recv_trailing_metadata) return &calld->on_complete[5];
- GPR_UNREACHABLE_CODE(return nullptr);
-}
-
-/* We perform a small hack to locate transport data alongside the connected
- channel data in call allocations, to allow everything to be pulled in minimal
- cache line requests */
+} call_data;
+
+static void run_in_call_combiner(void* arg, grpc_error* error) {
+ callback_state* state = static_cast<callback_state*>(arg);
+ GRPC_CALL_COMBINER_START(state->call_combiner, state->original_closure,
+ GRPC_ERROR_REF(error), state->reason);
+}
+
+static void run_cancel_in_call_combiner(void* arg, grpc_error* error) {
+ run_in_call_combiner(arg, error);
+ gpr_free(arg);
+}
+
+static void intercept_callback(call_data* calld, callback_state* state,
+ bool free_when_done, const char* reason,
+ grpc_closure** original_closure) {
+ state->original_closure = *original_closure;
+ state->call_combiner = calld->call_combiner;
+ state->reason = reason;
+ *original_closure = GRPC_CLOSURE_INIT(
+ &state->closure,
+ free_when_done ? run_cancel_in_call_combiner : run_in_call_combiner,
+ state, grpc_schedule_on_exec_ctx);
+}
+
+static callback_state* get_state_for_batch(
+ call_data* calld, grpc_transport_stream_op_batch* batch) {
+ if (batch->send_initial_metadata) return &calld->on_complete[0];
+ if (batch->send_message) return &calld->on_complete[1];
+ if (batch->send_trailing_metadata) return &calld->on_complete[2];
+ if (batch->recv_initial_metadata) return &calld->on_complete[3];
+ if (batch->recv_message) return &calld->on_complete[4];
+ if (batch->recv_trailing_metadata) return &calld->on_complete[5];
+ GPR_UNREACHABLE_CODE(return nullptr);
+}
+
+/* We perform a small hack to locate transport data alongside the connected
+ channel data in call allocations, to allow everything to be pulled in minimal
+ cache line requests */
#define TRANSPORT_STREAM_FROM_CALL_DATA(calld) \
((grpc_stream*)(((char*)(calld)) + \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(call_data))))
-#define CALL_DATA_FROM_TRANSPORT_STREAM(transport_stream) \
+#define CALL_DATA_FROM_TRANSPORT_STREAM(transport_stream) \
((call_data*)(((char*)(transport_stream)) - \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(call_data))))
-
-/* Intercept a call operation and either push it directly up or translate it
- into transport stream operations */
+
+/* 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(
- 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);
- if (batch->recv_initial_metadata) {
- callback_state* state = &calld->recv_initial_metadata_ready;
- intercept_callback(
- calld, state, false, "recv_initial_metadata_ready",
- &batch->payload->recv_initial_metadata.recv_initial_metadata_ready);
- }
- if (batch->recv_message) {
- callback_state* state = &calld->recv_message_ready;
- intercept_callback(calld, state, false, "recv_message_ready",
- &batch->payload->recv_message.recv_message_ready);
- }
+ 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);
+ if (batch->recv_initial_metadata) {
+ callback_state* state = &calld->recv_initial_metadata_ready;
+ intercept_callback(
+ calld, state, false, "recv_initial_metadata_ready",
+ &batch->payload->recv_initial_metadata.recv_initial_metadata_ready);
+ }
+ if (batch->recv_message) {
+ callback_state* state = &calld->recv_message_ready;
+ intercept_callback(calld, state, false, "recv_message_ready",
+ &batch->payload->recv_message.recv_message_ready);
+ }
if (batch->recv_trailing_metadata) {
callback_state* state = &calld->recv_trailing_metadata_ready;
intercept_callback(
calld, state, false, "recv_trailing_metadata_ready",
&batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready);
}
- if (batch->cancel_stream) {
- // There can be more than one cancellation batch in flight at any
- // given time, so we can't just pick out a fixed index into
- // calld->on_complete like we can for the other ops. However,
- // cancellation isn't in the fast path, so we just allocate a new
- // closure for each one.
- callback_state* state =
- static_cast<callback_state*>(gpr_malloc(sizeof(*state)));
- intercept_callback(calld, state, true, "on_complete (cancel_stream)",
- &batch->on_complete);
+ if (batch->cancel_stream) {
+ // There can be more than one cancellation batch in flight at any
+ // given time, so we can't just pick out a fixed index into
+ // calld->on_complete like we can for the other ops. However,
+ // cancellation isn't in the fast path, so we just allocate a new
+ // closure for each one.
+ callback_state* state =
+ static_cast<callback_state*>(gpr_malloc(sizeof(*state)));
+ intercept_callback(calld, state, true, "on_complete (cancel_stream)",
+ &batch->on_complete);
} else if (batch->on_complete != nullptr) {
- callback_state* state = get_state_for_batch(calld, batch);
- intercept_callback(calld, state, false, "on_complete", &batch->on_complete);
- }
- grpc_transport_perform_stream_op(
- chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld), batch);
- GRPC_CALL_COMBINER_STOP(calld->call_combiner, "passed batch to transport");
-}
-
+ callback_state* state = get_state_for_batch(calld, batch);
+ intercept_callback(calld, state, false, "on_complete", &batch->on_complete);
+ }
+ grpc_transport_perform_stream_op(
+ chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld), 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) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- grpc_transport_perform_op(chand->transport, op);
-}
-
-/* Constructor for call_data */
+ 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) {
- 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;
- int r = grpc_transport_init_stream(
- chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld),
- &args->call_stack->refcount, args->server_transport_data, args->arena);
- return r == 0 ? GRPC_ERROR_NONE
- : GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "transport stream initialization failed");
-}
-
-static void set_pollset_or_pollset_set(grpc_call_element* elem,
- grpc_polling_entity* pollent) {
- call_data* calld = static_cast<call_data*>(elem->call_data);
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- grpc_transport_set_pops(chand->transport,
- TRANSPORT_STREAM_FROM_CALL_DATA(calld), pollent);
-}
-
-/* Destructor for call_data */
+ 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;
+ int r = grpc_transport_init_stream(
+ chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld),
+ &args->call_stack->refcount, args->server_transport_data, args->arena);
+ return r == 0 ? GRPC_ERROR_NONE
+ : GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "transport stream initialization failed");
+}
+
+static void set_pollset_or_pollset_set(grpc_call_element* elem,
+ grpc_polling_entity* pollent) {
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ grpc_transport_set_pops(chand->transport,
+ TRANSPORT_STREAM_FROM_CALL_DATA(calld), pollent);
+}
+
+/* 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) {
- 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,
- TRANSPORT_STREAM_FROM_CALL_DATA(calld),
- then_schedule_closure);
-}
-
-/* Constructor for channel_data */
+ 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,
+ TRANSPORT_STREAM_FROM_CALL_DATA(calld),
+ then_schedule_closure);
+}
+
+/* Constructor for channel_data */
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;
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel_data */
+ channel_data* cd = static_cast<channel_data*>(elem->channel_data);
+ GPR_ASSERT(args->is_last);
+ cd->transport = nullptr;
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for channel_data */
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);
- }
-}
-
-/* No-op. */
+ channel_data* cd = static_cast<channel_data*>(elem->channel_data);
+ if (cd->transport) {
+ grpc_transport_destroy(cd->transport);
+ }
+}
+
+/* No-op. */
static void connected_channel_get_channel_info(
grpc_channel_element* /*elem*/, const grpc_channel_info* /*channel_info*/) {
}
-
-const grpc_channel_filter grpc_connected_filter = {
+
+const grpc_channel_filter grpc_connected_filter = {
connected_channel_start_transport_stream_op_batch,
connected_channel_start_transport_op,
- sizeof(call_data),
+ sizeof(call_data),
connected_channel_init_call_elem,
- set_pollset_or_pollset_set,
+ set_pollset_or_pollset_set,
connected_channel_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
connected_channel_init_channel_elem,
connected_channel_destroy_channel_elem,
connected_channel_get_channel_info,
- "connected",
-};
-
-static void bind_transport(grpc_channel_stack* channel_stack,
- grpc_channel_element* elem, void* t) {
- channel_data* cd = static_cast<channel_data*>(elem->channel_data);
- GPR_ASSERT(elem->filter == &grpc_connected_filter);
- GPR_ASSERT(cd->transport == nullptr);
- cd->transport = static_cast<grpc_transport*>(t);
-
- /* HACK(ctiller): increase call stack size for the channel to make space
- for channel data. We need a cleaner (but performant) way to do this,
- and I'm not sure what that is yet.
- This is only "safe" because call stacks place no additional data after
- the last call element, and the last call element MUST be the connected
- channel. */
- channel_stack->call_stack_size +=
- grpc_transport_stream_size(static_cast<grpc_transport*>(t));
-}
-
-bool grpc_add_connected_filter(grpc_channel_stack_builder* builder,
- void* arg_must_be_null) {
- GPR_ASSERT(arg_must_be_null == nullptr);
- grpc_transport* t = grpc_channel_stack_builder_get_transport(builder);
- GPR_ASSERT(t != nullptr);
- return grpc_channel_stack_builder_append_filter(
- builder, &grpc_connected_filter, bind_transport, t);
-}
-
-grpc_stream* grpc_connected_channel_get_stream(grpc_call_element* elem) {
- call_data* calld = static_cast<call_data*>(elem->call_data);
- return TRANSPORT_STREAM_FROM_CALL_DATA(calld);
-}
+ "connected",
+};
+
+static void bind_transport(grpc_channel_stack* channel_stack,
+ grpc_channel_element* elem, void* t) {
+ channel_data* cd = static_cast<channel_data*>(elem->channel_data);
+ GPR_ASSERT(elem->filter == &grpc_connected_filter);
+ GPR_ASSERT(cd->transport == nullptr);
+ cd->transport = static_cast<grpc_transport*>(t);
+
+ /* HACK(ctiller): increase call stack size for the channel to make space
+ for channel data. We need a cleaner (but performant) way to do this,
+ and I'm not sure what that is yet.
+ This is only "safe" because call stacks place no additional data after
+ the last call element, and the last call element MUST be the connected
+ channel. */
+ channel_stack->call_stack_size +=
+ grpc_transport_stream_size(static_cast<grpc_transport*>(t));
+}
+
+bool grpc_add_connected_filter(grpc_channel_stack_builder* builder,
+ void* arg_must_be_null) {
+ GPR_ASSERT(arg_must_be_null == nullptr);
+ grpc_transport* t = grpc_channel_stack_builder_get_transport(builder);
+ GPR_ASSERT(t != nullptr);
+ return grpc_channel_stack_builder_append_filter(
+ builder, &grpc_connected_filter, bind_transport, t);
+}
+
+grpc_stream* grpc_connected_channel_get_stream(grpc_call_element* elem) {
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ return TRANSPORT_STREAM_FROM_CALL_DATA(calld);
+}
diff --git a/contrib/libs/grpc/src/core/lib/channel/connected_channel.h b/contrib/libs/grpc/src/core/lib/channel/connected_channel.h
index faa1c73a21f..332af2c2a7a 100644
--- a/contrib/libs/grpc/src/core/lib/channel/connected_channel.h
+++ b/contrib/libs/grpc/src/core/lib/channel/connected_channel.h
@@ -1,34 +1,34 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CHANNEL_CONNECTED_CHANNEL_H
#define GRPC_CORE_LIB_CHANNEL_CONNECTED_CHANNEL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/channel/channel_stack_builder.h"
-extern const grpc_channel_filter grpc_connected_filter;
-
-bool grpc_add_connected_filter(grpc_channel_stack_builder* builder,
- void* arg_must_be_null);
-
-/* Debug helper to dig the transport stream out of a call element */
-grpc_stream* grpc_connected_channel_get_stream(grpc_call_element* elem);
+extern const grpc_channel_filter grpc_connected_filter;
+bool grpc_add_connected_filter(grpc_channel_stack_builder* builder,
+ void* arg_must_be_null);
+
+/* Debug helper to dig the transport stream out of a call element */
+grpc_stream* grpc_connected_channel_get_stream(grpc_call_element* elem);
+
#endif /* GRPC_CORE_LIB_CHANNEL_CONNECTED_CHANNEL_H */
diff --git a/contrib/libs/grpc/src/core/lib/channel/context.h b/contrib/libs/grpc/src/core/lib/channel/context.h
index bd7fd495e4a..155bad9f5a5 100644
--- a/contrib/libs/grpc/src/core/lib/channel/context.h
+++ b/contrib/libs/grpc/src/core/lib/channel/context.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -37,7 +37,7 @@ typedef enum {
/// Holds a pointer to ServiceConfigCallData associated with this call.
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 826be41cbb0..f0e890f2361 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <string.h>
+
#include "y_absl/strings/str_format.h"
#include <grpc/impl/codegen/slice.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/channel/handshaker.h"
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/iomgr/timer.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/channel/handshaker.h"
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/slice/slice_internal.h"
-
+
namespace grpc_core {
-
+
TraceFlag grpc_handshaker_trace(false, "handshaker");
-
+
namespace {
-
+
TString HandshakerArgsString(HandshakerArgs* args) {
size_t num_args = args->args != nullptr ? args->args->num_args : 0;
size_t read_buffer_length =
@@ -49,12 +49,12 @@ TString HandshakerArgsString(HandshakerArgs* args) {
args->endpoint, args->args, num_args,
grpc_channel_args_string(args->args), args->read_buffer,
read_buffer_length, args->exit_early);
-}
-
+}
+
} // namespace
-
+
HandshakeManager::HandshakeManager() { gpr_mu_init(&mu_); }
-
+
/// Add \a mgr to the server side list of all pending handshake managers, the
/// list starts with \a *head.
// Not thread-safe. Caller needs to synchronize.
@@ -62,53 +62,53 @@ void HandshakeManager::AddToPendingMgrList(HandshakeManager** head) {
GPR_ASSERT(prev_ == nullptr);
GPR_ASSERT(next_ == nullptr);
next_ = *head;
- if (*head) {
+ if (*head) {
(*head)->prev_ = this;
- }
+ }
*head = this;
-}
-
+}
+
/// Remove \a mgr from the server side list of all pending handshake managers.
// Not thread-safe. Caller needs to synchronize.
void HandshakeManager::RemoveFromPendingMgrList(HandshakeManager** head) {
if (next_ != nullptr) {
next_->prev_ = prev_;
- }
+ }
if (prev_ != nullptr) {
prev_->next_ = next_;
- } else {
+ } else {
GPR_ASSERT(*head == this);
*head = next_;
- }
-}
-
+ }
+}
+
/// Shutdown all pending handshake managers starting at head on the server
/// side. Not thread-safe. Caller needs to synchronize.
void HandshakeManager::ShutdownAllPending(grpc_error* why) {
auto* head = this;
- while (head != nullptr) {
+ while (head != nullptr) {
head->Shutdown(GRPC_ERROR_REF(why));
head = head->next_;
- }
- GRPC_ERROR_UNREF(why);
-}
-
+ }
+ GRPC_ERROR_UNREF(why);
+}
+
void HandshakeManager::Add(RefCountedPtr<Handshaker> handshaker) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
- gpr_log(
- GPR_INFO,
- "handshake_manager %p: adding handshaker %s [%p] at index %" PRIuPTR,
+ gpr_log(
+ GPR_INFO,
+ "handshake_manager %p: adding handshaker %s [%p] at index %" PRIuPTR,
this, handshaker->name(), handshaker.get(), handshakers_.size());
- }
+ }
MutexLock lock(&mu_);
handshakers_.push_back(std::move(handshaker));
-}
-
+}
+
HandshakeManager::~HandshakeManager() {
handshakers_.clear();
gpr_mu_destroy(&mu_);
-}
-
+}
+
void HandshakeManager::Shutdown(grpc_error* why) {
{
MutexLock lock(&mu_);
@@ -117,25 +117,25 @@ void HandshakeManager::Shutdown(grpc_error* why) {
is_shutdown_ = true;
handshakers_[index_ - 1]->Shutdown(GRPC_ERROR_REF(why));
}
- }
- GRPC_ERROR_UNREF(why);
-}
-
-// Helper function to call either the next handshaker or the
-// on_handshake_done callback.
-// Returns true if we've scheduled the on_handshake_done callback.
+ }
+ GRPC_ERROR_UNREF(why);
+}
+
+// Helper function to call either the next handshaker or the
+// 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)) {
- gpr_log(GPR_INFO,
- "handshake_manager %p: error=%s shutdown=%d index=%" PRIuPTR
- ", args=%s",
+ gpr_log(GPR_INFO,
+ "handshake_manager %p: error=%s shutdown=%d index=%" PRIuPTR
+ ", args=%s",
this, grpc_error_string(error), is_shutdown_, index_,
HandshakerArgsString(&args_).c_str());
- }
+ }
GPR_ASSERT(index_ <= handshakers_.size());
- // If we got an error or we've been shut down or we're exiting early or
- // we've finished the last handshaker, invoke the on_handshake_done
- // callback. Otherwise, call the next handshaker.
+ // If we got an error or we've been shut down or we're exiting early or
+ // we've finished the last handshaker, invoke the on_handshake_done
+ // callback. Otherwise, call the next handshaker.
if (error != GRPC_ERROR_NONE || is_shutdown_ || args_.exit_early ||
index_ == handshakers_.size()) {
if (error == GRPC_ERROR_NONE && is_shutdown_) {
@@ -163,26 +163,26 @@ bool HandshakeManager::CallNextHandshakerLocked(grpc_error* error) {
"handshake_manager %p: handshaking complete -- scheduling "
"on_handshake_done with error=%s",
this, grpc_error_string(error));
- }
- // Cancel deadline timer, since we're invoking the on_handshake_done
- // callback now.
+ }
+ // 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);
is_shutdown_ = true;
- } else {
+ } else {
auto handshaker = handshakers_[index_];
if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) {
- gpr_log(
- GPR_INFO,
- "handshake_manager %p: calling handshaker %s [%p] at index %" PRIuPTR,
+ gpr_log(
+ GPR_INFO,
+ "handshake_manager %p: calling handshaker %s [%p] at index %" PRIuPTR,
this, handshaker->name(), handshaker.get(), index_);
- }
+ }
handshaker->DoHandshake(acceptor_, &call_next_handshaker_, &args_);
- }
+ }
++index_;
return is_shutdown_;
-}
-
+}
+
void HandshakeManager::CallNextHandshakerFn(void* arg, grpc_error* error) {
auto* mgr = static_cast<HandshakeManager*>(arg);
bool done;
@@ -190,22 +190,22 @@ void HandshakeManager::CallNextHandshakerFn(void* arg, grpc_error* error) {
MutexLock lock(&mgr->mu_);
done = mgr->CallNextHandshakerLocked(GRPC_ERROR_REF(error));
}
- // If we're invoked the final callback, we won't be coming back
- // to this function, so we can release our reference to the
- // handshake manager.
- if (done) {
+ // If we're invoked the final callback, we won't be coming back
+ // to this function, so we can release our reference to the
+ // handshake manager.
+ if (done) {
mgr->Unref();
- }
-}
-
+ }
+}
+
void HandshakeManager::OnTimeoutFn(void* arg, grpc_error* error) {
auto* mgr = static_cast<HandshakeManager*>(arg);
if (error == GRPC_ERROR_NONE) { // Timer fired, rather than being cancelled
mgr->Shutdown(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshake timed out"));
- }
+ }
mgr->Unref();
-}
-
+}
+
void HandshakeManager::DoHandshake(grpc_endpoint* endpoint,
const grpc_channel_args* channel_args,
grpc_millis deadline,
@@ -246,10 +246,10 @@ void HandshakeManager::DoHandshake(grpc_endpoint* endpoint,
Ref().release();
done = CallNextHandshakerLocked(GRPC_ERROR_NONE);
}
- if (done) {
+ if (done) {
Unref();
- }
-}
+ }
+}
} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker.h b/contrib/libs/grpc/src/core/lib/channel/handshaker.h
index cc8e9b2578d..fbf80ddc77a 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker.h
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CHANNEL_HANDSHAKER_H
#define GRPC_CORE_LIB_CHANNEL_HANDSHAKER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "y_absl/container/inlined_vector.h"
#include <grpc/support/string_util.h>
@@ -88,7 +88,7 @@ class Handshaker : public RefCounted<Handshaker> {
//
// HandshakeManager
//
-
+
class HandshakeManager : public RefCounted<HandshakeManager> {
public:
HandshakeManager();
@@ -166,14 +166,14 @@ class HandshakeManager : public RefCounted<HandshakeManager> {
HandshakeManager* prev_ = nullptr;
HandshakeManager* next_ = nullptr;
};
-
+
} // namespace grpc_core
-
+
// TODO(arjunroy): These are transitional to account for the new handshaker API
// and will eventually be removed entirely.
typedef grpc_core::HandshakeManager grpc_handshake_manager;
typedef grpc_core::Handshaker grpc_handshaker;
void grpc_handshake_manager_add(grpc_handshake_manager* mgr,
grpc_handshaker* handshaker);
-
+
#endif /* GRPC_CORE_LIB_CHANNEL_HANDSHAKER_H */
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 520e5e4b258..4a1d72ffb87 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CHANNEL_HANDSHAKER_FACTORY_H
#define GRPC_CORE_LIB_CHANNEL_HANDSHAKER_FACTORY_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/grpc_types.h>
#include "src/core/lib/channel/handshaker.h"
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 614531832dd..680aea9e4cf 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc
@@ -1,40 +1,40 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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 "y_absl/container/inlined_vector.h"
-#include "src/core/lib/channel/handshaker_registry.h"
+#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/gpr/alloc.h"
#include "src/core/lib/gprpp/memory.h"
-
-#include <string.h>
+
+#include <string.h>
#include <algorithm>
-
-#include <grpc/support/alloc.h>
-
-//
-// grpc_handshaker_factory_list
-//
-
+
+#include <grpc/support/alloc.h>
+
+//
+// grpc_handshaker_factory_list
+//
+
namespace grpc_core {
-
+
namespace {
class HandshakerFactoryList {
@@ -55,44 +55,44 @@ HandshakerFactoryList* g_handshaker_factory_lists = nullptr;
void HandshakerFactoryList::Register(
bool at_start, std::unique_ptr<HandshakerFactory> factory) {
factories_.push_back(std::move(factory));
- if (at_start) {
+ if (at_start) {
auto* end = &factories_[factories_.size() - 1];
std::rotate(&factories_[0], end, end + 1);
- }
-}
-
+ }
+}
+
void HandshakerFactoryList::AddHandshakers(const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
HandshakeManager* handshake_mgr) {
for (size_t idx = 0; idx < factories_.size(); ++idx) {
auto& handshaker_factory = factories_[idx];
handshaker_factory->AddHandshakers(args, interested_parties, handshake_mgr);
- }
-}
-
-//
-// plugin
-//
-
+ }
+}
+
+//
+// plugin
+//
+
void HandshakerRegistry::Init() {
GPR_ASSERT(g_handshaker_factory_lists == nullptr);
g_handshaker_factory_lists = new HandshakerFactoryList[NUM_HANDSHAKER_TYPES];
-}
-
+}
+
void HandshakerRegistry::Shutdown() {
GPR_ASSERT(g_handshaker_factory_lists != nullptr);
delete[] g_handshaker_factory_lists;
g_handshaker_factory_lists = nullptr;
-}
-
+}
+
void HandshakerRegistry::RegisterHandshakerFactory(
bool at_start, HandshakerType handshaker_type,
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));
-}
-
+}
+
void HandshakerRegistry::AddHandshakers(HandshakerType handshaker_type,
const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
@@ -100,6 +100,6 @@ void HandshakerRegistry::AddHandshakers(HandshakerType handshaker_type,
GPR_ASSERT(g_handshaker_factory_lists != nullptr);
auto& factory_list = g_handshaker_factory_lists[handshaker_type];
factory_list.AddHandshakers(args, interested_parties, handshake_mgr);
-}
+}
} // namespace grpc_core
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 4a02efc3f24..7f9d230608f 100644
--- a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h
+++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CHANNEL_HANDSHAKER_REGISTRY_H
#define GRPC_CORE_LIB_CHANNEL_HANDSHAKER_REGISTRY_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/grpc_types.h>
#include "src/core/lib/channel/handshaker_factory.h"
diff --git a/contrib/libs/grpc/src/core/lib/channel/status_util.cc b/contrib/libs/grpc/src/core/lib/channel/status_util.cc
index 39f310a165b..2aef72e4bf8 100644
--- a/contrib/libs/grpc/src/core/lib/channel/status_util.cc
+++ b/contrib/libs/grpc/src/core/lib/channel/status_util.cc
@@ -1,99 +1,99 @@
-/*
- *
- * 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/channel/status_util.h"
-
-#include "src/core/lib/gpr/useful.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/channel/status_util.h"
+
+#include "src/core/lib/gpr/useful.h"
+
struct status_string_entry {
- const char* str;
- grpc_status_code status;
+ const char* str;
+ grpc_status_code status;
};
-static const status_string_entry g_status_string_entries[] = {
- {"OK", GRPC_STATUS_OK},
- {"CANCELLED", GRPC_STATUS_CANCELLED},
- {"UNKNOWN", GRPC_STATUS_UNKNOWN},
- {"INVALID_ARGUMENT", GRPC_STATUS_INVALID_ARGUMENT},
- {"DEADLINE_EXCEEDED", GRPC_STATUS_DEADLINE_EXCEEDED},
- {"NOT_FOUND", GRPC_STATUS_NOT_FOUND},
- {"ALREADY_EXISTS", GRPC_STATUS_ALREADY_EXISTS},
- {"PERMISSION_DENIED", GRPC_STATUS_PERMISSION_DENIED},
- {"UNAUTHENTICATED", GRPC_STATUS_UNAUTHENTICATED},
- {"RESOURCE_EXHAUSTED", GRPC_STATUS_RESOURCE_EXHAUSTED},
- {"FAILED_PRECONDITION", GRPC_STATUS_FAILED_PRECONDITION},
- {"ABORTED", GRPC_STATUS_ABORTED},
- {"OUT_OF_RANGE", GRPC_STATUS_OUT_OF_RANGE},
- {"UNIMPLEMENTED", GRPC_STATUS_UNIMPLEMENTED},
- {"INTERNAL", GRPC_STATUS_INTERNAL},
- {"UNAVAILABLE", GRPC_STATUS_UNAVAILABLE},
- {"DATA_LOSS", GRPC_STATUS_DATA_LOSS},
-};
-
-bool grpc_status_code_from_string(const char* status_str,
- grpc_status_code* status) {
- for (size_t i = 0; i < GPR_ARRAY_SIZE(g_status_string_entries); ++i) {
- if (strcmp(status_str, g_status_string_entries[i].str) == 0) {
- *status = g_status_string_entries[i].status;
- return true;
- }
- }
- return false;
-}
-
-const char* grpc_status_code_to_string(grpc_status_code status) {
- switch (status) {
- case GRPC_STATUS_OK:
- return "OK";
- case GRPC_STATUS_CANCELLED:
- return "CANCELLED";
- case GRPC_STATUS_UNKNOWN:
- return "UNKNOWN";
- case GRPC_STATUS_INVALID_ARGUMENT:
- return "INVALID_ARGUMENT";
- case GRPC_STATUS_DEADLINE_EXCEEDED:
- return "DEADLINE_EXCEEDED";
- case GRPC_STATUS_NOT_FOUND:
- return "NOT_FOUND";
- case GRPC_STATUS_ALREADY_EXISTS:
- return "ALREADY_EXISTS";
- case GRPC_STATUS_PERMISSION_DENIED:
- return "PERMISSION_DENIED";
- case GRPC_STATUS_UNAUTHENTICATED:
- return "UNAUTHENTICATED";
- case GRPC_STATUS_RESOURCE_EXHAUSTED:
- return "RESOURCE_EXHAUSTED";
- case GRPC_STATUS_FAILED_PRECONDITION:
- return "FAILED_PRECONDITION";
- case GRPC_STATUS_ABORTED:
- return "ABORTED";
- case GRPC_STATUS_OUT_OF_RANGE:
- return "OUT_OF_RANGE";
- case GRPC_STATUS_UNIMPLEMENTED:
- return "UNIMPLEMENTED";
- case GRPC_STATUS_INTERNAL:
- return "INTERNAL";
- case GRPC_STATUS_UNAVAILABLE:
- return "UNAVAILABLE";
- case GRPC_STATUS_DATA_LOSS:
- return "DATA_LOSS";
- default:
- return "UNKNOWN";
- }
-}
+static const status_string_entry g_status_string_entries[] = {
+ {"OK", GRPC_STATUS_OK},
+ {"CANCELLED", GRPC_STATUS_CANCELLED},
+ {"UNKNOWN", GRPC_STATUS_UNKNOWN},
+ {"INVALID_ARGUMENT", GRPC_STATUS_INVALID_ARGUMENT},
+ {"DEADLINE_EXCEEDED", GRPC_STATUS_DEADLINE_EXCEEDED},
+ {"NOT_FOUND", GRPC_STATUS_NOT_FOUND},
+ {"ALREADY_EXISTS", GRPC_STATUS_ALREADY_EXISTS},
+ {"PERMISSION_DENIED", GRPC_STATUS_PERMISSION_DENIED},
+ {"UNAUTHENTICATED", GRPC_STATUS_UNAUTHENTICATED},
+ {"RESOURCE_EXHAUSTED", GRPC_STATUS_RESOURCE_EXHAUSTED},
+ {"FAILED_PRECONDITION", GRPC_STATUS_FAILED_PRECONDITION},
+ {"ABORTED", GRPC_STATUS_ABORTED},
+ {"OUT_OF_RANGE", GRPC_STATUS_OUT_OF_RANGE},
+ {"UNIMPLEMENTED", GRPC_STATUS_UNIMPLEMENTED},
+ {"INTERNAL", GRPC_STATUS_INTERNAL},
+ {"UNAVAILABLE", GRPC_STATUS_UNAVAILABLE},
+ {"DATA_LOSS", GRPC_STATUS_DATA_LOSS},
+};
+
+bool grpc_status_code_from_string(const char* status_str,
+ grpc_status_code* status) {
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(g_status_string_entries); ++i) {
+ if (strcmp(status_str, g_status_string_entries[i].str) == 0) {
+ *status = g_status_string_entries[i].status;
+ return true;
+ }
+ }
+ return false;
+}
+
+const char* grpc_status_code_to_string(grpc_status_code status) {
+ switch (status) {
+ case GRPC_STATUS_OK:
+ return "OK";
+ case GRPC_STATUS_CANCELLED:
+ return "CANCELLED";
+ case GRPC_STATUS_UNKNOWN:
+ return "UNKNOWN";
+ case GRPC_STATUS_INVALID_ARGUMENT:
+ return "INVALID_ARGUMENT";
+ case GRPC_STATUS_DEADLINE_EXCEEDED:
+ return "DEADLINE_EXCEEDED";
+ case GRPC_STATUS_NOT_FOUND:
+ return "NOT_FOUND";
+ case GRPC_STATUS_ALREADY_EXISTS:
+ return "ALREADY_EXISTS";
+ case GRPC_STATUS_PERMISSION_DENIED:
+ return "PERMISSION_DENIED";
+ case GRPC_STATUS_UNAUTHENTICATED:
+ return "UNAUTHENTICATED";
+ case GRPC_STATUS_RESOURCE_EXHAUSTED:
+ return "RESOURCE_EXHAUSTED";
+ case GRPC_STATUS_FAILED_PRECONDITION:
+ return "FAILED_PRECONDITION";
+ case GRPC_STATUS_ABORTED:
+ return "ABORTED";
+ case GRPC_STATUS_OUT_OF_RANGE:
+ return "OUT_OF_RANGE";
+ case GRPC_STATUS_UNIMPLEMENTED:
+ return "UNIMPLEMENTED";
+ case GRPC_STATUS_INTERNAL:
+ return "INTERNAL";
+ case GRPC_STATUS_UNAVAILABLE:
+ return "UNAVAILABLE";
+ case GRPC_STATUS_DATA_LOSS:
+ return "DATA_LOSS";
+ default:
+ return "UNKNOWN";
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/channel/status_util.h b/contrib/libs/grpc/src/core/lib/channel/status_util.h
index 5409de6b3c9..812ed10c4a4 100644
--- a/contrib/libs/grpc/src/core/lib/channel/status_util.h
+++ b/contrib/libs/grpc/src/core/lib/channel/status_util.h
@@ -1,58 +1,58 @@
-/*
- *
- * 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_CHANNEL_STATUS_UTIL_H
-#define GRPC_CORE_LIB_CHANNEL_STATUS_UTIL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/status.h>
-
-#include <stdbool.h>
-#include <string.h>
-
-/// If \a status_str is a valid status string, sets \a status to the
-/// corresponding status value and returns true.
-bool grpc_status_code_from_string(const char* status_str,
- grpc_status_code* status);
-
-/// Returns the string form of \a status, or "UNKNOWN" if invalid.
-const char* grpc_status_code_to_string(grpc_status_code status);
-
-namespace grpc_core {
-namespace internal {
-
-/// A set of grpc_status_code values.
-class StatusCodeSet {
- public:
- bool Empty() const { return status_code_mask_ == 0; }
-
- void Add(grpc_status_code status) { status_code_mask_ |= (1 << status); }
-
- bool Contains(grpc_status_code status) const {
- return status_code_mask_ & (1 << status);
- }
-
- private:
- int status_code_mask_ = 0; // A bitfield of status codes in the set.
-};
-
-} // namespace internal
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_CHANNEL_STATUS_UTIL_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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_CHANNEL_STATUS_UTIL_H
+#define GRPC_CORE_LIB_CHANNEL_STATUS_UTIL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/status.h>
+
+#include <stdbool.h>
+#include <string.h>
+
+/// If \a status_str is a valid status string, sets \a status to the
+/// corresponding status value and returns true.
+bool grpc_status_code_from_string(const char* status_str,
+ grpc_status_code* status);
+
+/// Returns the string form of \a status, or "UNKNOWN" if invalid.
+const char* grpc_status_code_to_string(grpc_status_code status);
+
+namespace grpc_core {
+namespace internal {
+
+/// A set of grpc_status_code values.
+class StatusCodeSet {
+ public:
+ bool Empty() const { return status_code_mask_ == 0; }
+
+ void Add(grpc_status_code status) { status_code_mask_ |= (1 << status); }
+
+ bool Contains(grpc_status_code status) const {
+ return status_code_mask_ & (1 << status);
+ }
+
+ private:
+ int status_code_mask_ = 0; // A bitfield of status codes in the set.
+};
+
+} // namespace internal
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_CHANNEL_STATUS_UTIL_H */
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 d58d2f541a0..4c357d23576 100644
--- a/contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/compression/algorithm_metadata.h
@@ -1,61 +1,61 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_ALGORITHM_METADATA_H
#define GRPC_CORE_LIB_COMPRESSION_ALGORITHM_METADATA_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/compression.h>
-#include "src/core/lib/compression/compression_internal.h"
+#include "src/core/lib/compression/compression_internal.h"
#include "src/core/lib/transport/metadata.h"
/** Return compression algorithm based metadata value */
-grpc_slice grpc_compression_algorithm_slice(
+grpc_slice grpc_compression_algorithm_slice(
grpc_compression_algorithm algorithm);
-/** Find compression algorithm based on passed in mdstr - returns
- * GRPC_COMPRESS_ALGORITHM_COUNT on failure */
-grpc_compression_algorithm grpc_compression_algorithm_from_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);
-
-/** Return compression algorithm based metadata element */
-grpc_mdelem grpc_compression_encoding_mdelem(
+
+/** Return compression algorithm based metadata element */
+grpc_mdelem grpc_compression_encoding_mdelem(
grpc_compression_algorithm algorithm);
-/** Return message compression algorithm based metadata element (grpc-encoding:
- * xxx) */
-grpc_mdelem grpc_message_compression_encoding_mdelem(
- grpc_message_compression_algorithm algorithm);
-
-/** Return stream compression algorithm based metadata element
- * (content-encoding: xxx) */
-grpc_mdelem grpc_stream_compression_encoding_mdelem(
- grpc_stream_compression_algorithm algorithm);
-
+/** Return message compression algorithm based metadata element (grpc-encoding:
+ * xxx) */
+grpc_mdelem grpc_message_compression_encoding_mdelem(
+ grpc_message_compression_algorithm algorithm);
+
+/** Return stream compression algorithm based metadata element
+ * (content-encoding: xxx) */
+grpc_mdelem grpc_stream_compression_encoding_mdelem(
+ grpc_stream_compression_algorithm algorithm);
+
/** Find compression algorithm based on passed in mdstr - returns
* GRPC_COMPRESS_ALGORITHM_COUNT on failure */
-grpc_message_compression_algorithm
+grpc_message_compression_algorithm
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(
+/** 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);
-
+
#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 8a0abca8dd7..77cb993f104 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/compression.cc
@@ -1,154 +1,154 @@
-/*
- *
- * 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 <stdlib.h>
-#include <string.h>
-
-#include <grpc/compression.h>
-
-#include "src/core/lib/compression/algorithm_metadata.h"
-#include "src/core/lib/compression/compression_internal.h"
-#include "src/core/lib/gpr/useful.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 <stdlib.h>
+#include <string.h>
+
+#include <grpc/compression.h>
+
+#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/surface/api_trace.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-int grpc_compression_algorithm_is_message(
- grpc_compression_algorithm algorithm) {
- return (algorithm >= GRPC_COMPRESS_DEFLATE && algorithm <= GRPC_COMPRESS_GZIP)
- ? 1
- : 0;
-}
-
-int grpc_compression_algorithm_is_stream(grpc_compression_algorithm algorithm) {
- return (algorithm == GRPC_COMPRESS_STREAM_GZIP) ? 1 : 0;
-}
-
-int grpc_compression_algorithm_parse(grpc_slice name,
- grpc_compression_algorithm* algorithm) {
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+int grpc_compression_algorithm_is_message(
+ grpc_compression_algorithm algorithm) {
+ return (algorithm >= GRPC_COMPRESS_DEFLATE && algorithm <= GRPC_COMPRESS_GZIP)
+ ? 1
+ : 0;
+}
+
+int grpc_compression_algorithm_is_stream(grpc_compression_algorithm algorithm) {
+ return (algorithm == GRPC_COMPRESS_STREAM_GZIP) ? 1 : 0;
+}
+
+int grpc_compression_algorithm_parse(grpc_slice name,
+ grpc_compression_algorithm* algorithm) {
if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_IDENTITY)) {
- *algorithm = GRPC_COMPRESS_NONE;
- return 1;
+ *algorithm = GRPC_COMPRESS_NONE;
+ return 1;
} else if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_DEFLATE)) {
- *algorithm = GRPC_COMPRESS_DEFLATE;
- return 1;
+ *algorithm = GRPC_COMPRESS_DEFLATE;
+ return 1;
} else if (grpc_slice_eq_static_interned(name, GRPC_MDSTR_GZIP)) {
- *algorithm = GRPC_COMPRESS_GZIP;
- return 1;
+ *algorithm = GRPC_COMPRESS_GZIP;
+ return 1;
} else if (grpc_slice_eq_static_interned(name,
GRPC_MDSTR_STREAM_SLASH_GZIP)) {
- *algorithm = GRPC_COMPRESS_STREAM_GZIP;
- return 1;
- } else {
- return 0;
- }
-}
-
-int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm,
- const char** name) {
+ *algorithm = GRPC_COMPRESS_STREAM_GZIP;
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm,
+ const char** name) {
GRPC_API_TRACE("grpc_compression_algorithm_name(algorithm=%d, name=%p)", 2,
- ((int)algorithm, name));
- switch (algorithm) {
- case GRPC_COMPRESS_NONE:
- *name = "identity";
- return 1;
- case GRPC_COMPRESS_DEFLATE:
- *name = "deflate";
- return 1;
- case GRPC_COMPRESS_GZIP:
- *name = "gzip";
- return 1;
- case GRPC_COMPRESS_STREAM_GZIP:
- *name = "stream/gzip";
- return 1;
- case GRPC_COMPRESS_ALGORITHMS_COUNT:
- return 0;
- }
- return 0;
-}
-
-grpc_compression_algorithm grpc_compression_algorithm_for_level(
- grpc_compression_level level, uint32_t accepted_encodings) {
- grpc_compression_algorithm algo;
- if (level == GRPC_COMPRESS_LEVEL_NONE) {
- return GRPC_COMPRESS_NONE;
- } else if (level <= GRPC_COMPRESS_LEVEL_HIGH) {
- // TODO(mxyan): Design algorithm to select from all algorithms, including
- // stream compression algorithm
- if (!grpc_compression_algorithm_from_message_stream_compression_algorithm(
- &algo,
- grpc_message_compression_algorithm_for_level(
- level,
- grpc_compression_bitset_to_message_bitset(accepted_encodings)),
- static_cast<grpc_stream_compression_algorithm>(0))) {
- gpr_log(GPR_ERROR, "Parse compression level error");
- return GRPC_COMPRESS_NONE;
- }
- return algo;
- } else {
- gpr_log(GPR_ERROR, "Unknown compression level: %d", level);
- return GRPC_COMPRESS_NONE;
- }
-}
-
-void grpc_compression_options_init(grpc_compression_options* opts) {
- memset(opts, 0, sizeof(*opts));
- /* all enabled by default */
- opts->enabled_algorithms_bitset = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1;
-}
-
-void grpc_compression_options_enable_algorithm(
- grpc_compression_options* opts, grpc_compression_algorithm algorithm) {
- GPR_BITSET(&opts->enabled_algorithms_bitset, algorithm);
-}
-
-void grpc_compression_options_disable_algorithm(
- grpc_compression_options* opts, grpc_compression_algorithm algorithm) {
- GPR_BITCLEAR(&opts->enabled_algorithms_bitset, algorithm);
-}
-
-int grpc_compression_options_is_algorithm_enabled(
- const grpc_compression_options* opts,
- grpc_compression_algorithm algorithm) {
+ ((int)algorithm, name));
+ switch (algorithm) {
+ case GRPC_COMPRESS_NONE:
+ *name = "identity";
+ return 1;
+ case GRPC_COMPRESS_DEFLATE:
+ *name = "deflate";
+ return 1;
+ case GRPC_COMPRESS_GZIP:
+ *name = "gzip";
+ return 1;
+ case GRPC_COMPRESS_STREAM_GZIP:
+ *name = "stream/gzip";
+ return 1;
+ case GRPC_COMPRESS_ALGORITHMS_COUNT:
+ return 0;
+ }
+ return 0;
+}
+
+grpc_compression_algorithm grpc_compression_algorithm_for_level(
+ grpc_compression_level level, uint32_t accepted_encodings) {
+ grpc_compression_algorithm algo;
+ if (level == GRPC_COMPRESS_LEVEL_NONE) {
+ return GRPC_COMPRESS_NONE;
+ } else if (level <= GRPC_COMPRESS_LEVEL_HIGH) {
+ // TODO(mxyan): Design algorithm to select from all algorithms, including
+ // stream compression algorithm
+ if (!grpc_compression_algorithm_from_message_stream_compression_algorithm(
+ &algo,
+ grpc_message_compression_algorithm_for_level(
+ level,
+ grpc_compression_bitset_to_message_bitset(accepted_encodings)),
+ static_cast<grpc_stream_compression_algorithm>(0))) {
+ gpr_log(GPR_ERROR, "Parse compression level error");
+ return GRPC_COMPRESS_NONE;
+ }
+ return algo;
+ } else {
+ gpr_log(GPR_ERROR, "Unknown compression level: %d", level);
+ return GRPC_COMPRESS_NONE;
+ }
+}
+
+void grpc_compression_options_init(grpc_compression_options* opts) {
+ memset(opts, 0, sizeof(*opts));
+ /* all enabled by default */
+ opts->enabled_algorithms_bitset = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1;
+}
+
+void grpc_compression_options_enable_algorithm(
+ grpc_compression_options* opts, grpc_compression_algorithm algorithm) {
+ GPR_BITSET(&opts->enabled_algorithms_bitset, algorithm);
+}
+
+void grpc_compression_options_disable_algorithm(
+ grpc_compression_options* opts, grpc_compression_algorithm algorithm) {
+ GPR_BITCLEAR(&opts->enabled_algorithms_bitset, 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);
-}
-
-grpc_slice grpc_compression_algorithm_slice(
- grpc_compression_algorithm algorithm) {
- switch (algorithm) {
- case GRPC_COMPRESS_NONE:
- return GRPC_MDSTR_IDENTITY;
- case GRPC_COMPRESS_DEFLATE:
- return GRPC_MDSTR_DEFLATE;
- case GRPC_COMPRESS_GZIP:
- return GRPC_MDSTR_GZIP;
- case GRPC_COMPRESS_STREAM_GZIP:
- return GRPC_MDSTR_STREAM_SLASH_GZIP;
- case GRPC_COMPRESS_ALGORITHMS_COUNT:
- return grpc_empty_slice();
- }
- return grpc_empty_slice();
-}
-
-grpc_compression_algorithm grpc_compression_algorithm_from_slice(
+}
+
+grpc_slice grpc_compression_algorithm_slice(
+ grpc_compression_algorithm algorithm) {
+ switch (algorithm) {
+ case GRPC_COMPRESS_NONE:
+ return GRPC_MDSTR_IDENTITY;
+ case GRPC_COMPRESS_DEFLATE:
+ return GRPC_MDSTR_DEFLATE;
+ case GRPC_COMPRESS_GZIP:
+ return GRPC_MDSTR_GZIP;
+ case GRPC_COMPRESS_STREAM_GZIP:
+ return GRPC_MDSTR_STREAM_SLASH_GZIP;
+ case GRPC_COMPRESS_ALGORITHMS_COUNT:
+ return grpc_empty_slice();
+ }
+ return grpc_empty_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;
@@ -157,23 +157,23 @@ grpc_compression_algorithm grpc_compression_algorithm_from_slice(
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;
-}
-
-grpc_mdelem grpc_compression_encoding_mdelem(
- grpc_compression_algorithm algorithm) {
- switch (algorithm) {
- case GRPC_COMPRESS_NONE:
- return GRPC_MDELEM_GRPC_ENCODING_IDENTITY;
- case GRPC_COMPRESS_DEFLATE:
- return GRPC_MDELEM_GRPC_ENCODING_DEFLATE;
- case GRPC_COMPRESS_GZIP:
- return GRPC_MDELEM_GRPC_ENCODING_GZIP;
- case GRPC_COMPRESS_STREAM_GZIP:
- return GRPC_MDELEM_GRPC_ENCODING_GZIP;
- default:
- break;
- }
- return GRPC_MDNULL;
-}
+ return GRPC_COMPRESS_STREAM_GZIP;
+ return GRPC_COMPRESS_ALGORITHMS_COUNT;
+}
+
+grpc_mdelem grpc_compression_encoding_mdelem(
+ grpc_compression_algorithm algorithm) {
+ switch (algorithm) {
+ case GRPC_COMPRESS_NONE:
+ return GRPC_MDELEM_GRPC_ENCODING_IDENTITY;
+ case GRPC_COMPRESS_DEFLATE:
+ return GRPC_MDELEM_GRPC_ENCODING_DEFLATE;
+ case GRPC_COMPRESS_GZIP:
+ return GRPC_MDELEM_GRPC_ENCODING_GZIP;
+ case GRPC_COMPRESS_STREAM_GZIP:
+ return GRPC_MDELEM_GRPC_ENCODING_GZIP;
+ default:
+ break;
+ }
+ return GRPC_MDNULL;
+}
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 e0cf6d45194..4111b15265c 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression_internal.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/compression_internal.cc
@@ -1,280 +1,280 @@
-/*
- *
- * 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 <stdlib.h>
-#include <string.h>
-
-#include <grpc/compression.h>
-
-#include "src/core/lib/compression/algorithm_metadata.h"
-#include "src/core/lib/compression/compression_internal.h"
-#include "src/core/lib/gpr/useful.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 <stdlib.h>
+#include <string.h>
+
+#include <grpc/compression.h>
+
+#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/surface/api_trace.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-/* Interfaces related to MD */
-
-grpc_message_compression_algorithm
+#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))
- return GRPC_MESSAGE_COMPRESS_NONE;
+ return GRPC_MESSAGE_COMPRESS_NONE;
if (grpc_slice_eq_static_interned(str, GRPC_MDSTR_DEFLATE))
- return GRPC_MESSAGE_COMPRESS_DEFLATE;
+ return GRPC_MESSAGE_COMPRESS_DEFLATE;
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(
+ 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;
- return GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT;
-}
-
-grpc_mdelem grpc_message_compression_encoding_mdelem(
- grpc_message_compression_algorithm algorithm) {
- switch (algorithm) {
- case GRPC_MESSAGE_COMPRESS_NONE:
- return GRPC_MDELEM_GRPC_ENCODING_IDENTITY;
- case GRPC_MESSAGE_COMPRESS_DEFLATE:
- return GRPC_MDELEM_GRPC_ENCODING_DEFLATE;
- case GRPC_MESSAGE_COMPRESS_GZIP:
- return GRPC_MDELEM_GRPC_ENCODING_GZIP;
- default:
- break;
- }
- return GRPC_MDNULL;
-}
-
-grpc_mdelem grpc_stream_compression_encoding_mdelem(
- grpc_stream_compression_algorithm algorithm) {
- switch (algorithm) {
- case GRPC_STREAM_COMPRESS_NONE:
- return GRPC_MDELEM_CONTENT_ENCODING_IDENTITY;
- case GRPC_STREAM_COMPRESS_GZIP:
- return GRPC_MDELEM_CONTENT_ENCODING_GZIP;
- default:
- break;
- }
- return GRPC_MDNULL;
-}
-
-/* Interfaces performing transformation between compression algorithms and
- * levels. */
-grpc_message_compression_algorithm
-grpc_compression_algorithm_to_message_compression_algorithm(
- grpc_compression_algorithm algo) {
- switch (algo) {
- case GRPC_COMPRESS_DEFLATE:
- return GRPC_MESSAGE_COMPRESS_DEFLATE;
- case GRPC_COMPRESS_GZIP:
- return GRPC_MESSAGE_COMPRESS_GZIP;
- default:
- return GRPC_MESSAGE_COMPRESS_NONE;
- }
-}
-
-grpc_stream_compression_algorithm
-grpc_compression_algorithm_to_stream_compression_algorithm(
- grpc_compression_algorithm algo) {
- switch (algo) {
- case GRPC_COMPRESS_STREAM_GZIP:
- return GRPC_STREAM_COMPRESS_GZIP;
- default:
- return GRPC_STREAM_COMPRESS_NONE;
- }
-}
-
-uint32_t grpc_compression_bitset_to_message_bitset(uint32_t bitset) {
- return bitset & ((1u << GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) - 1);
-}
-
-uint32_t grpc_compression_bitset_to_stream_bitset(uint32_t bitset) {
- uint32_t identity = (bitset & 1u);
- uint32_t other_bits =
- (bitset >> (GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT - 1)) &
- ((1u << GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT) - 2);
- return identity | other_bits;
-}
-
-uint32_t grpc_compression_bitset_from_message_stream_compression_bitset(
- uint32_t message_bitset, uint32_t stream_bitset) {
- uint32_t offset_stream_bitset =
- (stream_bitset & 1u) |
- ((stream_bitset & (~1u)) << (GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT - 1));
- return message_bitset | offset_stream_bitset;
-}
-
-int grpc_compression_algorithm_from_message_stream_compression_algorithm(
- grpc_compression_algorithm* algorithm,
- grpc_message_compression_algorithm message_algorithm,
- grpc_stream_compression_algorithm stream_algorithm) {
- if (message_algorithm != GRPC_MESSAGE_COMPRESS_NONE &&
- stream_algorithm != GRPC_STREAM_COMPRESS_NONE) {
- *algorithm = GRPC_COMPRESS_NONE;
- return 0;
- }
- if (message_algorithm == GRPC_MESSAGE_COMPRESS_NONE) {
- switch (stream_algorithm) {
- case GRPC_STREAM_COMPRESS_NONE:
- *algorithm = GRPC_COMPRESS_NONE;
- return 1;
- case GRPC_STREAM_COMPRESS_GZIP:
- *algorithm = GRPC_COMPRESS_STREAM_GZIP;
- return 1;
- default:
- *algorithm = GRPC_COMPRESS_NONE;
- return 0;
- }
- } else {
- switch (message_algorithm) {
- case GRPC_MESSAGE_COMPRESS_NONE:
- *algorithm = GRPC_COMPRESS_NONE;
- return 1;
- case GRPC_MESSAGE_COMPRESS_DEFLATE:
- *algorithm = GRPC_COMPRESS_DEFLATE;
- return 1;
- case GRPC_MESSAGE_COMPRESS_GZIP:
- *algorithm = GRPC_COMPRESS_GZIP;
- return 1;
- default:
- *algorithm = GRPC_COMPRESS_NONE;
- return 0;
- }
- }
- return 0;
-}
-
-/* Interfaces for message compression. */
-
-int grpc_message_compression_algorithm_name(
- grpc_message_compression_algorithm algorithm, const char** name) {
- GRPC_API_TRACE(
+ return GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT;
+}
+
+grpc_mdelem grpc_message_compression_encoding_mdelem(
+ grpc_message_compression_algorithm algorithm) {
+ switch (algorithm) {
+ case GRPC_MESSAGE_COMPRESS_NONE:
+ return GRPC_MDELEM_GRPC_ENCODING_IDENTITY;
+ case GRPC_MESSAGE_COMPRESS_DEFLATE:
+ return GRPC_MDELEM_GRPC_ENCODING_DEFLATE;
+ case GRPC_MESSAGE_COMPRESS_GZIP:
+ return GRPC_MDELEM_GRPC_ENCODING_GZIP;
+ default:
+ break;
+ }
+ return GRPC_MDNULL;
+}
+
+grpc_mdelem grpc_stream_compression_encoding_mdelem(
+ grpc_stream_compression_algorithm algorithm) {
+ switch (algorithm) {
+ case GRPC_STREAM_COMPRESS_NONE:
+ return GRPC_MDELEM_CONTENT_ENCODING_IDENTITY;
+ case GRPC_STREAM_COMPRESS_GZIP:
+ return GRPC_MDELEM_CONTENT_ENCODING_GZIP;
+ default:
+ break;
+ }
+ return GRPC_MDNULL;
+}
+
+/* Interfaces performing transformation between compression algorithms and
+ * levels. */
+grpc_message_compression_algorithm
+grpc_compression_algorithm_to_message_compression_algorithm(
+ grpc_compression_algorithm algo) {
+ switch (algo) {
+ case GRPC_COMPRESS_DEFLATE:
+ return GRPC_MESSAGE_COMPRESS_DEFLATE;
+ case GRPC_COMPRESS_GZIP:
+ return GRPC_MESSAGE_COMPRESS_GZIP;
+ default:
+ return GRPC_MESSAGE_COMPRESS_NONE;
+ }
+}
+
+grpc_stream_compression_algorithm
+grpc_compression_algorithm_to_stream_compression_algorithm(
+ grpc_compression_algorithm algo) {
+ switch (algo) {
+ case GRPC_COMPRESS_STREAM_GZIP:
+ return GRPC_STREAM_COMPRESS_GZIP;
+ default:
+ return GRPC_STREAM_COMPRESS_NONE;
+ }
+}
+
+uint32_t grpc_compression_bitset_to_message_bitset(uint32_t bitset) {
+ return bitset & ((1u << GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) - 1);
+}
+
+uint32_t grpc_compression_bitset_to_stream_bitset(uint32_t bitset) {
+ uint32_t identity = (bitset & 1u);
+ uint32_t other_bits =
+ (bitset >> (GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT - 1)) &
+ ((1u << GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT) - 2);
+ return identity | other_bits;
+}
+
+uint32_t grpc_compression_bitset_from_message_stream_compression_bitset(
+ uint32_t message_bitset, uint32_t stream_bitset) {
+ uint32_t offset_stream_bitset =
+ (stream_bitset & 1u) |
+ ((stream_bitset & (~1u)) << (GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT - 1));
+ return message_bitset | offset_stream_bitset;
+}
+
+int grpc_compression_algorithm_from_message_stream_compression_algorithm(
+ grpc_compression_algorithm* algorithm,
+ grpc_message_compression_algorithm message_algorithm,
+ grpc_stream_compression_algorithm stream_algorithm) {
+ if (message_algorithm != GRPC_MESSAGE_COMPRESS_NONE &&
+ stream_algorithm != GRPC_STREAM_COMPRESS_NONE) {
+ *algorithm = GRPC_COMPRESS_NONE;
+ return 0;
+ }
+ if (message_algorithm == GRPC_MESSAGE_COMPRESS_NONE) {
+ switch (stream_algorithm) {
+ case GRPC_STREAM_COMPRESS_NONE:
+ *algorithm = GRPC_COMPRESS_NONE;
+ return 1;
+ case GRPC_STREAM_COMPRESS_GZIP:
+ *algorithm = GRPC_COMPRESS_STREAM_GZIP;
+ return 1;
+ default:
+ *algorithm = GRPC_COMPRESS_NONE;
+ return 0;
+ }
+ } else {
+ switch (message_algorithm) {
+ case GRPC_MESSAGE_COMPRESS_NONE:
+ *algorithm = GRPC_COMPRESS_NONE;
+ return 1;
+ case GRPC_MESSAGE_COMPRESS_DEFLATE:
+ *algorithm = GRPC_COMPRESS_DEFLATE;
+ return 1;
+ case GRPC_MESSAGE_COMPRESS_GZIP:
+ *algorithm = GRPC_COMPRESS_GZIP;
+ return 1;
+ default:
+ *algorithm = GRPC_COMPRESS_NONE;
+ return 0;
+ }
+ }
+ return 0;
+}
+
+/* Interfaces for message compression. */
+
+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,
- ((int)algorithm, name));
- switch (algorithm) {
- case GRPC_MESSAGE_COMPRESS_NONE:
- *name = "identity";
- return 1;
- case GRPC_MESSAGE_COMPRESS_DEFLATE:
- *name = "deflate";
- return 1;
- case GRPC_MESSAGE_COMPRESS_GZIP:
- *name = "gzip";
- return 1;
- case GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT:
- return 0;
- }
- return 0;
-}
-
-/* TODO(dgq): Add the ability to specify parameters to the individual
- * compression algorithms */
-grpc_message_compression_algorithm grpc_message_compression_algorithm_for_level(
- grpc_compression_level level, uint32_t accepted_encodings) {
- GRPC_API_TRACE("grpc_message_compression_algorithm_for_level(level=%d)", 1,
- ((int)level));
- if (level > GRPC_COMPRESS_LEVEL_HIGH) {
- gpr_log(GPR_ERROR, "Unknown message compression level %d.",
- static_cast<int>(level));
- abort();
- }
-
- const size_t num_supported =
- GPR_BITCOUNT(accepted_encodings) - 1; /* discard NONE */
- if (level == GRPC_COMPRESS_LEVEL_NONE || num_supported == 0) {
- return GRPC_MESSAGE_COMPRESS_NONE;
- }
-
- GPR_ASSERT(level > 0);
-
- /* Establish a "ranking" or compression algorithms in increasing order of
- * compression.
- * This is simplistic and we will probably want to introduce other dimensions
- * in the future (cpu/memory cost, etc). */
- const grpc_message_compression_algorithm algos_ranking[] = {
- GRPC_MESSAGE_COMPRESS_GZIP, GRPC_MESSAGE_COMPRESS_DEFLATE};
-
- /* intersect algos_ranking with the supported ones keeping the ranked order */
- grpc_message_compression_algorithm
- sorted_supported_algos[GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT];
- size_t algos_supported_idx = 0;
- for (size_t i = 0; i < GPR_ARRAY_SIZE(algos_ranking); i++) {
- const grpc_message_compression_algorithm alg = algos_ranking[i];
- for (size_t j = 0; j < num_supported; j++) {
- if (GPR_BITGET(accepted_encodings, alg) == 1) {
- /* if \a alg in supported */
- sorted_supported_algos[algos_supported_idx++] = alg;
- break;
- }
- }
- if (algos_supported_idx == num_supported) break;
- }
-
- switch (level) {
- case GRPC_COMPRESS_LEVEL_NONE:
- abort(); /* should have been handled already */
- case GRPC_COMPRESS_LEVEL_LOW:
- return sorted_supported_algos[0];
- case GRPC_COMPRESS_LEVEL_MED:
- return sorted_supported_algos[num_supported / 2];
- case GRPC_COMPRESS_LEVEL_HIGH:
- return sorted_supported_algos[num_supported - 1];
- default:
- abort();
- };
-}
-
-int grpc_message_compression_algorithm_parse(
- grpc_slice value, grpc_message_compression_algorithm* algorithm) {
+ ((int)algorithm, name));
+ switch (algorithm) {
+ case GRPC_MESSAGE_COMPRESS_NONE:
+ *name = "identity";
+ return 1;
+ case GRPC_MESSAGE_COMPRESS_DEFLATE:
+ *name = "deflate";
+ return 1;
+ case GRPC_MESSAGE_COMPRESS_GZIP:
+ *name = "gzip";
+ return 1;
+ case GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT:
+ return 0;
+ }
+ return 0;
+}
+
+/* TODO(dgq): Add the ability to specify parameters to the individual
+ * compression algorithms */
+grpc_message_compression_algorithm grpc_message_compression_algorithm_for_level(
+ grpc_compression_level level, uint32_t accepted_encodings) {
+ GRPC_API_TRACE("grpc_message_compression_algorithm_for_level(level=%d)", 1,
+ ((int)level));
+ if (level > GRPC_COMPRESS_LEVEL_HIGH) {
+ gpr_log(GPR_ERROR, "Unknown message compression level %d.",
+ static_cast<int>(level));
+ abort();
+ }
+
+ const size_t num_supported =
+ GPR_BITCOUNT(accepted_encodings) - 1; /* discard NONE */
+ if (level == GRPC_COMPRESS_LEVEL_NONE || num_supported == 0) {
+ return GRPC_MESSAGE_COMPRESS_NONE;
+ }
+
+ GPR_ASSERT(level > 0);
+
+ /* Establish a "ranking" or compression algorithms in increasing order of
+ * compression.
+ * This is simplistic and we will probably want to introduce other dimensions
+ * in the future (cpu/memory cost, etc). */
+ const grpc_message_compression_algorithm algos_ranking[] = {
+ GRPC_MESSAGE_COMPRESS_GZIP, GRPC_MESSAGE_COMPRESS_DEFLATE};
+
+ /* intersect algos_ranking with the supported ones keeping the ranked order */
+ grpc_message_compression_algorithm
+ sorted_supported_algos[GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT];
+ size_t algos_supported_idx = 0;
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(algos_ranking); i++) {
+ const grpc_message_compression_algorithm alg = algos_ranking[i];
+ for (size_t j = 0; j < num_supported; j++) {
+ if (GPR_BITGET(accepted_encodings, alg) == 1) {
+ /* if \a alg in supported */
+ sorted_supported_algos[algos_supported_idx++] = alg;
+ break;
+ }
+ }
+ if (algos_supported_idx == num_supported) break;
+ }
+
+ switch (level) {
+ case GRPC_COMPRESS_LEVEL_NONE:
+ abort(); /* should have been handled already */
+ case GRPC_COMPRESS_LEVEL_LOW:
+ return sorted_supported_algos[0];
+ case GRPC_COMPRESS_LEVEL_MED:
+ return sorted_supported_algos[num_supported / 2];
+ case GRPC_COMPRESS_LEVEL_HIGH:
+ return sorted_supported_algos[num_supported - 1];
+ default:
+ abort();
+ };
+}
+
+int grpc_message_compression_algorithm_parse(
+ grpc_slice value, grpc_message_compression_algorithm* algorithm) {
if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
- *algorithm = GRPC_MESSAGE_COMPRESS_NONE;
- return 1;
+ *algorithm = GRPC_MESSAGE_COMPRESS_NONE;
+ return 1;
} else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_DEFLATE)) {
- *algorithm = GRPC_MESSAGE_COMPRESS_DEFLATE;
- return 1;
+ *algorithm = GRPC_MESSAGE_COMPRESS_DEFLATE;
+ return 1;
} else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
- *algorithm = GRPC_MESSAGE_COMPRESS_GZIP;
- return 1;
- } else {
- return 0;
- }
- return 0;
-}
-
-/* Interfaces for stream compression. */
-
-int grpc_stream_compression_algorithm_parse(
- grpc_slice value, grpc_stream_compression_algorithm* algorithm) {
+ *algorithm = GRPC_MESSAGE_COMPRESS_GZIP;
+ return 1;
+ } else {
+ return 0;
+ }
+ return 0;
+}
+
+/* Interfaces for stream compression. */
+
+int grpc_stream_compression_algorithm_parse(
+ grpc_slice value, grpc_stream_compression_algorithm* algorithm) {
if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_IDENTITY)) {
- *algorithm = GRPC_STREAM_COMPRESS_NONE;
- return 1;
+ *algorithm = GRPC_STREAM_COMPRESS_NONE;
+ return 1;
} else if (grpc_slice_eq_static_interned(value, GRPC_MDSTR_GZIP)) {
- *algorithm = GRPC_STREAM_COMPRESS_GZIP;
- return 1;
- } else {
- return 0;
- }
- return 0;
-}
+ *algorithm = GRPC_STREAM_COMPRESS_GZIP;
+ return 1;
+ } else {
+ return 0;
+ }
+ return 0;
+}
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 49afb941d73..f9e7078898f 100644
--- a/contrib/libs/grpc/src/core/lib/compression/compression_internal.h
+++ b/contrib/libs/grpc/src/core/lib/compression/compression_internal.h
@@ -1,96 +1,96 @@
-/*
- *
- * 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_COMPRESSION_COMPRESSION_INTERNAL_H
-#define GRPC_CORE_LIB_COMPRESSION_COMPRESSION_INTERNAL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/compression_types.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_COMPRESSION_COMPRESSION_INTERNAL_H
+#define GRPC_CORE_LIB_COMPRESSION_COMPRESSION_INTERNAL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/impl/codegen/compression_types.h>
+
#include "src/core/lib/gpr/useful.h"
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef enum {
- GRPC_MESSAGE_COMPRESS_NONE = 0,
- GRPC_MESSAGE_COMPRESS_DEFLATE,
- GRPC_MESSAGE_COMPRESS_GZIP,
- /* TODO(ctiller): snappy */
- GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT
-} grpc_message_compression_algorithm;
-
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+ GRPC_MESSAGE_COMPRESS_NONE = 0,
+ GRPC_MESSAGE_COMPRESS_DEFLATE,
+ GRPC_MESSAGE_COMPRESS_GZIP,
+ /* TODO(ctiller): snappy */
+ GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT
+} grpc_message_compression_algorithm;
+
/** Stream compression algorithms supported by gRPC */
-typedef enum {
- GRPC_STREAM_COMPRESS_NONE = 0,
- GRPC_STREAM_COMPRESS_GZIP,
- GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT
-} grpc_stream_compression_algorithm;
-
-/* Interfaces performing transformation between compression algorithms and
- * levels. */
-
-grpc_message_compression_algorithm
-grpc_compression_algorithm_to_message_compression_algorithm(
- grpc_compression_algorithm algo);
-
-grpc_stream_compression_algorithm
-grpc_compression_algorithm_to_stream_compression_algorithm(
- grpc_compression_algorithm algo);
-
-uint32_t grpc_compression_bitset_to_message_bitset(uint32_t bitset);
-
-uint32_t grpc_compression_bitset_to_stream_bitset(uint32_t bitset);
-
-uint32_t grpc_compression_bitset_from_message_stream_compression_bitset(
- uint32_t message_bitset, uint32_t stream_bitset);
-
-int grpc_compression_algorithm_from_message_stream_compression_algorithm(
- grpc_compression_algorithm* algorithm,
- grpc_message_compression_algorithm message_algorithm,
- grpc_stream_compression_algorithm stream_algorithm);
-
-/* Interfaces for message compression. */
-
-int grpc_message_compression_algorithm_name(
- grpc_message_compression_algorithm algorithm, const char** name);
-
-grpc_message_compression_algorithm grpc_message_compression_algorithm_for_level(
- grpc_compression_level level, uint32_t accepted_encodings);
-
-int grpc_message_compression_algorithm_parse(
- grpc_slice value, grpc_message_compression_algorithm* algorithm);
-
-/* Interfaces for stream compression. */
-
-int grpc_stream_compression_algorithm_parse(
- grpc_slice value, grpc_stream_compression_algorithm* algorithm);
-
-#ifdef __cplusplus
-}
-#endif
-
+typedef enum {
+ GRPC_STREAM_COMPRESS_NONE = 0,
+ GRPC_STREAM_COMPRESS_GZIP,
+ GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT
+} grpc_stream_compression_algorithm;
+
+/* Interfaces performing transformation between compression algorithms and
+ * levels. */
+
+grpc_message_compression_algorithm
+grpc_compression_algorithm_to_message_compression_algorithm(
+ grpc_compression_algorithm algo);
+
+grpc_stream_compression_algorithm
+grpc_compression_algorithm_to_stream_compression_algorithm(
+ grpc_compression_algorithm algo);
+
+uint32_t grpc_compression_bitset_to_message_bitset(uint32_t bitset);
+
+uint32_t grpc_compression_bitset_to_stream_bitset(uint32_t bitset);
+
+uint32_t grpc_compression_bitset_from_message_stream_compression_bitset(
+ uint32_t message_bitset, uint32_t stream_bitset);
+
+int grpc_compression_algorithm_from_message_stream_compression_algorithm(
+ grpc_compression_algorithm* algorithm,
+ grpc_message_compression_algorithm message_algorithm,
+ grpc_stream_compression_algorithm stream_algorithm);
+
+/* Interfaces for message compression. */
+
+int grpc_message_compression_algorithm_name(
+ grpc_message_compression_algorithm algorithm, const char** name);
+
+grpc_message_compression_algorithm grpc_message_compression_algorithm_for_level(
+ grpc_compression_level level, uint32_t accepted_encodings);
+
+int grpc_message_compression_algorithm_parse(
+ grpc_slice value, grpc_message_compression_algorithm* algorithm);
+
+/* Interfaces for stream compression. */
+
+int grpc_stream_compression_algorithm_parse(
+ grpc_slice value, grpc_stream_compression_algorithm* algorithm);
+
+#ifdef __cplusplus
+}
+#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);
}
-#endif /* GRPC_CORE_LIB_COMPRESSION_COMPRESSION_INTERNAL_H */
+#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 7c2a70bad4e..0bc2689974c 100644
--- a/contrib/libs/grpc/src/core/lib/compression/message_compress.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/message_compress.cc
@@ -1,192 +1,192 @@
-/*
- *
- * 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/compression/message_compress.h"
-
-#include <string.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 <grpc/support/port_platform.h>
+
+#include "src/core/lib/compression/message_compress.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
#include <zlib.h>
-
-#include "src/core/lib/slice/slice_internal.h"
-
-#define OUTPUT_BLOCK_SIZE 1024
-
-static int zlib_body(z_stream* zs, grpc_slice_buffer* input,
- grpc_slice_buffer* output,
- int (*flate)(z_stream* zs, int flush)) {
+
+#include "src/core/lib/slice/slice_internal.h"
+
+#define OUTPUT_BLOCK_SIZE 1024
+
+static int zlib_body(z_stream* zs, grpc_slice_buffer* input,
+ grpc_slice_buffer* output,
+ int (*flate)(z_stream* zs, int flush)) {
int r = Z_STREAM_END; /* Do not fail on an empty input. */
- int flush;
- size_t i;
- grpc_slice outbuf = GRPC_SLICE_MALLOC(OUTPUT_BLOCK_SIZE);
- const uInt uint_max = ~static_cast<uInt>(0);
-
- GPR_ASSERT(GRPC_SLICE_LENGTH(outbuf) <= uint_max);
- zs->avail_out = static_cast<uInt> GRPC_SLICE_LENGTH(outbuf);
- zs->next_out = GRPC_SLICE_START_PTR(outbuf);
- flush = Z_NO_FLUSH;
- for (i = 0; i < input->count; i++) {
- if (i == input->count - 1) flush = Z_FINISH;
- GPR_ASSERT(GRPC_SLICE_LENGTH(input->slices[i]) <= uint_max);
- zs->avail_in = static_cast<uInt> GRPC_SLICE_LENGTH(input->slices[i]);
- zs->next_in = GRPC_SLICE_START_PTR(input->slices[i]);
- do {
- if (zs->avail_out == 0) {
- grpc_slice_buffer_add_indexed(output, outbuf);
- outbuf = GRPC_SLICE_MALLOC(OUTPUT_BLOCK_SIZE);
- GPR_ASSERT(GRPC_SLICE_LENGTH(outbuf) <= uint_max);
- zs->avail_out = static_cast<uInt> GRPC_SLICE_LENGTH(outbuf);
- zs->next_out = GRPC_SLICE_START_PTR(outbuf);
- }
- r = flate(zs, flush);
- if (r < 0 && r != Z_BUF_ERROR /* not fatal */) {
- gpr_log(GPR_INFO, "zlib error (%d)", r);
- goto error;
- }
- } while (zs->avail_out == 0);
- if (zs->avail_in) {
- gpr_log(GPR_INFO, "zlib: not all input consumed");
- goto error;
- }
- }
+ int flush;
+ size_t i;
+ grpc_slice outbuf = GRPC_SLICE_MALLOC(OUTPUT_BLOCK_SIZE);
+ const uInt uint_max = ~static_cast<uInt>(0);
+
+ GPR_ASSERT(GRPC_SLICE_LENGTH(outbuf) <= uint_max);
+ zs->avail_out = static_cast<uInt> GRPC_SLICE_LENGTH(outbuf);
+ zs->next_out = GRPC_SLICE_START_PTR(outbuf);
+ flush = Z_NO_FLUSH;
+ for (i = 0; i < input->count; i++) {
+ if (i == input->count - 1) flush = Z_FINISH;
+ GPR_ASSERT(GRPC_SLICE_LENGTH(input->slices[i]) <= uint_max);
+ zs->avail_in = static_cast<uInt> GRPC_SLICE_LENGTH(input->slices[i]);
+ zs->next_in = GRPC_SLICE_START_PTR(input->slices[i]);
+ do {
+ if (zs->avail_out == 0) {
+ grpc_slice_buffer_add_indexed(output, outbuf);
+ outbuf = GRPC_SLICE_MALLOC(OUTPUT_BLOCK_SIZE);
+ GPR_ASSERT(GRPC_SLICE_LENGTH(outbuf) <= uint_max);
+ zs->avail_out = static_cast<uInt> GRPC_SLICE_LENGTH(outbuf);
+ zs->next_out = GRPC_SLICE_START_PTR(outbuf);
+ }
+ r = flate(zs, flush);
+ if (r < 0 && r != Z_BUF_ERROR /* not fatal */) {
+ gpr_log(GPR_INFO, "zlib error (%d)", r);
+ goto error;
+ }
+ } while (zs->avail_out == 0);
+ if (zs->avail_in) {
+ gpr_log(GPR_INFO, "zlib: not all input consumed");
+ goto error;
+ }
+ }
if (r != Z_STREAM_END) {
gpr_log(GPR_INFO, "zlib: Data error");
goto error;
}
-
- GPR_ASSERT(outbuf.refcount);
- outbuf.data.refcounted.length -= zs->avail_out;
- grpc_slice_buffer_add_indexed(output, outbuf);
-
- return 1;
-
-error:
- grpc_slice_unref_internal(outbuf);
- return 0;
-}
-
+
+ GPR_ASSERT(outbuf.refcount);
+ outbuf.data.refcounted.length -= zs->avail_out;
+ grpc_slice_buffer_add_indexed(output, outbuf);
+
+ return 1;
+
+error:
+ grpc_slice_unref_internal(outbuf);
+ return 0;
+}
+
static void* zalloc_gpr(void* /*opaque*/, unsigned int items,
unsigned int size) {
- return gpr_malloc(items * size);
-}
-
+ return gpr_malloc(items * size);
+}
+
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) {
- z_stream zs;
- int r;
- size_t i;
- size_t count_before = output->count;
- size_t length_before = output->length;
- memset(&zs, 0, sizeof(zs));
- zs.zalloc = zalloc_gpr;
- zs.zfree = zfree_gpr;
- r = deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | (gzip ? 16 : 0),
- 8, Z_DEFAULT_STRATEGY);
- GPR_ASSERT(r == Z_OK);
- r = zlib_body(&zs, input, output, deflate) && output->length < input->length;
- if (!r) {
- for (i = count_before; i < output->count; i++) {
- grpc_slice_unref_internal(output->slices[i]);
- }
- output->count = count_before;
- output->length = length_before;
- }
- deflateEnd(&zs);
- return r;
-}
-
-static int zlib_decompress(grpc_slice_buffer* input, grpc_slice_buffer* output,
- int gzip) {
- z_stream zs;
- int r;
- size_t i;
- size_t count_before = output->count;
- size_t length_before = output->length;
- memset(&zs, 0, sizeof(zs));
- zs.zalloc = zalloc_gpr;
- zs.zfree = zfree_gpr;
- r = inflateInit2(&zs, 15 | (gzip ? 16 : 0));
- GPR_ASSERT(r == Z_OK);
- r = zlib_body(&zs, input, output, inflate);
- if (!r) {
- for (i = count_before; i < output->count; i++) {
- grpc_slice_unref_internal(output->slices[i]);
- }
- output->count = count_before;
- output->length = length_before;
- }
- inflateEnd(&zs);
- return r;
-}
-
-static int copy(grpc_slice_buffer* input, grpc_slice_buffer* output) {
- size_t i;
- for (i = 0; i < input->count; i++) {
- grpc_slice_buffer_add(output, grpc_slice_ref_internal(input->slices[i]));
- }
- return 1;
-}
-
-static int compress_inner(grpc_message_compression_algorithm algorithm,
- grpc_slice_buffer* input, grpc_slice_buffer* output) {
- switch (algorithm) {
- case GRPC_MESSAGE_COMPRESS_NONE:
- /* the fallback path always needs to be send uncompressed: we simply
- rely on that here */
- return 0;
- case GRPC_MESSAGE_COMPRESS_DEFLATE:
- return zlib_compress(input, output, 0);
- case GRPC_MESSAGE_COMPRESS_GZIP:
- return zlib_compress(input, output, 1);
- case GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT:
- break;
- }
- gpr_log(GPR_ERROR, "invalid compression algorithm %d", algorithm);
- return 0;
-}
-
-int grpc_msg_compress(grpc_message_compression_algorithm algorithm,
- grpc_slice_buffer* input, grpc_slice_buffer* output) {
- if (!compress_inner(algorithm, input, output)) {
- copy(input, output);
- return 0;
- }
- return 1;
-}
-
-int grpc_msg_decompress(grpc_message_compression_algorithm algorithm,
- grpc_slice_buffer* input, grpc_slice_buffer* output) {
- switch (algorithm) {
- case GRPC_MESSAGE_COMPRESS_NONE:
- return copy(input, output);
- case GRPC_MESSAGE_COMPRESS_DEFLATE:
- return zlib_decompress(input, output, 0);
- case GRPC_MESSAGE_COMPRESS_GZIP:
- return zlib_decompress(input, output, 1);
- case GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT:
- break;
- }
- gpr_log(GPR_ERROR, "invalid compression algorithm %d", algorithm);
- return 0;
-}
+
+static int zlib_compress(grpc_slice_buffer* input, grpc_slice_buffer* output,
+ int gzip) {
+ z_stream zs;
+ int r;
+ size_t i;
+ size_t count_before = output->count;
+ size_t length_before = output->length;
+ memset(&zs, 0, sizeof(zs));
+ zs.zalloc = zalloc_gpr;
+ zs.zfree = zfree_gpr;
+ r = deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | (gzip ? 16 : 0),
+ 8, Z_DEFAULT_STRATEGY);
+ GPR_ASSERT(r == Z_OK);
+ r = zlib_body(&zs, input, output, deflate) && output->length < input->length;
+ if (!r) {
+ for (i = count_before; i < output->count; i++) {
+ grpc_slice_unref_internal(output->slices[i]);
+ }
+ output->count = count_before;
+ output->length = length_before;
+ }
+ deflateEnd(&zs);
+ return r;
+}
+
+static int zlib_decompress(grpc_slice_buffer* input, grpc_slice_buffer* output,
+ int gzip) {
+ z_stream zs;
+ int r;
+ size_t i;
+ size_t count_before = output->count;
+ size_t length_before = output->length;
+ memset(&zs, 0, sizeof(zs));
+ zs.zalloc = zalloc_gpr;
+ zs.zfree = zfree_gpr;
+ r = inflateInit2(&zs, 15 | (gzip ? 16 : 0));
+ GPR_ASSERT(r == Z_OK);
+ r = zlib_body(&zs, input, output, inflate);
+ if (!r) {
+ for (i = count_before; i < output->count; i++) {
+ grpc_slice_unref_internal(output->slices[i]);
+ }
+ output->count = count_before;
+ output->length = length_before;
+ }
+ inflateEnd(&zs);
+ return r;
+}
+
+static int copy(grpc_slice_buffer* input, grpc_slice_buffer* output) {
+ size_t i;
+ for (i = 0; i < input->count; i++) {
+ grpc_slice_buffer_add(output, grpc_slice_ref_internal(input->slices[i]));
+ }
+ return 1;
+}
+
+static int compress_inner(grpc_message_compression_algorithm algorithm,
+ grpc_slice_buffer* input, grpc_slice_buffer* output) {
+ switch (algorithm) {
+ case GRPC_MESSAGE_COMPRESS_NONE:
+ /* the fallback path always needs to be send uncompressed: we simply
+ rely on that here */
+ return 0;
+ case GRPC_MESSAGE_COMPRESS_DEFLATE:
+ return zlib_compress(input, output, 0);
+ case GRPC_MESSAGE_COMPRESS_GZIP:
+ return zlib_compress(input, output, 1);
+ case GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT:
+ break;
+ }
+ gpr_log(GPR_ERROR, "invalid compression algorithm %d", algorithm);
+ return 0;
+}
+
+int grpc_msg_compress(grpc_message_compression_algorithm algorithm,
+ grpc_slice_buffer* input, grpc_slice_buffer* output) {
+ if (!compress_inner(algorithm, input, output)) {
+ copy(input, output);
+ return 0;
+ }
+ return 1;
+}
+
+int grpc_msg_decompress(grpc_message_compression_algorithm algorithm,
+ grpc_slice_buffer* input, grpc_slice_buffer* output) {
+ switch (algorithm) {
+ case GRPC_MESSAGE_COMPRESS_NONE:
+ return copy(input, output);
+ case GRPC_MESSAGE_COMPRESS_DEFLATE:
+ return zlib_decompress(input, output, 0);
+ case GRPC_MESSAGE_COMPRESS_GZIP:
+ return zlib_decompress(input, output, 1);
+ case GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT:
+ break;
+ }
+ gpr_log(GPR_ERROR, "invalid compression algorithm %d", algorithm);
+ return 0;
+}
diff --git a/contrib/libs/grpc/src/core/lib/compression/message_compress.h b/contrib/libs/grpc/src/core/lib/compression/message_compress.h
index 91654e47e33..026386b8689 100644
--- a/contrib/libs/grpc/src/core/lib/compression/message_compress.h
+++ b/contrib/libs/grpc/src/core/lib/compression/message_compress.h
@@ -1,40 +1,40 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_MESSAGE_COMPRESS_H
#define GRPC_CORE_LIB_COMPRESSION_MESSAGE_COMPRESS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice_buffer.h>
-#include "src/core/lib/compression/compression_internal.h"
-
+#include "src/core/lib/compression/compression_internal.h"
+
/* compress 'input' to 'output' using 'algorithm'.
On success, appends compressed slices to output and returns 1.
On failure, appends uncompressed slices to output and returns 0. */
-int grpc_msg_compress(grpc_message_compression_algorithm algorithm,
+int grpc_msg_compress(grpc_message_compression_algorithm algorithm,
grpc_slice_buffer* input, grpc_slice_buffer* output);
/* decompress 'input' to 'output' using 'algorithm'.
On success, appends slices to output and returns 1.
On failure, output is unchanged, and returns 0. */
-int grpc_msg_decompress(grpc_message_compression_algorithm algorithm,
+int grpc_msg_decompress(grpc_message_compression_algorithm algorithm,
grpc_slice_buffer* input, grpc_slice_buffer* output);
#endif /* GRPC_CORE_LIB_COMPRESSION_MESSAGE_COMPRESS_H */
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 e0857988643..26253231387 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression.cc
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression.cc
@@ -1,80 +1,80 @@
-/*
- *
- * 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 <grpc/support/log.h>
-
-#include "src/core/lib/compression/stream_compression.h"
-#include "src/core/lib/compression/stream_compression_gzip.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/log.h>
+
+#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"
-
-extern const grpc_stream_compression_vtable
- grpc_stream_compression_identity_vtable;
-
-bool grpc_stream_compress(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) {
- return ctx->vtable->compress(ctx, in, out, output_size, max_output_size,
- flush);
-}
-
-bool grpc_stream_decompress(grpc_stream_compression_context* ctx,
- grpc_slice_buffer* in, grpc_slice_buffer* out,
- size_t* output_size, size_t max_output_size,
- bool* end_of_context) {
- return ctx->vtable->decompress(ctx, in, out, output_size, max_output_size,
- end_of_context);
-}
-
-grpc_stream_compression_context* grpc_stream_compression_context_create(
- grpc_stream_compression_method method) {
- switch (method) {
- case GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS:
- case GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS:
- return grpc_stream_compression_identity_vtable.context_create(method);
- case GRPC_STREAM_COMPRESSION_GZIP_COMPRESS:
- case GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS:
- return grpc_stream_compression_gzip_vtable.context_create(method);
- default:
- gpr_log(GPR_ERROR, "Unknown stream compression method: %d", method);
- return nullptr;
- }
-}
-
-void grpc_stream_compression_context_destroy(
- grpc_stream_compression_context* ctx) {
- ctx->vtable->context_destroy(ctx);
-}
-
-int grpc_stream_compression_method_parse(
- grpc_slice value, bool is_compress,
- grpc_stream_compression_method* method) {
+
+extern const grpc_stream_compression_vtable
+ grpc_stream_compression_identity_vtable;
+
+bool grpc_stream_compress(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) {
+ return ctx->vtable->compress(ctx, in, out, output_size, max_output_size,
+ flush);
+}
+
+bool grpc_stream_decompress(grpc_stream_compression_context* ctx,
+ grpc_slice_buffer* in, grpc_slice_buffer* out,
+ size_t* output_size, size_t max_output_size,
+ bool* end_of_context) {
+ return ctx->vtable->decompress(ctx, in, out, output_size, max_output_size,
+ end_of_context);
+}
+
+grpc_stream_compression_context* grpc_stream_compression_context_create(
+ grpc_stream_compression_method method) {
+ switch (method) {
+ case GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS:
+ case GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS:
+ return grpc_stream_compression_identity_vtable.context_create(method);
+ case GRPC_STREAM_COMPRESSION_GZIP_COMPRESS:
+ case GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS:
+ return grpc_stream_compression_gzip_vtable.context_create(method);
+ default:
+ gpr_log(GPR_ERROR, "Unknown stream compression method: %d", method);
+ return nullptr;
+ }
+}
+
+void grpc_stream_compression_context_destroy(
+ grpc_stream_compression_context* ctx) {
+ ctx->vtable->context_destroy(ctx);
+}
+
+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)) {
- *method = is_compress ? GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS
- : GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS;
- return 1;
+ *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)) {
- *method = is_compress ? GRPC_STREAM_COMPRESSION_GZIP_COMPRESS
- : GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS;
- return 1;
- } else {
- return 0;
- }
-}
+ *method = is_compress ? GRPC_STREAM_COMPRESSION_GZIP_COMPRESS
+ : GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS;
+ return 1;
+ } else {
+ return 0;
+ }
+}
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 7328c3ec0f2..fe1bddd62d4 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression.h
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression.h
@@ -1,116 +1,116 @@
-/*
- *
- * 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_COMPRESSION_STREAM_COMPRESSION_H
-#define GRPC_CORE_LIB_COMPRESSION_STREAM_COMPRESSION_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include <grpc/slice_buffer.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_COMPRESSION_STREAM_COMPRESSION_H
+#define GRPC_CORE_LIB_COMPRESSION_STREAM_COMPRESSION_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include <grpc/slice_buffer.h>
#include <zlib.h>
-
-#include "src/core/lib/transport/static_metadata.h"
-
-typedef struct grpc_stream_compression_vtable grpc_stream_compression_vtable;
-
-/* Stream compression/decompression context */
-typedef struct grpc_stream_compression_context {
- const grpc_stream_compression_vtable* vtable;
-} grpc_stream_compression_context;
-
-typedef enum grpc_stream_compression_method {
- GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS = 0,
- GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS,
- GRPC_STREAM_COMPRESSION_GZIP_COMPRESS,
- GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS,
- GRPC_STREAM_COMPRESSION_METHOD_COUNT
-} grpc_stream_compression_method;
-
-typedef enum grpc_stream_compression_flush {
- GRPC_STREAM_COMPRESSION_FLUSH_NONE = 0,
- GRPC_STREAM_COMPRESSION_FLUSH_SYNC,
- GRPC_STREAM_COMPRESSION_FLUSH_FINISH,
- GRPC_STREAM_COMPRESSION_FLUSH_COUNT
-} grpc_stream_compression_flush;
-
-struct grpc_stream_compression_vtable {
- bool (*compress)(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);
- bool (*decompress)(grpc_stream_compression_context* ctx,
- grpc_slice_buffer* in, grpc_slice_buffer* out,
- size_t* output_size, size_t max_output_size,
- bool* end_of_context);
- grpc_stream_compression_context* (*context_create)(
- grpc_stream_compression_method method);
- void (*context_destroy)(grpc_stream_compression_context* ctx);
-};
-
-/**
- * Compress bytes provided in \a in with a given context, with an optional flush
- * 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
+
+#include "src/core/lib/transport/static_metadata.h"
+
+typedef struct grpc_stream_compression_vtable grpc_stream_compression_vtable;
+
+/* Stream compression/decompression context */
+typedef struct grpc_stream_compression_context {
+ const grpc_stream_compression_vtable* vtable;
+} grpc_stream_compression_context;
+
+typedef enum grpc_stream_compression_method {
+ GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS = 0,
+ GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS,
+ GRPC_STREAM_COMPRESSION_GZIP_COMPRESS,
+ GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS,
+ GRPC_STREAM_COMPRESSION_METHOD_COUNT
+} grpc_stream_compression_method;
+
+typedef enum grpc_stream_compression_flush {
+ GRPC_STREAM_COMPRESSION_FLUSH_NONE = 0,
+ GRPC_STREAM_COMPRESSION_FLUSH_SYNC,
+ GRPC_STREAM_COMPRESSION_FLUSH_FINISH,
+ GRPC_STREAM_COMPRESSION_FLUSH_COUNT
+} grpc_stream_compression_flush;
+
+struct grpc_stream_compression_vtable {
+ bool (*compress)(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);
+ bool (*decompress)(grpc_stream_compression_context* ctx,
+ grpc_slice_buffer* in, grpc_slice_buffer* out,
+ size_t* output_size, size_t max_output_size,
+ bool* end_of_context);
+ grpc_stream_compression_context* (*context_create)(
+ grpc_stream_compression_method method);
+ void (*context_destroy)(grpc_stream_compression_context* ctx);
+};
+
+/**
+ * Compress bytes provided in \a in with a given context, with an optional flush
+ * 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.
- *
- * 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
- * compression will not be dependent on the state of the current context and any
- * previous compressed bytes. It allows corresponding decompression context to
- * be dropped when reaching this boundary.
- */
-bool grpc_stream_compress(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);
-
-/**
- * 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
+ *
+ * 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
+ * compression will not be dependent on the state of the current context and any
+ * previous compressed bytes. It allows corresponding decompression context to
+ * be dropped when reaching this boundary.
+ */
+bool grpc_stream_compress(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);
+
+/**
+ * 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
- * output_size.
- */
-bool grpc_stream_decompress(grpc_stream_compression_context* ctx,
- grpc_slice_buffer* in, grpc_slice_buffer* out,
- size_t* output_size, size_t max_output_size,
- bool* end_of_context);
-
-/**
- * Creates a stream compression context. \a pending_bytes_buffer is the input
- * buffer for compression/decompression operations. \a method specifies whether
- * the context is for compression or decompression.
- */
-grpc_stream_compression_context* grpc_stream_compression_context_create(
- grpc_stream_compression_method method);
-
-/**
- * Destroys a stream compression context.
- */
-void grpc_stream_compression_context_destroy(
- grpc_stream_compression_context* ctx);
-
-/**
- * Parse stream compression method based on algorithm name
- */
-int grpc_stream_compression_method_parse(
- grpc_slice value, bool is_compress, grpc_stream_compression_method* method);
-
-#endif
+ * output_size.
+ */
+bool grpc_stream_decompress(grpc_stream_compression_context* ctx,
+ grpc_slice_buffer* in, grpc_slice_buffer* out,
+ size_t* output_size, size_t max_output_size,
+ bool* end_of_context);
+
+/**
+ * Creates a stream compression context. \a pending_bytes_buffer is the input
+ * buffer for compression/decompression operations. \a method specifies whether
+ * the context is for compression or decompression.
+ */
+grpc_stream_compression_context* grpc_stream_compression_context_create(
+ grpc_stream_compression_method method);
+
+/**
+ * Destroys a stream compression context.
+ */
+void grpc_stream_compression_context_destroy(
+ grpc_stream_compression_context* ctx);
+
+/**
+ * Parse stream compression method based on algorithm name
+ */
+int grpc_stream_compression_method_parse(
+ grpc_slice value, bool is_compress, grpc_stream_compression_method* method);
+
+#endif
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 452b22b7628..d1846cb0cbc 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
@@ -1,230 +1,230 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/compression/stream_compression_gzip.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-#define OUTPUT_BLOCK_SIZE (1024)
-
-typedef struct grpc_stream_compression_context_gzip {
- grpc_stream_compression_context base;
-
- z_stream zs;
- int (*flate)(z_stream* zs, int flush);
-} grpc_stream_compression_context_gzip;
-
-static bool gzip_flate(grpc_stream_compression_context_gzip* ctx,
- grpc_slice_buffer* in, grpc_slice_buffer* out,
- size_t* output_size, size_t max_output_size, int flush,
- bool* end_of_context) {
- GPR_ASSERT(flush == 0 || flush == Z_SYNC_FLUSH || flush == Z_FINISH);
- /* Full flush is not allowed when inflating. */
- GPR_ASSERT(!(ctx->flate == inflate && (flush == Z_FINISH)));
-
- grpc_core::ExecCtx exec_ctx;
- int r;
- bool eoc = false;
- size_t original_max_output_size = max_output_size;
- while (max_output_size > 0 && (in->length > 0 || flush) && !eoc) {
- size_t slice_size = max_output_size < OUTPUT_BLOCK_SIZE ? max_output_size
- : OUTPUT_BLOCK_SIZE;
- grpc_slice slice_out = GRPC_SLICE_MALLOC(slice_size);
- 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) {
+/*
+ *
+ * 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 <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/compression/stream_compression_gzip.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+#define OUTPUT_BLOCK_SIZE (1024)
+
+typedef struct grpc_stream_compression_context_gzip {
+ grpc_stream_compression_context base;
+
+ z_stream zs;
+ int (*flate)(z_stream* zs, int flush);
+} grpc_stream_compression_context_gzip;
+
+static bool gzip_flate(grpc_stream_compression_context_gzip* ctx,
+ grpc_slice_buffer* in, grpc_slice_buffer* out,
+ size_t* output_size, size_t max_output_size, int flush,
+ bool* end_of_context) {
+ GPR_ASSERT(flush == 0 || flush == Z_SYNC_FLUSH || flush == Z_FINISH);
+ /* Full flush is not allowed when inflating. */
+ GPR_ASSERT(!(ctx->flate == inflate && (flush == Z_FINISH)));
+
+ grpc_core::ExecCtx exec_ctx;
+ int r;
+ bool eoc = false;
+ size_t original_max_output_size = max_output_size;
+ while (max_output_size > 0 && (in->length > 0 || flush) && !eoc) {
+ size_t slice_size = max_output_size < OUTPUT_BLOCK_SIZE ? max_output_size
+ : OUTPUT_BLOCK_SIZE;
+ grpc_slice slice_out = GRPC_SLICE_MALLOC(slice_size);
+ 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);
- 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);
+ 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);
- return false;
- } else if (r == Z_STREAM_END && ctx->flate == inflate) {
- eoc = true;
- }
- if (ctx->zs.avail_in > 0) {
+ 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);
- }
- }
- if (flush != 0 && ctx->zs.avail_out > 0 && !eoc) {
- GPR_ASSERT(in->length == 0);
- r = ctx->flate(&ctx->zs, flush);
- if (flush == Z_SYNC_FLUSH) {
- switch (r) {
- case Z_OK:
- /* Maybe flush is not complete; just made some partial progress. */
- if (ctx->zs.avail_out > 0) {
- flush = 0;
- }
- break;
- case Z_BUF_ERROR:
- case Z_STREAM_END:
- flush = 0;
- break;
- default:
- gpr_log(GPR_ERROR, "zlib error (%d)", r);
- grpc_slice_unref_internal(slice_out);
-
- return false;
- }
- } else if (flush == Z_FINISH) {
- switch (r) {
- case Z_OK:
- case Z_BUF_ERROR:
- /* Wait for the next loop to assign additional output space. */
- GPR_ASSERT(ctx->zs.avail_out == 0);
- break;
- case Z_STREAM_END:
- flush = 0;
- break;
- default:
- gpr_log(GPR_ERROR, "zlib error (%d)", r);
- grpc_slice_unref_internal(slice_out);
-
- return false;
- }
- }
- }
-
- if (ctx->zs.avail_out == 0) {
- grpc_slice_buffer_add(out, slice_out);
- } else if (ctx->zs.avail_out < slice_size) {
- size_t len = GRPC_SLICE_LENGTH(slice_out);
- GRPC_SLICE_SET_LENGTH(slice_out, len - ctx->zs.avail_out);
- grpc_slice_buffer_add(out, slice_out);
- } else {
- grpc_slice_unref_internal(slice_out);
- }
- max_output_size -= (slice_size - ctx->zs.avail_out);
- }
-
- if (end_of_context) {
- *end_of_context = eoc;
- }
- if (output_size) {
- *output_size = original_max_output_size - max_output_size;
- }
- return true;
-}
-
-static bool grpc_stream_compress_gzip(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;
- }
- grpc_stream_compression_context_gzip* gzip_ctx =
- reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx);
- GPR_ASSERT(gzip_ctx->flate == deflate);
- int gzip_flush;
- switch (flush) {
- case GRPC_STREAM_COMPRESSION_FLUSH_NONE:
- gzip_flush = 0;
- break;
- case GRPC_STREAM_COMPRESSION_FLUSH_SYNC:
- gzip_flush = Z_SYNC_FLUSH;
- break;
- case GRPC_STREAM_COMPRESSION_FLUSH_FINISH:
- gzip_flush = Z_FINISH;
- break;
- default:
- gzip_flush = 0;
- }
- return gzip_flate(gzip_ctx, in, out, output_size, max_output_size, gzip_flush,
- nullptr);
-}
-
-static bool grpc_stream_decompress_gzip(grpc_stream_compression_context* ctx,
- grpc_slice_buffer* in,
- grpc_slice_buffer* out,
- size_t* output_size,
- size_t max_output_size,
- bool* end_of_context) {
- if (ctx == nullptr) {
- return false;
- }
- grpc_stream_compression_context_gzip* gzip_ctx =
- reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx);
- GPR_ASSERT(gzip_ctx->flate == inflate);
- return gzip_flate(gzip_ctx, in, out, output_size, max_output_size,
- Z_SYNC_FLUSH, end_of_context);
-}
-
-static grpc_stream_compression_context*
-grpc_stream_compression_context_create_gzip(
- grpc_stream_compression_method method) {
- GPR_ASSERT(method == GRPC_STREAM_COMPRESSION_GZIP_COMPRESS ||
- method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS);
- grpc_stream_compression_context_gzip* gzip_ctx =
- static_cast<grpc_stream_compression_context_gzip*>(
- gpr_zalloc(sizeof(grpc_stream_compression_context_gzip)));
- int r;
- if (gzip_ctx == nullptr) {
- return nullptr;
- }
- if (method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS) {
- r = inflateInit2(&gzip_ctx->zs, 0x1F);
- gzip_ctx->flate = inflate;
- } else {
- r = deflateInit2(&gzip_ctx->zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 0x1F, 8,
- Z_DEFAULT_STRATEGY);
- gzip_ctx->flate = deflate;
- }
- if (r != Z_OK) {
- gpr_free(gzip_ctx);
- return nullptr;
- }
-
- gzip_ctx->base.vtable = &grpc_stream_compression_gzip_vtable;
- return reinterpret_cast<grpc_stream_compression_context*>(gzip_ctx);
-}
-
-static void grpc_stream_compression_context_destroy_gzip(
- grpc_stream_compression_context* ctx) {
- if (ctx == nullptr) {
- return;
- }
- grpc_stream_compression_context_gzip* gzip_ctx =
- reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx);
- if (gzip_ctx->flate == inflate) {
- inflateEnd(&gzip_ctx->zs);
- } else {
- deflateEnd(&gzip_ctx->zs);
- }
- gpr_free(ctx);
-}
-
-const grpc_stream_compression_vtable grpc_stream_compression_gzip_vtable = {
- grpc_stream_compress_gzip, grpc_stream_decompress_gzip,
- grpc_stream_compression_context_create_gzip,
- grpc_stream_compression_context_destroy_gzip};
+ }
+ }
+ if (flush != 0 && ctx->zs.avail_out > 0 && !eoc) {
+ GPR_ASSERT(in->length == 0);
+ r = ctx->flate(&ctx->zs, flush);
+ if (flush == Z_SYNC_FLUSH) {
+ switch (r) {
+ case Z_OK:
+ /* Maybe flush is not complete; just made some partial progress. */
+ if (ctx->zs.avail_out > 0) {
+ flush = 0;
+ }
+ break;
+ case Z_BUF_ERROR:
+ case Z_STREAM_END:
+ flush = 0;
+ break;
+ default:
+ gpr_log(GPR_ERROR, "zlib error (%d)", r);
+ grpc_slice_unref_internal(slice_out);
+
+ return false;
+ }
+ } else if (flush == Z_FINISH) {
+ switch (r) {
+ case Z_OK:
+ case Z_BUF_ERROR:
+ /* Wait for the next loop to assign additional output space. */
+ GPR_ASSERT(ctx->zs.avail_out == 0);
+ break;
+ case Z_STREAM_END:
+ flush = 0;
+ break;
+ default:
+ gpr_log(GPR_ERROR, "zlib error (%d)", r);
+ grpc_slice_unref_internal(slice_out);
+
+ return false;
+ }
+ }
+ }
+
+ if (ctx->zs.avail_out == 0) {
+ grpc_slice_buffer_add(out, slice_out);
+ } else if (ctx->zs.avail_out < slice_size) {
+ size_t len = GRPC_SLICE_LENGTH(slice_out);
+ GRPC_SLICE_SET_LENGTH(slice_out, len - ctx->zs.avail_out);
+ grpc_slice_buffer_add(out, slice_out);
+ } else {
+ grpc_slice_unref_internal(slice_out);
+ }
+ max_output_size -= (slice_size - ctx->zs.avail_out);
+ }
+
+ if (end_of_context) {
+ *end_of_context = eoc;
+ }
+ if (output_size) {
+ *output_size = original_max_output_size - max_output_size;
+ }
+ return true;
+}
+
+static bool grpc_stream_compress_gzip(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;
+ }
+ grpc_stream_compression_context_gzip* gzip_ctx =
+ reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx);
+ GPR_ASSERT(gzip_ctx->flate == deflate);
+ int gzip_flush;
+ switch (flush) {
+ case GRPC_STREAM_COMPRESSION_FLUSH_NONE:
+ gzip_flush = 0;
+ break;
+ case GRPC_STREAM_COMPRESSION_FLUSH_SYNC:
+ gzip_flush = Z_SYNC_FLUSH;
+ break;
+ case GRPC_STREAM_COMPRESSION_FLUSH_FINISH:
+ gzip_flush = Z_FINISH;
+ break;
+ default:
+ gzip_flush = 0;
+ }
+ return gzip_flate(gzip_ctx, in, out, output_size, max_output_size, gzip_flush,
+ nullptr);
+}
+
+static bool grpc_stream_decompress_gzip(grpc_stream_compression_context* ctx,
+ grpc_slice_buffer* in,
+ grpc_slice_buffer* out,
+ size_t* output_size,
+ size_t max_output_size,
+ bool* end_of_context) {
+ if (ctx == nullptr) {
+ return false;
+ }
+ grpc_stream_compression_context_gzip* gzip_ctx =
+ reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx);
+ GPR_ASSERT(gzip_ctx->flate == inflate);
+ return gzip_flate(gzip_ctx, in, out, output_size, max_output_size,
+ Z_SYNC_FLUSH, end_of_context);
+}
+
+static grpc_stream_compression_context*
+grpc_stream_compression_context_create_gzip(
+ grpc_stream_compression_method method) {
+ GPR_ASSERT(method == GRPC_STREAM_COMPRESSION_GZIP_COMPRESS ||
+ method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS);
+ grpc_stream_compression_context_gzip* gzip_ctx =
+ static_cast<grpc_stream_compression_context_gzip*>(
+ gpr_zalloc(sizeof(grpc_stream_compression_context_gzip)));
+ int r;
+ if (gzip_ctx == nullptr) {
+ return nullptr;
+ }
+ if (method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS) {
+ r = inflateInit2(&gzip_ctx->zs, 0x1F);
+ gzip_ctx->flate = inflate;
+ } else {
+ r = deflateInit2(&gzip_ctx->zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 0x1F, 8,
+ Z_DEFAULT_STRATEGY);
+ gzip_ctx->flate = deflate;
+ }
+ if (r != Z_OK) {
+ gpr_free(gzip_ctx);
+ return nullptr;
+ }
+
+ gzip_ctx->base.vtable = &grpc_stream_compression_gzip_vtable;
+ return reinterpret_cast<grpc_stream_compression_context*>(gzip_ctx);
+}
+
+static void grpc_stream_compression_context_destroy_gzip(
+ grpc_stream_compression_context* ctx) {
+ if (ctx == nullptr) {
+ return;
+ }
+ grpc_stream_compression_context_gzip* gzip_ctx =
+ reinterpret_cast<grpc_stream_compression_context_gzip*>(ctx);
+ if (gzip_ctx->flate == inflate) {
+ inflateEnd(&gzip_ctx->zs);
+ } else {
+ deflateEnd(&gzip_ctx->zs);
+ }
+ gpr_free(ctx);
+}
+
+const grpc_stream_compression_vtable grpc_stream_compression_gzip_vtable = {
+ grpc_stream_compress_gzip, grpc_stream_decompress_gzip,
+ grpc_stream_compression_context_create_gzip,
+ grpc_stream_compression_context_destroy_gzip};
diff --git a/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.h b/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.h
index 740f09734a6..2e9b34ddc6f 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.h
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression_gzip.h
@@ -1,28 +1,28 @@
-/*
- *
- * 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_COMPRESSION_STREAM_COMPRESSION_GZIP_H
-#define GRPC_CORE_LIB_COMPRESSION_STREAM_COMPRESSION_GZIP_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/compression/stream_compression.h"
-
-extern const grpc_stream_compression_vtable grpc_stream_compression_gzip_vtable;
-
-#endif
+/*
+ *
+ * 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_COMPRESSION_STREAM_COMPRESSION_GZIP_H
+#define GRPC_CORE_LIB_COMPRESSION_STREAM_COMPRESSION_GZIP_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/compression/stream_compression.h"
+
+extern const grpc_stream_compression_vtable grpc_stream_compression_gzip_vtable;
+
+#endif
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 d5e3afff052..9d6f69fecdf 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
@@ -1,92 +1,92 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/compression/stream_compression_identity.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-#define OUTPUT_BLOCK_SIZE (1024)
-
-/* Singleton context used for all identity streams. */
-static grpc_stream_compression_context identity_ctx = {
- &grpc_stream_compression_identity_vtable};
-
-static void grpc_stream_compression_pass_through(grpc_slice_buffer* in,
- grpc_slice_buffer* out,
- size_t* output_size,
- size_t max_output_size) {
- if (max_output_size >= in->length) {
- if (output_size) {
- *output_size = in->length;
- }
- grpc_slice_buffer_move_into(in, out);
- } else {
- if (output_size) {
- *output_size = max_output_size;
- }
- grpc_slice_buffer_move_first(in, max_output_size, out);
- }
-}
-
+/*
+ *
+ * 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 <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/compression/stream_compression_identity.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+#define OUTPUT_BLOCK_SIZE (1024)
+
+/* Singleton context used for all identity streams. */
+static grpc_stream_compression_context identity_ctx = {
+ &grpc_stream_compression_identity_vtable};
+
+static void grpc_stream_compression_pass_through(grpc_slice_buffer* in,
+ grpc_slice_buffer* out,
+ size_t* output_size,
+ size_t max_output_size) {
+ if (max_output_size >= in->length) {
+ if (output_size) {
+ *output_size = in->length;
+ }
+ grpc_slice_buffer_move_into(in, out);
+ } else {
+ if (output_size) {
+ *output_size = max_output_size;
+ }
+ grpc_slice_buffer_move_first(in, max_output_size, out);
+ }
+}
+
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;
- }
- grpc_stream_compression_pass_through(in, out, output_size, max_output_size);
- return true;
-}
-
-static bool grpc_stream_decompress_identity(
- grpc_stream_compression_context* ctx, grpc_slice_buffer* in,
- grpc_slice_buffer* out, size_t* output_size, size_t max_output_size,
- bool* end_of_context) {
- if (ctx == nullptr) {
- return false;
- }
- grpc_stream_compression_pass_through(in, out, output_size, max_output_size);
- if (end_of_context) {
- *end_of_context = false;
- }
- return true;
-}
-
-static grpc_stream_compression_context*
-grpc_stream_compression_context_create_identity(
- grpc_stream_compression_method method) {
- GPR_ASSERT(method == GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS ||
- method == GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS);
- /* No context needed in this case. Use fake context instead. */
- return &identity_ctx;
-}
-
-static void grpc_stream_compression_context_destroy_identity(
+ if (ctx == nullptr) {
+ return false;
+ }
+ grpc_stream_compression_pass_through(in, out, output_size, max_output_size);
+ return true;
+}
+
+static bool grpc_stream_decompress_identity(
+ grpc_stream_compression_context* ctx, grpc_slice_buffer* in,
+ grpc_slice_buffer* out, size_t* output_size, size_t max_output_size,
+ bool* end_of_context) {
+ if (ctx == nullptr) {
+ return false;
+ }
+ grpc_stream_compression_pass_through(in, out, output_size, max_output_size);
+ if (end_of_context) {
+ *end_of_context = false;
+ }
+ return true;
+}
+
+static grpc_stream_compression_context*
+grpc_stream_compression_context_create_identity(
+ grpc_stream_compression_method method) {
+ GPR_ASSERT(method == GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS ||
+ method == GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS);
+ /* No context needed in this case. Use fake context instead. */
+ return &identity_ctx;
+}
+
+static void grpc_stream_compression_context_destroy_identity(
grpc_stream_compression_context* /*ctx*/) {
- return;
-}
-
-const grpc_stream_compression_vtable grpc_stream_compression_identity_vtable = {
- grpc_stream_compress_identity, grpc_stream_decompress_identity,
- grpc_stream_compression_context_create_identity,
- grpc_stream_compression_context_destroy_identity};
+ return;
+}
+
+const grpc_stream_compression_vtable grpc_stream_compression_identity_vtable = {
+ grpc_stream_compress_identity, grpc_stream_decompress_identity,
+ grpc_stream_compression_context_create_identity,
+ grpc_stream_compression_context_destroy_identity};
diff --git a/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.h b/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.h
index cc77b63ecdf..92379042a41 100644
--- a/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.h
+++ b/contrib/libs/grpc/src/core/lib/compression/stream_compression_identity.h
@@ -1,29 +1,29 @@
-/*
- *
- * 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_COMPRESSION_STREAM_COMPRESSION_IDENTITY_H
-#define GRPC_CORE_LIB_COMPRESSION_STREAM_COMPRESSION_IDENTITY_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/compression/stream_compression.h"
-
-extern const grpc_stream_compression_vtable
- grpc_stream_compression_identity_vtable;
-
-#endif
+/*
+ *
+ * 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_COMPRESSION_STREAM_COMPRESSION_IDENTITY_H
+#define GRPC_CORE_LIB_COMPRESSION_STREAM_COMPRESSION_IDENTITY_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/compression/stream_compression.h"
+
+extern const grpc_stream_compression_vtable
+ grpc_stream_compression_identity_vtable;
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/debug/stats.cc b/contrib/libs/grpc/src/core/lib/debug/stats.cc
index 1bcd1af25a2..4e98f20b1d2 100644
--- a/contrib/libs/grpc/src/core/lib/debug/stats.cc
+++ b/contrib/libs/grpc/src/core/lib/debug/stats.cc
@@ -1,172 +1,172 @@
-/*
- *
- * 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/debug/stats.h"
-
-#include <inttypes.h>
-#include <string.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/debug/stats.h"
+
+#include <inttypes.h>
+#include <string.h>
+
#include <vector>
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
-
-grpc_stats_data* grpc_stats_per_cpu_storage = nullptr;
-static size_t g_num_cores;
-
-void grpc_stats_init(void) {
- g_num_cores = GPR_MAX(1, gpr_cpu_num_cores());
- grpc_stats_per_cpu_storage = static_cast<grpc_stats_data*>(
- gpr_zalloc(sizeof(grpc_stats_data) * g_num_cores));
-}
-
-void grpc_stats_shutdown(void) { gpr_free(grpc_stats_per_cpu_storage); }
-
-void grpc_stats_collect(grpc_stats_data* output) {
- memset(output, 0, sizeof(*output));
- for (size_t core = 0; core < g_num_cores; core++) {
- for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
- output->counters[i] += gpr_atm_no_barrier_load(
- &grpc_stats_per_cpu_storage[core].counters[i]);
- }
- for (size_t i = 0; i < GRPC_STATS_HISTOGRAM_BUCKETS; i++) {
- output->histograms[i] += gpr_atm_no_barrier_load(
- &grpc_stats_per_cpu_storage[core].histograms[i]);
- }
- }
-}
-
-void grpc_stats_diff(const grpc_stats_data* b, const grpc_stats_data* a,
- grpc_stats_data* c) {
- for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
- c->counters[i] = b->counters[i] - a->counters[i];
- }
- for (size_t i = 0; i < GRPC_STATS_HISTOGRAM_BUCKETS; i++) {
- c->histograms[i] = b->histograms[i] - a->histograms[i];
- }
-}
-
-int grpc_stats_histo_find_bucket_slow(int value, const int* table,
- int table_size) {
- GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS();
- const int* const start = table;
- while (table_size > 0) {
- int step = table_size / 2;
- const int* it = table + step;
- if (value >= *it) {
- table = it + 1;
- table_size -= step + 1;
- } else {
- table_size = step;
- }
- }
- return static_cast<int>(table - start) - 1;
-}
-
-size_t grpc_stats_histo_count(const grpc_stats_data* stats,
- grpc_stats_histograms histogram) {
- size_t sum = 0;
- for (int i = 0; i < grpc_stats_histo_buckets[histogram]; i++) {
- sum += static_cast<size_t>(
- stats->histograms[grpc_stats_histo_start[histogram] + i]);
- }
- return sum;
-}
-
-static double threshold_for_count_below(const gpr_atm* bucket_counts,
- const int* bucket_boundaries,
- int num_buckets, double count_below) {
- double count_so_far;
- double lower_bound;
- double upper_bound;
- int lower_idx;
- int upper_idx;
-
- /* find the lowest bucket that gets us above count_below */
- count_so_far = 0.0;
- for (lower_idx = 0; lower_idx < num_buckets; lower_idx++) {
- count_so_far += static_cast<double>(bucket_counts[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 < num_buckets; upper_idx++) {
- if (bucket_counts[upper_idx]) {
- break;
- }
- }
- return (bucket_boundaries[lower_idx] + bucket_boundaries[upper_idx]) / 2.0;
- } else {
- /* treat values as uniform throughout the bucket, and find where this value
- should lie */
- lower_bound = bucket_boundaries[lower_idx];
- upper_bound = bucket_boundaries[lower_idx + 1];
- return upper_bound - (upper_bound - lower_bound) *
- (count_so_far - count_below) /
- static_cast<double>(bucket_counts[lower_idx]);
- }
-}
-
-double grpc_stats_histo_percentile(const grpc_stats_data* stats,
- grpc_stats_histograms histogram,
- double percentile) {
- size_t count = grpc_stats_histo_count(stats, histogram);
- if (count == 0) return 0.0;
- return threshold_for_count_below(
- stats->histograms + grpc_stats_histo_start[histogram],
- grpc_stats_histo_bucket_boundaries[histogram],
- grpc_stats_histo_buckets[histogram],
- static_cast<double>(count) * percentile / 100.0);
-}
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
+
+grpc_stats_data* grpc_stats_per_cpu_storage = nullptr;
+static size_t g_num_cores;
+
+void grpc_stats_init(void) {
+ g_num_cores = GPR_MAX(1, gpr_cpu_num_cores());
+ grpc_stats_per_cpu_storage = static_cast<grpc_stats_data*>(
+ gpr_zalloc(sizeof(grpc_stats_data) * g_num_cores));
+}
+
+void grpc_stats_shutdown(void) { gpr_free(grpc_stats_per_cpu_storage); }
+
+void grpc_stats_collect(grpc_stats_data* output) {
+ memset(output, 0, sizeof(*output));
+ for (size_t core = 0; core < g_num_cores; core++) {
+ for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
+ output->counters[i] += gpr_atm_no_barrier_load(
+ &grpc_stats_per_cpu_storage[core].counters[i]);
+ }
+ for (size_t i = 0; i < GRPC_STATS_HISTOGRAM_BUCKETS; i++) {
+ output->histograms[i] += gpr_atm_no_barrier_load(
+ &grpc_stats_per_cpu_storage[core].histograms[i]);
+ }
+ }
+}
+
+void grpc_stats_diff(const grpc_stats_data* b, const grpc_stats_data* a,
+ grpc_stats_data* c) {
+ for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
+ c->counters[i] = b->counters[i] - a->counters[i];
+ }
+ for (size_t i = 0; i < GRPC_STATS_HISTOGRAM_BUCKETS; i++) {
+ c->histograms[i] = b->histograms[i] - a->histograms[i];
+ }
+}
+
+int grpc_stats_histo_find_bucket_slow(int value, const int* table,
+ int table_size) {
+ GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS();
+ const int* const start = table;
+ while (table_size > 0) {
+ int step = table_size / 2;
+ const int* it = table + step;
+ if (value >= *it) {
+ table = it + 1;
+ table_size -= step + 1;
+ } else {
+ table_size = step;
+ }
+ }
+ return static_cast<int>(table - start) - 1;
+}
+
+size_t grpc_stats_histo_count(const grpc_stats_data* stats,
+ grpc_stats_histograms histogram) {
+ size_t sum = 0;
+ for (int i = 0; i < grpc_stats_histo_buckets[histogram]; i++) {
+ sum += static_cast<size_t>(
+ stats->histograms[grpc_stats_histo_start[histogram] + i]);
+ }
+ return sum;
+}
+
+static double threshold_for_count_below(const gpr_atm* bucket_counts,
+ const int* bucket_boundaries,
+ int num_buckets, double count_below) {
+ double count_so_far;
+ double lower_bound;
+ double upper_bound;
+ int lower_idx;
+ int upper_idx;
+
+ /* find the lowest bucket that gets us above count_below */
+ count_so_far = 0.0;
+ for (lower_idx = 0; lower_idx < num_buckets; lower_idx++) {
+ count_so_far += static_cast<double>(bucket_counts[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 < num_buckets; upper_idx++) {
+ if (bucket_counts[upper_idx]) {
+ break;
+ }
+ }
+ return (bucket_boundaries[lower_idx] + bucket_boundaries[upper_idx]) / 2.0;
+ } else {
+ /* treat values as uniform throughout the bucket, and find where this value
+ should lie */
+ lower_bound = bucket_boundaries[lower_idx];
+ upper_bound = bucket_boundaries[lower_idx + 1];
+ return upper_bound - (upper_bound - lower_bound) *
+ (count_so_far - count_below) /
+ static_cast<double>(bucket_counts[lower_idx]);
+ }
+}
+
+double grpc_stats_histo_percentile(const grpc_stats_data* stats,
+ grpc_stats_histograms histogram,
+ double percentile) {
+ size_t count = grpc_stats_histo_count(stats, histogram);
+ if (count == 0) return 0.0;
+ return threshold_for_count_below(
+ stats->histograms + grpc_stats_histo_start[histogram],
+ grpc_stats_histo_bucket_boundaries[histogram],
+ grpc_stats_histo_buckets[histogram],
+ static_cast<double>(count) * percentile / 100.0);
+}
+
TString grpc_stats_data_as_json(const grpc_stats_data* data) {
std::vector<TString> parts;
parts.push_back("{");
- for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
+ for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) {
parts.push_back(y_absl::StrFormat(
"\"%s\": %" PRIdPTR, grpc_stats_counter_name[i], data->counters[i]));
- }
- for (size_t i = 0; i < GRPC_STATS_HISTOGRAM_COUNT; i++) {
+ }
+ for (size_t i = 0; i < GRPC_STATS_HISTOGRAM_COUNT; i++) {
parts.push_back(y_absl::StrFormat("\"%s\": [", grpc_stats_histogram_name[i]));
- for (int j = 0; j < grpc_stats_histo_buckets[i]; j++) {
+ for (int j = 0; j < grpc_stats_histo_buckets[i]; j++) {
parts.push_back(
y_absl::StrFormat("%s%" PRIdPTR, j == 0 ? "" : ",",
data->histograms[grpc_stats_histo_start[i] + j]));
- }
+ }
parts.push_back(
y_absl::StrFormat("], \"%s_bkt\": [", grpc_stats_histogram_name[i]));
- for (int j = 0; j < grpc_stats_histo_buckets[i]; j++) {
+ for (int j = 0; j < grpc_stats_histo_buckets[i]; j++) {
parts.push_back(y_absl::StrFormat(
"%s%d", j == 0 ? "" : ",", grpc_stats_histo_bucket_boundaries[i][j]));
- }
+ }
parts.push_back("]");
- }
+ }
parts.push_back("}");
return y_absl::StrJoin(parts, "");
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/debug/stats.h b/contrib/libs/grpc/src/core/lib/debug/stats.h
index c184fa7fc70..0106803de76 100644
--- a/contrib/libs/grpc/src/core/lib/debug/stats.h
+++ b/contrib/libs/grpc/src/core/lib/debug/stats.h
@@ -1,70 +1,70 @@
-/*
- *
- * 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_DEBUG_STATS_H
-#define GRPC_CORE_LIB_DEBUG_STATS_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_DEBUG_STATS_H
+#define GRPC_CORE_LIB_DEBUG_STATS_H
+
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
-#include <grpc/support/atm.h>
-#include "src/core/lib/debug/stats_data.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-
-typedef struct grpc_stats_data {
- gpr_atm counters[GRPC_STATS_COUNTER_COUNT];
- gpr_atm histograms[GRPC_STATS_HISTOGRAM_BUCKETS];
-} grpc_stats_data;
-
-extern grpc_stats_data* grpc_stats_per_cpu_storage;
-
-#define GRPC_THREAD_STATS_DATA() \
- (&grpc_stats_per_cpu_storage[grpc_core::ExecCtx::Get()->starting_cpu()])
-
+#include <grpc/support/atm.h>
+#include "src/core/lib/debug/stats_data.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+
+typedef struct grpc_stats_data {
+ gpr_atm counters[GRPC_STATS_COUNTER_COUNT];
+ gpr_atm histograms[GRPC_STATS_HISTOGRAM_BUCKETS];
+} grpc_stats_data;
+
+extern grpc_stats_data* grpc_stats_per_cpu_storage;
+
+#define GRPC_THREAD_STATS_DATA() \
+ (&grpc_stats_per_cpu_storage[grpc_core::ExecCtx::Get()->starting_cpu()])
+
/* Only collect stats if GRPC_COLLECT_STATS is defined or it is a debug build.
*/
#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)
-#define GRPC_STATS_INC_COUNTER(ctr) \
- (gpr_atm_no_barrier_fetch_add(&GRPC_THREAD_STATS_DATA()->counters[(ctr)], 1))
-
-#define GRPC_STATS_INC_HISTOGRAM(histogram, index) \
- (gpr_atm_no_barrier_fetch_add( \
- &GRPC_THREAD_STATS_DATA()->histograms[histogram##_FIRST_SLOT + (index)], \
- 1))
+#define GRPC_STATS_INC_COUNTER(ctr) \
+ (gpr_atm_no_barrier_fetch_add(&GRPC_THREAD_STATS_DATA()->counters[(ctr)], 1))
+
+#define GRPC_STATS_INC_HISTOGRAM(histogram, index) \
+ (gpr_atm_no_barrier_fetch_add( \
+ &GRPC_THREAD_STATS_DATA()->histograms[histogram##_FIRST_SLOT + (index)], \
+ 1))
#else /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */
#define GRPC_STATS_INC_COUNTER(ctr)
#define GRPC_STATS_INC_HISTOGRAM(histogram, index)
#endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */
-
-void grpc_stats_init(void);
-void grpc_stats_shutdown(void);
-void grpc_stats_collect(grpc_stats_data* output);
-// c = b-a
-void grpc_stats_diff(const grpc_stats_data* b, const grpc_stats_data* a,
- grpc_stats_data* c);
+
+void grpc_stats_init(void);
+void grpc_stats_shutdown(void);
+void grpc_stats_collect(grpc_stats_data* output);
+// c = b-a
+void grpc_stats_diff(const grpc_stats_data* b, const grpc_stats_data* a,
+ grpc_stats_data* c);
TString grpc_stats_data_as_json(const grpc_stats_data* data);
-int grpc_stats_histo_find_bucket_slow(int value, const int* table,
- int table_size);
-double grpc_stats_histo_percentile(const grpc_stats_data* data,
- grpc_stats_histograms histogram,
- double percentile);
-size_t grpc_stats_histo_count(const grpc_stats_data* data,
- grpc_stats_histograms histogram);
-
-#endif
+int grpc_stats_histo_find_bucket_slow(int value, const int* table,
+ int table_size);
+double grpc_stats_histo_percentile(const grpc_stats_data* data,
+ grpc_stats_histograms histogram,
+ double percentile);
+size_t grpc_stats_histo_count(const grpc_stats_data* data,
+ grpc_stats_histograms histogram);
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/debug/stats_data.cc b/contrib/libs/grpc/src/core/lib/debug/stats_data.cc
index f8c27db0a81..d15d57bac92 100644
--- a/contrib/libs/grpc/src/core/lib/debug/stats_data.cc
+++ b/contrib/libs/grpc/src/core/lib/debug/stats_data.cc
@@ -1,687 +1,687 @@
-/*
- * 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.
- */
-
-/*
- * Automatically generated by tools/codegen/core/gen_stats_data.py
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/debug/stats_data.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-
-const char* grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT] = {
- "client_calls_created",
- "server_calls_created",
- "cqs_created",
- "client_channels_created",
- "client_subchannels_created",
- "server_channels_created",
- "syscall_poll",
- "syscall_wait",
- "pollset_kick",
- "pollset_kicked_without_poller",
- "pollset_kicked_again",
- "pollset_kick_wakeup_fd",
- "pollset_kick_wakeup_cv",
- "pollset_kick_own_thread",
+/*
+ * 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.
+ */
+
+/*
+ * Automatically generated by tools/codegen/core/gen_stats_data.py
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/debug/stats_data.h"
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+
+const char* grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT] = {
+ "client_calls_created",
+ "server_calls_created",
+ "cqs_created",
+ "client_channels_created",
+ "client_subchannels_created",
+ "server_channels_created",
+ "syscall_poll",
+ "syscall_wait",
+ "pollset_kick",
+ "pollset_kicked_without_poller",
+ "pollset_kicked_again",
+ "pollset_kick_wakeup_fd",
+ "pollset_kick_wakeup_cv",
+ "pollset_kick_own_thread",
"syscall_epoll_ctl",
"pollset_fd_cache_hits",
- "histogram_slow_lookups",
- "syscall_write",
- "syscall_read",
- "tcp_backup_pollers_created",
- "tcp_backup_poller_polls",
- "http2_op_batches",
- "http2_op_cancel",
- "http2_op_send_initial_metadata",
- "http2_op_send_message",
- "http2_op_send_trailing_metadata",
- "http2_op_recv_initial_metadata",
- "http2_op_recv_message",
- "http2_op_recv_trailing_metadata",
- "http2_settings_writes",
- "http2_pings_sent",
- "http2_writes_begun",
- "http2_writes_offloaded",
- "http2_writes_continued",
- "http2_partial_writes",
- "http2_initiate_write_due_to_initial_write",
- "http2_initiate_write_due_to_start_new_stream",
- "http2_initiate_write_due_to_send_message",
- "http2_initiate_write_due_to_send_initial_metadata",
- "http2_initiate_write_due_to_send_trailing_metadata",
- "http2_initiate_write_due_to_retry_send_ping",
- "http2_initiate_write_due_to_continue_pings",
- "http2_initiate_write_due_to_goaway_sent",
- "http2_initiate_write_due_to_rst_stream",
- "http2_initiate_write_due_to_close_from_api",
- "http2_initiate_write_due_to_stream_flow_control",
- "http2_initiate_write_due_to_transport_flow_control",
- "http2_initiate_write_due_to_send_settings",
- "http2_initiate_write_due_to_bdp_estimator_ping",
- "http2_initiate_write_due_to_flow_control_unstalled_by_setting",
- "http2_initiate_write_due_to_flow_control_unstalled_by_update",
- "http2_initiate_write_due_to_application_ping",
- "http2_initiate_write_due_to_keepalive_ping",
- "http2_initiate_write_due_to_transport_flow_control_unstalled",
- "http2_initiate_write_due_to_ping_response",
- "http2_initiate_write_due_to_force_rst_stream",
- "http2_spurious_writes_begun",
- "hpack_recv_indexed",
- "hpack_recv_lithdr_incidx",
- "hpack_recv_lithdr_incidx_v",
- "hpack_recv_lithdr_notidx",
- "hpack_recv_lithdr_notidx_v",
- "hpack_recv_lithdr_nvridx",
- "hpack_recv_lithdr_nvridx_v",
- "hpack_recv_uncompressed",
- "hpack_recv_huffman",
- "hpack_recv_binary",
- "hpack_recv_binary_base64",
- "hpack_send_indexed",
- "hpack_send_lithdr_incidx",
- "hpack_send_lithdr_incidx_v",
- "hpack_send_lithdr_notidx",
- "hpack_send_lithdr_notidx_v",
- "hpack_send_lithdr_nvridx",
- "hpack_send_lithdr_nvridx_v",
- "hpack_send_uncompressed",
- "hpack_send_huffman",
- "hpack_send_binary",
- "hpack_send_binary_base64",
- "combiner_locks_initiated",
- "combiner_locks_scheduled_items",
- "combiner_locks_scheduled_final_items",
- "combiner_locks_offloaded",
- "call_combiner_locks_initiated",
- "call_combiner_locks_scheduled_items",
- "call_combiner_set_notify_on_cancel",
- "call_combiner_cancelled",
- "executor_scheduled_short_items",
- "executor_scheduled_long_items",
- "executor_scheduled_to_self",
- "executor_wakeup_initiated",
- "executor_queue_drained",
- "executor_push_retries",
- "server_requested_calls",
- "server_slowpath_requests_queued",
- "cq_ev_queue_trylock_failures",
- "cq_ev_queue_trylock_successes",
- "cq_ev_queue_transient_pop_failures",
-};
-const char* grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT] = {
- "Number of client side calls created by this process",
- "Number of server side calls created by this process",
- "Number of completion queues created",
- "Number of client channels created",
- "Number of client subchannels created",
- "Number of server channels created",
- "Number of polling syscalls (epoll_wait, poll, etc) made by this process",
- "Number of sleeping syscalls made by this process",
- "How many polling wakeups were performed by the process (only valid for "
- "epoll1 right now)",
- "How many times was a polling wakeup requested without an active poller "
- "(only valid for epoll1 right now)",
- "How many times was the same polling worker awoken repeatedly before "
- "waking up (only valid for epoll1 right now)",
- "How many times was an eventfd used as the wakeup vector for a polling "
- "wakeup (only valid for epoll1 right now)",
- "How many times was a condition variable used as the wakeup vector for a "
- "polling wakeup (only valid for epoll1 right now)",
- "How many times could a polling wakeup be satisfied by keeping the waking "
- "thread awake? (only valid for epoll1 right now)",
+ "histogram_slow_lookups",
+ "syscall_write",
+ "syscall_read",
+ "tcp_backup_pollers_created",
+ "tcp_backup_poller_polls",
+ "http2_op_batches",
+ "http2_op_cancel",
+ "http2_op_send_initial_metadata",
+ "http2_op_send_message",
+ "http2_op_send_trailing_metadata",
+ "http2_op_recv_initial_metadata",
+ "http2_op_recv_message",
+ "http2_op_recv_trailing_metadata",
+ "http2_settings_writes",
+ "http2_pings_sent",
+ "http2_writes_begun",
+ "http2_writes_offloaded",
+ "http2_writes_continued",
+ "http2_partial_writes",
+ "http2_initiate_write_due_to_initial_write",
+ "http2_initiate_write_due_to_start_new_stream",
+ "http2_initiate_write_due_to_send_message",
+ "http2_initiate_write_due_to_send_initial_metadata",
+ "http2_initiate_write_due_to_send_trailing_metadata",
+ "http2_initiate_write_due_to_retry_send_ping",
+ "http2_initiate_write_due_to_continue_pings",
+ "http2_initiate_write_due_to_goaway_sent",
+ "http2_initiate_write_due_to_rst_stream",
+ "http2_initiate_write_due_to_close_from_api",
+ "http2_initiate_write_due_to_stream_flow_control",
+ "http2_initiate_write_due_to_transport_flow_control",
+ "http2_initiate_write_due_to_send_settings",
+ "http2_initiate_write_due_to_bdp_estimator_ping",
+ "http2_initiate_write_due_to_flow_control_unstalled_by_setting",
+ "http2_initiate_write_due_to_flow_control_unstalled_by_update",
+ "http2_initiate_write_due_to_application_ping",
+ "http2_initiate_write_due_to_keepalive_ping",
+ "http2_initiate_write_due_to_transport_flow_control_unstalled",
+ "http2_initiate_write_due_to_ping_response",
+ "http2_initiate_write_due_to_force_rst_stream",
+ "http2_spurious_writes_begun",
+ "hpack_recv_indexed",
+ "hpack_recv_lithdr_incidx",
+ "hpack_recv_lithdr_incidx_v",
+ "hpack_recv_lithdr_notidx",
+ "hpack_recv_lithdr_notidx_v",
+ "hpack_recv_lithdr_nvridx",
+ "hpack_recv_lithdr_nvridx_v",
+ "hpack_recv_uncompressed",
+ "hpack_recv_huffman",
+ "hpack_recv_binary",
+ "hpack_recv_binary_base64",
+ "hpack_send_indexed",
+ "hpack_send_lithdr_incidx",
+ "hpack_send_lithdr_incidx_v",
+ "hpack_send_lithdr_notidx",
+ "hpack_send_lithdr_notidx_v",
+ "hpack_send_lithdr_nvridx",
+ "hpack_send_lithdr_nvridx_v",
+ "hpack_send_uncompressed",
+ "hpack_send_huffman",
+ "hpack_send_binary",
+ "hpack_send_binary_base64",
+ "combiner_locks_initiated",
+ "combiner_locks_scheduled_items",
+ "combiner_locks_scheduled_final_items",
+ "combiner_locks_offloaded",
+ "call_combiner_locks_initiated",
+ "call_combiner_locks_scheduled_items",
+ "call_combiner_set_notify_on_cancel",
+ "call_combiner_cancelled",
+ "executor_scheduled_short_items",
+ "executor_scheduled_long_items",
+ "executor_scheduled_to_self",
+ "executor_wakeup_initiated",
+ "executor_queue_drained",
+ "executor_push_retries",
+ "server_requested_calls",
+ "server_slowpath_requests_queued",
+ "cq_ev_queue_trylock_failures",
+ "cq_ev_queue_trylock_successes",
+ "cq_ev_queue_transient_pop_failures",
+};
+const char* grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT] = {
+ "Number of client side calls created by this process",
+ "Number of server side calls created by this process",
+ "Number of completion queues created",
+ "Number of client channels created",
+ "Number of client subchannels created",
+ "Number of server channels created",
+ "Number of polling syscalls (epoll_wait, poll, etc) made by this process",
+ "Number of sleeping syscalls made by this process",
+ "How many polling wakeups were performed by the process (only valid for "
+ "epoll1 right now)",
+ "How many times was a polling wakeup requested without an active poller "
+ "(only valid for epoll1 right now)",
+ "How many times was the same polling worker awoken repeatedly before "
+ "waking up (only valid for epoll1 right now)",
+ "How many times was an eventfd used as the wakeup vector for a polling "
+ "wakeup (only valid for epoll1 right now)",
+ "How many times was a condition variable used as the wakeup vector for a "
+ "polling wakeup (only valid for epoll1 right now)",
+ "How many times could a polling wakeup be satisfied by keeping the waking "
+ "thread awake? (only valid for epoll1 right now)",
"Number of epoll_ctl calls made (only valid for epollex right now)",
"Number of epoll_ctl calls skipped because the fd was cached as already "
"being added. (only valid for epollex right now)",
- "Number of times histogram increments went through the slow (binary "
- "search) path",
- "Number of write syscalls (or equivalent - eg sendmsg) made by this "
- "process",
- "Number of read syscalls (or equivalent - eg recvmsg) made by this process",
- "Number of times a backup poller has been created (this can be expensive)",
- "Number of polls performed on the backup poller",
- "Number of batches received by HTTP2 transport",
- "Number of cancelations received by HTTP2 transport",
- "Number of batches containing send initial metadata",
- "Number of batches containing send message",
- "Number of batches containing send trailing metadata",
- "Number of batches containing receive initial metadata",
- "Number of batches containing receive message",
- "Number of batches containing receive trailing metadata",
- "Number of settings frames sent",
- "Number of HTTP2 pings sent by process",
- "Number of HTTP2 writes initiated",
- "Number of HTTP2 writes offloaded to the executor from application threads",
- "Number of HTTP2 writes that finished seeing more data needed to be "
- "written",
- "Number of HTTP2 writes that were made knowing there was still more data "
- "to be written (we cap maximum write size to syscall_write)",
- "Number of HTTP2 writes initiated due to 'initial_write'",
- "Number of HTTP2 writes initiated due to 'start_new_stream'",
- "Number of HTTP2 writes initiated due to 'send_message'",
- "Number of HTTP2 writes initiated due to 'send_initial_metadata'",
- "Number of HTTP2 writes initiated due to 'send_trailing_metadata'",
- "Number of HTTP2 writes initiated due to 'retry_send_ping'",
- "Number of HTTP2 writes initiated due to 'continue_pings'",
- "Number of HTTP2 writes initiated due to 'goaway_sent'",
- "Number of HTTP2 writes initiated due to 'rst_stream'",
- "Number of HTTP2 writes initiated due to 'close_from_api'",
- "Number of HTTP2 writes initiated due to 'stream_flow_control'",
- "Number of HTTP2 writes initiated due to 'transport_flow_control'",
- "Number of HTTP2 writes initiated due to 'send_settings'",
- "Number of HTTP2 writes initiated due to 'bdp_estimator_ping'",
- "Number of HTTP2 writes initiated due to "
- "'flow_control_unstalled_by_setting'",
- "Number of HTTP2 writes initiated due to "
- "'flow_control_unstalled_by_update'",
- "Number of HTTP2 writes initiated due to 'application_ping'",
- "Number of HTTP2 writes initiated due to 'keepalive_ping'",
- "Number of HTTP2 writes initiated due to "
- "'transport_flow_control_unstalled'",
- "Number of HTTP2 writes initiated due to 'ping_response'",
- "Number of HTTP2 writes initiated due to 'force_rst_stream'",
- "Number of HTTP2 writes initiated with nothing to write",
- "Number of HPACK indexed fields received",
- "Number of HPACK literal headers received with incremental indexing",
- "Number of HPACK literal headers received with incremental indexing and "
- "literal keys",
- "Number of HPACK literal headers received with no indexing",
- "Number of HPACK literal headers received with no indexing and literal "
- "keys",
- "Number of HPACK literal headers received with never-indexing",
- "Number of HPACK literal headers received with never-indexing and literal "
- "keys",
- "Number of uncompressed strings received in metadata",
- "Number of huffman encoded strings received in metadata",
- "Number of binary strings received in metadata",
- "Number of binary strings received encoded in base64 in metadata",
- "Number of HPACK indexed fields sent",
- "Number of HPACK literal headers sent with incremental indexing",
- "Number of HPACK literal headers sent with incremental indexing and "
- "literal keys",
- "Number of HPACK literal headers sent with no indexing",
- "Number of HPACK literal headers sent with no indexing and literal keys",
- "Number of HPACK literal headers sent with never-indexing",
- "Number of HPACK literal headers sent with never-indexing and literal keys",
- "Number of uncompressed strings sent in metadata",
- "Number of huffman encoded strings sent in metadata",
- "Number of binary strings received in metadata",
- "Number of binary strings received encoded in base64 in metadata",
- "Number of combiner lock entries by process (first items queued to a "
- "combiner)",
- "Number of items scheduled against combiner locks",
- "Number of final items scheduled against combiner locks",
- "Number of combiner locks offloaded to different threads",
- "Number of call combiner lock entries by process (first items queued to a "
- "call combiner)",
- "Number of items scheduled against call combiner locks",
- "Number of times a cancellation callback was set on a call combiner",
- "Number of times a call combiner was cancelled",
- "Number of finite runtime closures scheduled against the executor (gRPC "
- "thread pool)",
- "Number of potentially infinite runtime closures scheduled against the "
- "executor (gRPC thread pool)",
- "Number of closures scheduled by the executor to the executor",
- "Number of thread wakeups initiated within the executor",
- "Number of times an executor queue was drained",
- "Number of times we raced and were forced to retry pushing a closure to "
- "the executor",
- "How many calls were requested (not necessarily received) by the server",
- "How many times was the server slow path taken (indicates too few "
- "outstanding requests)",
- "Number of lock (trylock) acquisition failures on completion queue event "
- "queue. High value here indicates high contention on completion queues",
- "Number of lock (trylock) acquisition successes on completion queue event "
- "queue.",
- "Number of times NULL was popped out of completion queue's event queue "
- "even though the event queue was not empty",
-};
-const char* grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT] = {
- "call_initial_size",
- "poll_events_returned",
- "tcp_write_size",
- "tcp_write_iov_size",
- "tcp_read_size",
- "tcp_read_offer",
- "tcp_read_offer_iov_size",
- "http2_send_message_size",
- "http2_send_initial_metadata_per_write",
- "http2_send_message_per_write",
- "http2_send_trailing_metadata_per_write",
- "http2_send_flowctl_per_write",
- "server_cqs_checked",
-};
-const char* grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT] = {
- "Initial size of the grpc_call arena created at call start",
- "How many events are called for each syscall_poll",
- "Number of bytes offered to each syscall_write",
- "Number of byte segments offered to each syscall_write",
- "Number of bytes received by each syscall_read",
- "Number of bytes offered to each syscall_read",
- "Number of byte segments offered to each syscall_read",
- "Size of messages received by HTTP2 transport",
- "Number of streams initiated written per TCP write",
- "Number of streams whose payload was written per TCP write",
- "Number of streams terminated per TCP write",
- "Number of flow control updates written per TCP write",
- "How many completion queues were checked looking for a CQ that had "
- "requested the incoming call",
-};
-const int grpc_stats_table_0[65] = {
- 0, 1, 2, 3, 4, 5, 7, 9, 11, 14,
- 17, 21, 26, 32, 39, 47, 57, 68, 82, 98,
- 117, 140, 167, 199, 238, 284, 339, 404, 482, 575,
- 685, 816, 972, 1158, 1380, 1644, 1959, 2334, 2780, 3312,
- 3945, 4699, 5597, 6667, 7941, 9459, 11267, 13420, 15984, 19038,
- 22676, 27009, 32169, 38315, 45635, 54353, 64737, 77104, 91834, 109378,
- 130273, 155159, 184799, 220100, 262144};
-const uint8_t grpc_stats_table_1[124] = {
- 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6,
- 7, 7, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
- 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 22, 23, 24,
- 24, 25, 25, 26, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 31, 32, 33,
- 33, 34, 34, 34, 35, 35, 36, 37, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41,
- 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50,
- 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58};
-const int grpc_stats_table_2[129] = {
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30,
- 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60,
- 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 94, 98, 102, 106, 110,
- 114, 118, 122, 126, 131, 136, 141, 146, 151, 156, 162, 168, 174, 180, 186,
- 192, 199, 206, 213, 220, 228, 236, 244, 252, 260, 269, 278, 287, 297, 307,
- 317, 327, 338, 349, 360, 372, 384, 396, 409, 422, 436, 450, 464, 479, 494,
- 510, 526, 543, 560, 578, 596, 615, 634, 654, 674, 695, 717, 739, 762, 785,
- 809, 834, 859, 885, 912, 939, 967, 996, 1024};
-const uint8_t grpc_stats_table_3[166] = {
- 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7,
- 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16,
- 17, 17, 18, 19, 19, 20, 21, 21, 22, 23, 23, 24, 25, 25, 26, 26, 27, 27, 28,
- 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 36, 36, 37, 38, 39,
- 40, 40, 41, 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 49, 50, 50, 51,
- 51, 52, 52, 53, 53, 54, 54, 55, 56, 57, 58, 59, 59, 60, 61, 62, 63, 63, 64,
- 65, 65, 66, 67, 67, 68, 69, 69, 70, 71, 71, 72, 72, 73, 73, 74, 75, 75, 76,
- 76, 77, 78, 79, 79, 80, 81, 82, 83, 84, 85, 85, 86, 87, 88, 88, 89, 90, 90,
- 91, 92, 92, 93, 94, 94, 95, 95, 96, 97, 97, 98, 98, 99};
-const int grpc_stats_table_4[65] = {
- 0, 1, 2, 3, 4, 6, 8, 11,
- 15, 20, 26, 34, 44, 57, 73, 94,
- 121, 155, 199, 255, 327, 419, 537, 688,
- 881, 1128, 1444, 1848, 2365, 3026, 3872, 4954,
- 6338, 8108, 10373, 13270, 16976, 21717, 27782, 35541,
- 45467, 58165, 74409, 95189, 121772, 155778, 199281, 254933,
- 326126, 417200, 533707, 682750, 873414, 1117323, 1429345, 1828502,
- 2339127, 2992348, 3827987, 4896985, 6264509, 8013925, 10251880, 13114801,
- 16777216};
-const uint8_t grpc_stats_table_5[87] = {
- 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11,
- 11, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23,
- 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36,
- 36, 37, 38, 39, 39, 40, 41, 41, 42, 43, 44, 44, 45, 45, 46, 47, 48, 48,
- 49, 50, 51, 51, 52, 53, 53, 54, 55, 56, 56, 57, 58, 58, 59};
-const int grpc_stats_table_6[65] = {
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
- 14, 16, 18, 20, 22, 24, 27, 30, 33, 36, 39, 43, 47,
- 51, 56, 61, 66, 72, 78, 85, 92, 100, 109, 118, 128, 139,
- 151, 164, 178, 193, 209, 226, 244, 264, 285, 308, 333, 359, 387,
- 418, 451, 486, 524, 565, 609, 656, 707, 762, 821, 884, 952, 1024};
-const uint8_t grpc_stats_table_7[102] = {
- 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
- 6, 7, 7, 7, 8, 8, 9, 9, 10, 11, 11, 12, 12, 13, 13, 14, 14,
- 14, 15, 15, 16, 16, 17, 17, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23,
- 23, 24, 24, 24, 25, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32,
- 32, 33, 33, 34, 35, 35, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41,
- 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 49, 50, 50, 51, 51};
-const int grpc_stats_table_8[9] = {0, 1, 2, 4, 7, 13, 23, 39, 64};
-const uint8_t grpc_stats_table_9[9] = {0, 0, 1, 2, 2, 3, 4, 4, 5};
-void grpc_stats_inc_call_initial_size(int value) {
- value = GPR_CLAMP(value, 0, 262144);
- if (value < 6) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4651092515166879744ull) {
- int bucket =
- grpc_stats_table_1[((_val.uint - 4618441417868443648ull) >> 49)] + 6;
- _bkt.dbl = grpc_stats_table_0[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_0, 64));
-}
-void grpc_stats_inc_poll_events_returned(int value) {
- value = GPR_CLAMP(value, 0, 1024);
- if (value < 29) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4642789003353915392ull) {
- int bucket =
- grpc_stats_table_3[((_val.uint - 4628855992006737920ull) >> 47)] + 29;
- _bkt.dbl = grpc_stats_table_2[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_2, 128));
-}
-void grpc_stats_inc_tcp_write_size(int value) {
- value = GPR_CLAMP(value, 0, 16777216);
- if (value < 5) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4683743612465315840ull) {
- int bucket =
- grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
- _bkt.dbl = grpc_stats_table_4[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
-}
-void grpc_stats_inc_tcp_write_iov_size(int value) {
- value = GPR_CLAMP(value, 0, 1024);
- if (value < 13) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4637863191261478912ull) {
- int bucket =
- grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
- _bkt.dbl = grpc_stats_table_6[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
-}
-void grpc_stats_inc_tcp_read_size(int value) {
- value = GPR_CLAMP(value, 0, 16777216);
- if (value < 5) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_SIZE, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4683743612465315840ull) {
- int bucket =
- grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
- _bkt.dbl = grpc_stats_table_4[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_SIZE, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_TCP_READ_SIZE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
-}
-void grpc_stats_inc_tcp_read_offer(int value) {
- value = GPR_CLAMP(value, 0, 16777216);
- if (value < 5) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4683743612465315840ull) {
- int bucket =
- grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
- _bkt.dbl = grpc_stats_table_4[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
-}
-void grpc_stats_inc_tcp_read_offer_iov_size(int value) {
- value = GPR_CLAMP(value, 0, 1024);
- if (value < 13) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
- value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4637863191261478912ull) {
- int bucket =
- grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
- _bkt.dbl = grpc_stats_table_6[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
- bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
-}
-void grpc_stats_inc_http2_send_message_size(int value) {
- value = GPR_CLAMP(value, 0, 16777216);
- if (value < 5) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
- value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4683743612465315840ull) {
- int bucket =
- grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
- _bkt.dbl = grpc_stats_table_4[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
- bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
-}
-void grpc_stats_inc_http2_send_initial_metadata_per_write(int value) {
- value = GPR_CLAMP(value, 0, 1024);
- if (value < 13) {
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4637863191261478912ull) {
- int bucket =
- grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
- _bkt.dbl = grpc_stats_table_6[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
-}
-void grpc_stats_inc_http2_send_message_per_write(int value) {
- value = GPR_CLAMP(value, 0, 1024);
- if (value < 13) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
- value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4637863191261478912ull) {
- int bucket =
- grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
- _bkt.dbl = grpc_stats_table_6[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
- bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
-}
-void grpc_stats_inc_http2_send_trailing_metadata_per_write(int value) {
- value = GPR_CLAMP(value, 0, 1024);
- if (value < 13) {
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4637863191261478912ull) {
- int bucket =
- grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
- _bkt.dbl = grpc_stats_table_6[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
-}
-void grpc_stats_inc_http2_send_flowctl_per_write(int value) {
- value = GPR_CLAMP(value, 0, 1024);
- if (value < 13) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
- value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4637863191261478912ull) {
- int bucket =
- grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
- _bkt.dbl = grpc_stats_table_6[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
- bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
-}
-void grpc_stats_inc_server_cqs_checked(int value) {
- value = GPR_CLAMP(value, 0, 64);
- if (value < 3) {
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED, value);
- return;
- }
- union {
- double dbl;
- uint64_t uint;
- } _val, _bkt;
- _val.dbl = value;
- if (_val.uint < 4625196817309499392ull) {
- int bucket =
- grpc_stats_table_9[((_val.uint - 4613937818241073152ull) >> 51)] + 3;
- _bkt.dbl = grpc_stats_table_8[bucket];
- bucket -= (_val.uint < _bkt.uint);
- GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED, bucket);
- return;
- }
- GRPC_STATS_INC_HISTOGRAM(
- GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED,
- grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_8, 8));
-}
-const int grpc_stats_histo_buckets[13] = {64, 128, 64, 64, 64, 64, 64,
- 64, 64, 64, 64, 64, 8};
-const int grpc_stats_histo_start[13] = {0, 64, 192, 256, 320, 384, 448,
- 512, 576, 640, 704, 768, 832};
-const int* const grpc_stats_histo_bucket_boundaries[13] = {
- grpc_stats_table_0, grpc_stats_table_2, grpc_stats_table_4,
- grpc_stats_table_6, grpc_stats_table_4, grpc_stats_table_4,
- grpc_stats_table_6, grpc_stats_table_4, grpc_stats_table_6,
- grpc_stats_table_6, grpc_stats_table_6, grpc_stats_table_6,
- grpc_stats_table_8};
-void (*const grpc_stats_inc_histogram[13])(int x) = {
- grpc_stats_inc_call_initial_size,
- grpc_stats_inc_poll_events_returned,
- grpc_stats_inc_tcp_write_size,
- grpc_stats_inc_tcp_write_iov_size,
- grpc_stats_inc_tcp_read_size,
- grpc_stats_inc_tcp_read_offer,
- grpc_stats_inc_tcp_read_offer_iov_size,
- grpc_stats_inc_http2_send_message_size,
- grpc_stats_inc_http2_send_initial_metadata_per_write,
- grpc_stats_inc_http2_send_message_per_write,
- grpc_stats_inc_http2_send_trailing_metadata_per_write,
- grpc_stats_inc_http2_send_flowctl_per_write,
- grpc_stats_inc_server_cqs_checked};
+ "Number of times histogram increments went through the slow (binary "
+ "search) path",
+ "Number of write syscalls (or equivalent - eg sendmsg) made by this "
+ "process",
+ "Number of read syscalls (or equivalent - eg recvmsg) made by this process",
+ "Number of times a backup poller has been created (this can be expensive)",
+ "Number of polls performed on the backup poller",
+ "Number of batches received by HTTP2 transport",
+ "Number of cancelations received by HTTP2 transport",
+ "Number of batches containing send initial metadata",
+ "Number of batches containing send message",
+ "Number of batches containing send trailing metadata",
+ "Number of batches containing receive initial metadata",
+ "Number of batches containing receive message",
+ "Number of batches containing receive trailing metadata",
+ "Number of settings frames sent",
+ "Number of HTTP2 pings sent by process",
+ "Number of HTTP2 writes initiated",
+ "Number of HTTP2 writes offloaded to the executor from application threads",
+ "Number of HTTP2 writes that finished seeing more data needed to be "
+ "written",
+ "Number of HTTP2 writes that were made knowing there was still more data "
+ "to be written (we cap maximum write size to syscall_write)",
+ "Number of HTTP2 writes initiated due to 'initial_write'",
+ "Number of HTTP2 writes initiated due to 'start_new_stream'",
+ "Number of HTTP2 writes initiated due to 'send_message'",
+ "Number of HTTP2 writes initiated due to 'send_initial_metadata'",
+ "Number of HTTP2 writes initiated due to 'send_trailing_metadata'",
+ "Number of HTTP2 writes initiated due to 'retry_send_ping'",
+ "Number of HTTP2 writes initiated due to 'continue_pings'",
+ "Number of HTTP2 writes initiated due to 'goaway_sent'",
+ "Number of HTTP2 writes initiated due to 'rst_stream'",
+ "Number of HTTP2 writes initiated due to 'close_from_api'",
+ "Number of HTTP2 writes initiated due to 'stream_flow_control'",
+ "Number of HTTP2 writes initiated due to 'transport_flow_control'",
+ "Number of HTTP2 writes initiated due to 'send_settings'",
+ "Number of HTTP2 writes initiated due to 'bdp_estimator_ping'",
+ "Number of HTTP2 writes initiated due to "
+ "'flow_control_unstalled_by_setting'",
+ "Number of HTTP2 writes initiated due to "
+ "'flow_control_unstalled_by_update'",
+ "Number of HTTP2 writes initiated due to 'application_ping'",
+ "Number of HTTP2 writes initiated due to 'keepalive_ping'",
+ "Number of HTTP2 writes initiated due to "
+ "'transport_flow_control_unstalled'",
+ "Number of HTTP2 writes initiated due to 'ping_response'",
+ "Number of HTTP2 writes initiated due to 'force_rst_stream'",
+ "Number of HTTP2 writes initiated with nothing to write",
+ "Number of HPACK indexed fields received",
+ "Number of HPACK literal headers received with incremental indexing",
+ "Number of HPACK literal headers received with incremental indexing and "
+ "literal keys",
+ "Number of HPACK literal headers received with no indexing",
+ "Number of HPACK literal headers received with no indexing and literal "
+ "keys",
+ "Number of HPACK literal headers received with never-indexing",
+ "Number of HPACK literal headers received with never-indexing and literal "
+ "keys",
+ "Number of uncompressed strings received in metadata",
+ "Number of huffman encoded strings received in metadata",
+ "Number of binary strings received in metadata",
+ "Number of binary strings received encoded in base64 in metadata",
+ "Number of HPACK indexed fields sent",
+ "Number of HPACK literal headers sent with incremental indexing",
+ "Number of HPACK literal headers sent with incremental indexing and "
+ "literal keys",
+ "Number of HPACK literal headers sent with no indexing",
+ "Number of HPACK literal headers sent with no indexing and literal keys",
+ "Number of HPACK literal headers sent with never-indexing",
+ "Number of HPACK literal headers sent with never-indexing and literal keys",
+ "Number of uncompressed strings sent in metadata",
+ "Number of huffman encoded strings sent in metadata",
+ "Number of binary strings received in metadata",
+ "Number of binary strings received encoded in base64 in metadata",
+ "Number of combiner lock entries by process (first items queued to a "
+ "combiner)",
+ "Number of items scheduled against combiner locks",
+ "Number of final items scheduled against combiner locks",
+ "Number of combiner locks offloaded to different threads",
+ "Number of call combiner lock entries by process (first items queued to a "
+ "call combiner)",
+ "Number of items scheduled against call combiner locks",
+ "Number of times a cancellation callback was set on a call combiner",
+ "Number of times a call combiner was cancelled",
+ "Number of finite runtime closures scheduled against the executor (gRPC "
+ "thread pool)",
+ "Number of potentially infinite runtime closures scheduled against the "
+ "executor (gRPC thread pool)",
+ "Number of closures scheduled by the executor to the executor",
+ "Number of thread wakeups initiated within the executor",
+ "Number of times an executor queue was drained",
+ "Number of times we raced and were forced to retry pushing a closure to "
+ "the executor",
+ "How many calls were requested (not necessarily received) by the server",
+ "How many times was the server slow path taken (indicates too few "
+ "outstanding requests)",
+ "Number of lock (trylock) acquisition failures on completion queue event "
+ "queue. High value here indicates high contention on completion queues",
+ "Number of lock (trylock) acquisition successes on completion queue event "
+ "queue.",
+ "Number of times NULL was popped out of completion queue's event queue "
+ "even though the event queue was not empty",
+};
+const char* grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT] = {
+ "call_initial_size",
+ "poll_events_returned",
+ "tcp_write_size",
+ "tcp_write_iov_size",
+ "tcp_read_size",
+ "tcp_read_offer",
+ "tcp_read_offer_iov_size",
+ "http2_send_message_size",
+ "http2_send_initial_metadata_per_write",
+ "http2_send_message_per_write",
+ "http2_send_trailing_metadata_per_write",
+ "http2_send_flowctl_per_write",
+ "server_cqs_checked",
+};
+const char* grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT] = {
+ "Initial size of the grpc_call arena created at call start",
+ "How many events are called for each syscall_poll",
+ "Number of bytes offered to each syscall_write",
+ "Number of byte segments offered to each syscall_write",
+ "Number of bytes received by each syscall_read",
+ "Number of bytes offered to each syscall_read",
+ "Number of byte segments offered to each syscall_read",
+ "Size of messages received by HTTP2 transport",
+ "Number of streams initiated written per TCP write",
+ "Number of streams whose payload was written per TCP write",
+ "Number of streams terminated per TCP write",
+ "Number of flow control updates written per TCP write",
+ "How many completion queues were checked looking for a CQ that had "
+ "requested the incoming call",
+};
+const int grpc_stats_table_0[65] = {
+ 0, 1, 2, 3, 4, 5, 7, 9, 11, 14,
+ 17, 21, 26, 32, 39, 47, 57, 68, 82, 98,
+ 117, 140, 167, 199, 238, 284, 339, 404, 482, 575,
+ 685, 816, 972, 1158, 1380, 1644, 1959, 2334, 2780, 3312,
+ 3945, 4699, 5597, 6667, 7941, 9459, 11267, 13420, 15984, 19038,
+ 22676, 27009, 32169, 38315, 45635, 54353, 64737, 77104, 91834, 109378,
+ 130273, 155159, 184799, 220100, 262144};
+const uint8_t grpc_stats_table_1[124] = {
+ 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6,
+ 7, 7, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
+ 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 22, 23, 24,
+ 24, 25, 25, 26, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 31, 32, 33,
+ 33, 34, 34, 34, 35, 35, 36, 37, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41,
+ 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50,
+ 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58};
+const int grpc_stats_table_2[129] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30,
+ 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60,
+ 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 94, 98, 102, 106, 110,
+ 114, 118, 122, 126, 131, 136, 141, 146, 151, 156, 162, 168, 174, 180, 186,
+ 192, 199, 206, 213, 220, 228, 236, 244, 252, 260, 269, 278, 287, 297, 307,
+ 317, 327, 338, 349, 360, 372, 384, 396, 409, 422, 436, 450, 464, 479, 494,
+ 510, 526, 543, 560, 578, 596, 615, 634, 654, 674, 695, 717, 739, 762, 785,
+ 809, 834, 859, 885, 912, 939, 967, 996, 1024};
+const uint8_t grpc_stats_table_3[166] = {
+ 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7,
+ 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16,
+ 17, 17, 18, 19, 19, 20, 21, 21, 22, 23, 23, 24, 25, 25, 26, 26, 27, 27, 28,
+ 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 36, 36, 37, 38, 39,
+ 40, 40, 41, 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 49, 50, 50, 51,
+ 51, 52, 52, 53, 53, 54, 54, 55, 56, 57, 58, 59, 59, 60, 61, 62, 63, 63, 64,
+ 65, 65, 66, 67, 67, 68, 69, 69, 70, 71, 71, 72, 72, 73, 73, 74, 75, 75, 76,
+ 76, 77, 78, 79, 79, 80, 81, 82, 83, 84, 85, 85, 86, 87, 88, 88, 89, 90, 90,
+ 91, 92, 92, 93, 94, 94, 95, 95, 96, 97, 97, 98, 98, 99};
+const int grpc_stats_table_4[65] = {
+ 0, 1, 2, 3, 4, 6, 8, 11,
+ 15, 20, 26, 34, 44, 57, 73, 94,
+ 121, 155, 199, 255, 327, 419, 537, 688,
+ 881, 1128, 1444, 1848, 2365, 3026, 3872, 4954,
+ 6338, 8108, 10373, 13270, 16976, 21717, 27782, 35541,
+ 45467, 58165, 74409, 95189, 121772, 155778, 199281, 254933,
+ 326126, 417200, 533707, 682750, 873414, 1117323, 1429345, 1828502,
+ 2339127, 2992348, 3827987, 4896985, 6264509, 8013925, 10251880, 13114801,
+ 16777216};
+const uint8_t grpc_stats_table_5[87] = {
+ 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11,
+ 11, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23,
+ 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36,
+ 36, 37, 38, 39, 39, 40, 41, 41, 42, 43, 44, 44, 45, 45, 46, 47, 48, 48,
+ 49, 50, 51, 51, 52, 53, 53, 54, 55, 56, 56, 57, 58, 58, 59};
+const int grpc_stats_table_6[65] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 14, 16, 18, 20, 22, 24, 27, 30, 33, 36, 39, 43, 47,
+ 51, 56, 61, 66, 72, 78, 85, 92, 100, 109, 118, 128, 139,
+ 151, 164, 178, 193, 209, 226, 244, 264, 285, 308, 333, 359, 387,
+ 418, 451, 486, 524, 565, 609, 656, 707, 762, 821, 884, 952, 1024};
+const uint8_t grpc_stats_table_7[102] = {
+ 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+ 6, 7, 7, 7, 8, 8, 9, 9, 10, 11, 11, 12, 12, 13, 13, 14, 14,
+ 14, 15, 15, 16, 16, 17, 17, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23,
+ 23, 24, 24, 24, 25, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32,
+ 32, 33, 33, 34, 35, 35, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41,
+ 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 49, 50, 50, 51, 51};
+const int grpc_stats_table_8[9] = {0, 1, 2, 4, 7, 13, 23, 39, 64};
+const uint8_t grpc_stats_table_9[9] = {0, 0, 1, 2, 2, 3, 4, 4, 5};
+void grpc_stats_inc_call_initial_size(int value) {
+ value = GPR_CLAMP(value, 0, 262144);
+ if (value < 6) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4651092515166879744ull) {
+ int bucket =
+ grpc_stats_table_1[((_val.uint - 4618441417868443648ull) >> 49)] + 6;
+ _bkt.dbl = grpc_stats_table_0[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_0, 64));
+}
+void grpc_stats_inc_poll_events_returned(int value) {
+ value = GPR_CLAMP(value, 0, 1024);
+ if (value < 29) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4642789003353915392ull) {
+ int bucket =
+ grpc_stats_table_3[((_val.uint - 4628855992006737920ull) >> 47)] + 29;
+ _bkt.dbl = grpc_stats_table_2[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_2, 128));
+}
+void grpc_stats_inc_tcp_write_size(int value) {
+ value = GPR_CLAMP(value, 0, 16777216);
+ if (value < 5) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4683743612465315840ull) {
+ int bucket =
+ grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
+ _bkt.dbl = grpc_stats_table_4[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
+}
+void grpc_stats_inc_tcp_write_iov_size(int value) {
+ value = GPR_CLAMP(value, 0, 1024);
+ if (value < 13) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4637863191261478912ull) {
+ int bucket =
+ grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
+ _bkt.dbl = grpc_stats_table_6[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
+}
+void grpc_stats_inc_tcp_read_size(int value) {
+ value = GPR_CLAMP(value, 0, 16777216);
+ if (value < 5) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_SIZE, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4683743612465315840ull) {
+ int bucket =
+ grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
+ _bkt.dbl = grpc_stats_table_4[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_SIZE, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_TCP_READ_SIZE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
+}
+void grpc_stats_inc_tcp_read_offer(int value) {
+ value = GPR_CLAMP(value, 0, 16777216);
+ if (value < 5) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4683743612465315840ull) {
+ int bucket =
+ grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
+ _bkt.dbl = grpc_stats_table_4[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
+}
+void grpc_stats_inc_tcp_read_offer_iov_size(int value) {
+ value = GPR_CLAMP(value, 0, 1024);
+ if (value < 13) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
+ value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4637863191261478912ull) {
+ int bucket =
+ grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
+ _bkt.dbl = grpc_stats_table_6[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
+ bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
+}
+void grpc_stats_inc_http2_send_message_size(int value) {
+ value = GPR_CLAMP(value, 0, 16777216);
+ if (value < 5) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
+ value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4683743612465315840ull) {
+ int bucket =
+ grpc_stats_table_5[((_val.uint - 4617315517961601024ull) >> 50)] + 5;
+ _bkt.dbl = grpc_stats_table_4[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
+ bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_4, 64));
+}
+void grpc_stats_inc_http2_send_initial_metadata_per_write(int value) {
+ value = GPR_CLAMP(value, 0, 1024);
+ if (value < 13) {
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4637863191261478912ull) {
+ int bucket =
+ grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
+ _bkt.dbl = grpc_stats_table_6[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
+}
+void grpc_stats_inc_http2_send_message_per_write(int value) {
+ value = GPR_CLAMP(value, 0, 1024);
+ if (value < 13) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
+ value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4637863191261478912ull) {
+ int bucket =
+ grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
+ _bkt.dbl = grpc_stats_table_6[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
+ bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
+}
+void grpc_stats_inc_http2_send_trailing_metadata_per_write(int value) {
+ value = GPR_CLAMP(value, 0, 1024);
+ if (value < 13) {
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4637863191261478912ull) {
+ int bucket =
+ grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
+ _bkt.dbl = grpc_stats_table_6[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
+}
+void grpc_stats_inc_http2_send_flowctl_per_write(int value) {
+ value = GPR_CLAMP(value, 0, 1024);
+ if (value < 13) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
+ value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4637863191261478912ull) {
+ int bucket =
+ grpc_stats_table_7[((_val.uint - 4623507967449235456ull) >> 48)] + 13;
+ _bkt.dbl = grpc_stats_table_6[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
+ bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_6, 64));
+}
+void grpc_stats_inc_server_cqs_checked(int value) {
+ value = GPR_CLAMP(value, 0, 64);
+ if (value < 3) {
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED, value);
+ return;
+ }
+ union {
+ double dbl;
+ uint64_t uint;
+ } _val, _bkt;
+ _val.dbl = value;
+ if (_val.uint < 4625196817309499392ull) {
+ int bucket =
+ grpc_stats_table_9[((_val.uint - 4613937818241073152ull) >> 51)] + 3;
+ _bkt.dbl = grpc_stats_table_8[bucket];
+ bucket -= (_val.uint < _bkt.uint);
+ GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED, bucket);
+ return;
+ }
+ GRPC_STATS_INC_HISTOGRAM(
+ GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED,
+ grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_8, 8));
+}
+const int grpc_stats_histo_buckets[13] = {64, 128, 64, 64, 64, 64, 64,
+ 64, 64, 64, 64, 64, 8};
+const int grpc_stats_histo_start[13] = {0, 64, 192, 256, 320, 384, 448,
+ 512, 576, 640, 704, 768, 832};
+const int* const grpc_stats_histo_bucket_boundaries[13] = {
+ grpc_stats_table_0, grpc_stats_table_2, grpc_stats_table_4,
+ grpc_stats_table_6, grpc_stats_table_4, grpc_stats_table_4,
+ grpc_stats_table_6, grpc_stats_table_4, grpc_stats_table_6,
+ grpc_stats_table_6, grpc_stats_table_6, grpc_stats_table_6,
+ grpc_stats_table_8};
+void (*const grpc_stats_inc_histogram[13])(int x) = {
+ grpc_stats_inc_call_initial_size,
+ grpc_stats_inc_poll_events_returned,
+ grpc_stats_inc_tcp_write_size,
+ grpc_stats_inc_tcp_write_iov_size,
+ grpc_stats_inc_tcp_read_size,
+ grpc_stats_inc_tcp_read_offer,
+ grpc_stats_inc_tcp_read_offer_iov_size,
+ grpc_stats_inc_http2_send_message_size,
+ grpc_stats_inc_http2_send_initial_metadata_per_write,
+ grpc_stats_inc_http2_send_message_per_write,
+ grpc_stats_inc_http2_send_trailing_metadata_per_write,
+ grpc_stats_inc_http2_send_flowctl_per_write,
+ grpc_stats_inc_server_cqs_checked};
diff --git a/contrib/libs/grpc/src/core/lib/debug/stats_data.h b/contrib/libs/grpc/src/core/lib/debug/stats_data.h
index 1f3861f4941..a6e2727c000 100644
--- a/contrib/libs/grpc/src/core/lib/debug/stats_data.h
+++ b/contrib/libs/grpc/src/core/lib/debug/stats_data.h
@@ -1,439 +1,439 @@
-/*
- * 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.
- */
-
-/*
- * Automatically generated by tools/codegen/core/gen_stats_data.py
- */
-
-#ifndef GRPC_CORE_LIB_DEBUG_STATS_DATA_H
-#define GRPC_CORE_LIB_DEBUG_STATS_DATA_H
-
-#include <grpc/support/port_platform.h>
-
-#include <inttypes.h>
-#include "src/core/lib/iomgr/exec_ctx.h"
-
-typedef enum {
- GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED,
- GRPC_STATS_COUNTER_SERVER_CALLS_CREATED,
- GRPC_STATS_COUNTER_CQS_CREATED,
- GRPC_STATS_COUNTER_CLIENT_CHANNELS_CREATED,
- GRPC_STATS_COUNTER_CLIENT_SUBCHANNELS_CREATED,
- GRPC_STATS_COUNTER_SERVER_CHANNELS_CREATED,
- GRPC_STATS_COUNTER_SYSCALL_POLL,
- GRPC_STATS_COUNTER_SYSCALL_WAIT,
- GRPC_STATS_COUNTER_POLLSET_KICK,
- GRPC_STATS_COUNTER_POLLSET_KICKED_WITHOUT_POLLER,
- GRPC_STATS_COUNTER_POLLSET_KICKED_AGAIN,
- GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_FD,
- GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_CV,
- GRPC_STATS_COUNTER_POLLSET_KICK_OWN_THREAD,
+/*
+ * 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.
+ */
+
+/*
+ * Automatically generated by tools/codegen/core/gen_stats_data.py
+ */
+
+#ifndef GRPC_CORE_LIB_DEBUG_STATS_DATA_H
+#define GRPC_CORE_LIB_DEBUG_STATS_DATA_H
+
+#include <grpc/support/port_platform.h>
+
+#include <inttypes.h>
+#include "src/core/lib/iomgr/exec_ctx.h"
+
+typedef enum {
+ GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED,
+ GRPC_STATS_COUNTER_SERVER_CALLS_CREATED,
+ GRPC_STATS_COUNTER_CQS_CREATED,
+ GRPC_STATS_COUNTER_CLIENT_CHANNELS_CREATED,
+ GRPC_STATS_COUNTER_CLIENT_SUBCHANNELS_CREATED,
+ GRPC_STATS_COUNTER_SERVER_CHANNELS_CREATED,
+ GRPC_STATS_COUNTER_SYSCALL_POLL,
+ GRPC_STATS_COUNTER_SYSCALL_WAIT,
+ GRPC_STATS_COUNTER_POLLSET_KICK,
+ GRPC_STATS_COUNTER_POLLSET_KICKED_WITHOUT_POLLER,
+ GRPC_STATS_COUNTER_POLLSET_KICKED_AGAIN,
+ GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_FD,
+ GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_CV,
+ GRPC_STATS_COUNTER_POLLSET_KICK_OWN_THREAD,
GRPC_STATS_COUNTER_SYSCALL_EPOLL_CTL,
GRPC_STATS_COUNTER_POLLSET_FD_CACHE_HITS,
- GRPC_STATS_COUNTER_HISTOGRAM_SLOW_LOOKUPS,
- GRPC_STATS_COUNTER_SYSCALL_WRITE,
- GRPC_STATS_COUNTER_SYSCALL_READ,
- GRPC_STATS_COUNTER_TCP_BACKUP_POLLERS_CREATED,
- GRPC_STATS_COUNTER_TCP_BACKUP_POLLER_POLLS,
- GRPC_STATS_COUNTER_HTTP2_OP_BATCHES,
- GRPC_STATS_COUNTER_HTTP2_OP_CANCEL,
- GRPC_STATS_COUNTER_HTTP2_OP_SEND_INITIAL_METADATA,
- GRPC_STATS_COUNTER_HTTP2_OP_SEND_MESSAGE,
- GRPC_STATS_COUNTER_HTTP2_OP_SEND_TRAILING_METADATA,
- GRPC_STATS_COUNTER_HTTP2_OP_RECV_INITIAL_METADATA,
- GRPC_STATS_COUNTER_HTTP2_OP_RECV_MESSAGE,
- GRPC_STATS_COUNTER_HTTP2_OP_RECV_TRAILING_METADATA,
- GRPC_STATS_COUNTER_HTTP2_SETTINGS_WRITES,
- GRPC_STATS_COUNTER_HTTP2_PINGS_SENT,
- GRPC_STATS_COUNTER_HTTP2_WRITES_BEGUN,
- GRPC_STATS_COUNTER_HTTP2_WRITES_OFFLOADED,
- GRPC_STATS_COUNTER_HTTP2_WRITES_CONTINUED,
- GRPC_STATS_COUNTER_HTTP2_PARTIAL_WRITES,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE,
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM,
- GRPC_STATS_COUNTER_HTTP2_SPURIOUS_WRITES_BEGUN,
- GRPC_STATS_COUNTER_HPACK_RECV_INDEXED,
- GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX,
- GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX_V,
- GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX,
- GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX_V,
- GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX,
- GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX_V,
- GRPC_STATS_COUNTER_HPACK_RECV_UNCOMPRESSED,
- GRPC_STATS_COUNTER_HPACK_RECV_HUFFMAN,
- GRPC_STATS_COUNTER_HPACK_RECV_BINARY,
- GRPC_STATS_COUNTER_HPACK_RECV_BINARY_BASE64,
- GRPC_STATS_COUNTER_HPACK_SEND_INDEXED,
- GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX,
- GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX_V,
- GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX,
- GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX_V,
- GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX,
- GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX_V,
- GRPC_STATS_COUNTER_HPACK_SEND_UNCOMPRESSED,
- GRPC_STATS_COUNTER_HPACK_SEND_HUFFMAN,
- GRPC_STATS_COUNTER_HPACK_SEND_BINARY,
- GRPC_STATS_COUNTER_HPACK_SEND_BINARY_BASE64,
- GRPC_STATS_COUNTER_COMBINER_LOCKS_INITIATED,
- GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_ITEMS,
- GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS,
- GRPC_STATS_COUNTER_COMBINER_LOCKS_OFFLOADED,
- GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_INITIATED,
- GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS,
- GRPC_STATS_COUNTER_CALL_COMBINER_SET_NOTIFY_ON_CANCEL,
- GRPC_STATS_COUNTER_CALL_COMBINER_CANCELLED,
- GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_SHORT_ITEMS,
- GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_LONG_ITEMS,
- GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_TO_SELF,
- GRPC_STATS_COUNTER_EXECUTOR_WAKEUP_INITIATED,
- GRPC_STATS_COUNTER_EXECUTOR_QUEUE_DRAINED,
- GRPC_STATS_COUNTER_EXECUTOR_PUSH_RETRIES,
- GRPC_STATS_COUNTER_SERVER_REQUESTED_CALLS,
- GRPC_STATS_COUNTER_SERVER_SLOWPATH_REQUESTS_QUEUED,
- GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_FAILURES,
- GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_SUCCESSES,
- GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES,
- GRPC_STATS_COUNTER_COUNT
-} grpc_stats_counters;
-extern const char* grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT];
-extern const char* grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT];
-typedef enum {
- GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE,
- GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED,
- GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE,
- GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE,
- GRPC_STATS_HISTOGRAM_TCP_READ_SIZE,
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER,
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
- GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED,
- GRPC_STATS_HISTOGRAM_COUNT
-} grpc_stats_histograms;
-extern const char* grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT];
-extern const char* grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT];
-typedef enum {
- GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE_FIRST_SLOT = 0,
- GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED_FIRST_SLOT = 64,
- GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED_BUCKETS = 128,
- GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE_FIRST_SLOT = 192,
- GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE_FIRST_SLOT = 256,
- GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_TCP_READ_SIZE_FIRST_SLOT = 320,
- GRPC_STATS_HISTOGRAM_TCP_READ_SIZE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_FIRST_SLOT = 384,
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE_FIRST_SLOT = 448,
- GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE_FIRST_SLOT = 512,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE_FIRST_SLOT = 576,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE_FIRST_SLOT = 640,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE_FIRST_SLOT = 704,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE_FIRST_SLOT = 768,
- GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE_BUCKETS = 64,
- GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED_FIRST_SLOT = 832,
- GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED_BUCKETS = 8,
- GRPC_STATS_HISTOGRAM_BUCKETS = 840
-} grpc_stats_histogram_constants;
+ GRPC_STATS_COUNTER_HISTOGRAM_SLOW_LOOKUPS,
+ GRPC_STATS_COUNTER_SYSCALL_WRITE,
+ GRPC_STATS_COUNTER_SYSCALL_READ,
+ GRPC_STATS_COUNTER_TCP_BACKUP_POLLERS_CREATED,
+ GRPC_STATS_COUNTER_TCP_BACKUP_POLLER_POLLS,
+ GRPC_STATS_COUNTER_HTTP2_OP_BATCHES,
+ GRPC_STATS_COUNTER_HTTP2_OP_CANCEL,
+ GRPC_STATS_COUNTER_HTTP2_OP_SEND_INITIAL_METADATA,
+ GRPC_STATS_COUNTER_HTTP2_OP_SEND_MESSAGE,
+ GRPC_STATS_COUNTER_HTTP2_OP_SEND_TRAILING_METADATA,
+ GRPC_STATS_COUNTER_HTTP2_OP_RECV_INITIAL_METADATA,
+ GRPC_STATS_COUNTER_HTTP2_OP_RECV_MESSAGE,
+ GRPC_STATS_COUNTER_HTTP2_OP_RECV_TRAILING_METADATA,
+ GRPC_STATS_COUNTER_HTTP2_SETTINGS_WRITES,
+ GRPC_STATS_COUNTER_HTTP2_PINGS_SENT,
+ GRPC_STATS_COUNTER_HTTP2_WRITES_BEGUN,
+ GRPC_STATS_COUNTER_HTTP2_WRITES_OFFLOADED,
+ GRPC_STATS_COUNTER_HTTP2_WRITES_CONTINUED,
+ GRPC_STATS_COUNTER_HTTP2_PARTIAL_WRITES,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE,
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM,
+ GRPC_STATS_COUNTER_HTTP2_SPURIOUS_WRITES_BEGUN,
+ GRPC_STATS_COUNTER_HPACK_RECV_INDEXED,
+ GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX,
+ GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX_V,
+ GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX,
+ GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX_V,
+ GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX,
+ GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX_V,
+ GRPC_STATS_COUNTER_HPACK_RECV_UNCOMPRESSED,
+ GRPC_STATS_COUNTER_HPACK_RECV_HUFFMAN,
+ GRPC_STATS_COUNTER_HPACK_RECV_BINARY,
+ GRPC_STATS_COUNTER_HPACK_RECV_BINARY_BASE64,
+ GRPC_STATS_COUNTER_HPACK_SEND_INDEXED,
+ GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX,
+ GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX_V,
+ GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX,
+ GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX_V,
+ GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX,
+ GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX_V,
+ GRPC_STATS_COUNTER_HPACK_SEND_UNCOMPRESSED,
+ GRPC_STATS_COUNTER_HPACK_SEND_HUFFMAN,
+ GRPC_STATS_COUNTER_HPACK_SEND_BINARY,
+ GRPC_STATS_COUNTER_HPACK_SEND_BINARY_BASE64,
+ GRPC_STATS_COUNTER_COMBINER_LOCKS_INITIATED,
+ GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_ITEMS,
+ GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS,
+ GRPC_STATS_COUNTER_COMBINER_LOCKS_OFFLOADED,
+ GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_INITIATED,
+ GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS,
+ GRPC_STATS_COUNTER_CALL_COMBINER_SET_NOTIFY_ON_CANCEL,
+ GRPC_STATS_COUNTER_CALL_COMBINER_CANCELLED,
+ GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_SHORT_ITEMS,
+ GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_LONG_ITEMS,
+ GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_TO_SELF,
+ GRPC_STATS_COUNTER_EXECUTOR_WAKEUP_INITIATED,
+ GRPC_STATS_COUNTER_EXECUTOR_QUEUE_DRAINED,
+ GRPC_STATS_COUNTER_EXECUTOR_PUSH_RETRIES,
+ GRPC_STATS_COUNTER_SERVER_REQUESTED_CALLS,
+ GRPC_STATS_COUNTER_SERVER_SLOWPATH_REQUESTS_QUEUED,
+ GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_FAILURES,
+ GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_SUCCESSES,
+ GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES,
+ GRPC_STATS_COUNTER_COUNT
+} grpc_stats_counters;
+extern const char* grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT];
+extern const char* grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT];
+typedef enum {
+ GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE,
+ GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED,
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE,
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE,
+ GRPC_STATS_HISTOGRAM_TCP_READ_SIZE,
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER,
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE,
+ GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED,
+ GRPC_STATS_HISTOGRAM_COUNT
+} grpc_stats_histograms;
+extern const char* grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT];
+extern const char* grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT];
+typedef enum {
+ GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE_FIRST_SLOT = 0,
+ GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED_FIRST_SLOT = 64,
+ GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED_BUCKETS = 128,
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE_FIRST_SLOT = 192,
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE_FIRST_SLOT = 256,
+ GRPC_STATS_HISTOGRAM_TCP_WRITE_IOV_SIZE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_TCP_READ_SIZE_FIRST_SLOT = 320,
+ GRPC_STATS_HISTOGRAM_TCP_READ_SIZE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_FIRST_SLOT = 384,
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE_FIRST_SLOT = 448,
+ GRPC_STATS_HISTOGRAM_TCP_READ_OFFER_IOV_SIZE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE_FIRST_SLOT = 512,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_SIZE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE_FIRST_SLOT = 576,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_INITIAL_METADATA_PER_WRITE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE_FIRST_SLOT = 640,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_MESSAGE_PER_WRITE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE_FIRST_SLOT = 704,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_TRAILING_METADATA_PER_WRITE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE_FIRST_SLOT = 768,
+ GRPC_STATS_HISTOGRAM_HTTP2_SEND_FLOWCTL_PER_WRITE_BUCKETS = 64,
+ GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED_FIRST_SLOT = 832,
+ GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED_BUCKETS = 8,
+ GRPC_STATS_HISTOGRAM_BUCKETS = 840
+} grpc_stats_histogram_constants;
#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)
-#define GRPC_STATS_INC_CLIENT_CALLS_CREATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED)
-#define GRPC_STATS_INC_SERVER_CALLS_CREATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_CALLS_CREATED)
-#define GRPC_STATS_INC_CQS_CREATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQS_CREATED)
-#define GRPC_STATS_INC_CLIENT_CHANNELS_CREATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CLIENT_CHANNELS_CREATED)
-#define GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CLIENT_SUBCHANNELS_CREATED)
-#define GRPC_STATS_INC_SERVER_CHANNELS_CREATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_CHANNELS_CREATED)
-#define GRPC_STATS_INC_SYSCALL_POLL() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_POLL)
-#define GRPC_STATS_INC_SYSCALL_WAIT() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_WAIT)
-#define GRPC_STATS_INC_POLLSET_KICK() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK)
-#define GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICKED_WITHOUT_POLLER)
-#define GRPC_STATS_INC_POLLSET_KICKED_AGAIN() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICKED_AGAIN)
-#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_FD)
-#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_CV)
-#define GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_OWN_THREAD)
+#define GRPC_STATS_INC_CLIENT_CALLS_CREATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED)
+#define GRPC_STATS_INC_SERVER_CALLS_CREATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_CALLS_CREATED)
+#define GRPC_STATS_INC_CQS_CREATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQS_CREATED)
+#define GRPC_STATS_INC_CLIENT_CHANNELS_CREATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CLIENT_CHANNELS_CREATED)
+#define GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CLIENT_SUBCHANNELS_CREATED)
+#define GRPC_STATS_INC_SERVER_CHANNELS_CREATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_CHANNELS_CREATED)
+#define GRPC_STATS_INC_SYSCALL_POLL() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_POLL)
+#define GRPC_STATS_INC_SYSCALL_WAIT() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_WAIT)
+#define GRPC_STATS_INC_POLLSET_KICK() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK)
+#define GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICKED_WITHOUT_POLLER)
+#define GRPC_STATS_INC_POLLSET_KICKED_AGAIN() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICKED_AGAIN)
+#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_FD)
+#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_CV)
+#define GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_OWN_THREAD)
#define GRPC_STATS_INC_SYSCALL_EPOLL_CTL() \
GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_EPOLL_CTL)
#define GRPC_STATS_INC_POLLSET_FD_CACHE_HITS() \
GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_FD_CACHE_HITS)
-#define GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HISTOGRAM_SLOW_LOOKUPS)
-#define GRPC_STATS_INC_SYSCALL_WRITE() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_WRITE)
-#define GRPC_STATS_INC_SYSCALL_READ() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_READ)
-#define GRPC_STATS_INC_TCP_BACKUP_POLLERS_CREATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_TCP_BACKUP_POLLERS_CREATED)
-#define GRPC_STATS_INC_TCP_BACKUP_POLLER_POLLS() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_TCP_BACKUP_POLLER_POLLS)
-#define GRPC_STATS_INC_HTTP2_OP_BATCHES() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_BATCHES)
-#define GRPC_STATS_INC_HTTP2_OP_CANCEL() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_CANCEL)
-#define GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_SEND_INITIAL_METADATA)
-#define GRPC_STATS_INC_HTTP2_OP_SEND_MESSAGE() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_SEND_MESSAGE)
-#define GRPC_STATS_INC_HTTP2_OP_SEND_TRAILING_METADATA() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_SEND_TRAILING_METADATA)
-#define GRPC_STATS_INC_HTTP2_OP_RECV_INITIAL_METADATA() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_RECV_INITIAL_METADATA)
-#define GRPC_STATS_INC_HTTP2_OP_RECV_MESSAGE() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_RECV_MESSAGE)
-#define GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_RECV_TRAILING_METADATA)
-#define GRPC_STATS_INC_HTTP2_SETTINGS_WRITES() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_SETTINGS_WRITES)
-#define GRPC_STATS_INC_HTTP2_PINGS_SENT() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_PINGS_SENT)
-#define GRPC_STATS_INC_HTTP2_WRITES_BEGUN() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_WRITES_BEGUN)
-#define GRPC_STATS_INC_HTTP2_WRITES_OFFLOADED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_WRITES_OFFLOADED)
-#define GRPC_STATS_INC_HTTP2_WRITES_CONTINUED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_WRITES_CONTINUED)
-#define GRPC_STATS_INC_HTTP2_PARTIAL_WRITES() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_PARTIAL_WRITES)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE)
-#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM)
-#define GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_SPURIOUS_WRITES_BEGUN)
-#define GRPC_STATS_INC_HPACK_RECV_INDEXED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_INDEXED)
-#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX)
-#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX_V() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX_V)
-#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX)
-#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX_V() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX_V)
-#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX)
-#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX_V() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX_V)
-#define GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_UNCOMPRESSED)
-#define GRPC_STATS_INC_HPACK_RECV_HUFFMAN() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_HUFFMAN)
-#define GRPC_STATS_INC_HPACK_RECV_BINARY() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_BINARY)
-#define GRPC_STATS_INC_HPACK_RECV_BINARY_BASE64() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_BINARY_BASE64)
-#define GRPC_STATS_INC_HPACK_SEND_INDEXED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_INDEXED)
-#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX)
-#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX_V() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX_V)
-#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX)
-#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX_V)
-#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX)
-#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX_V() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX_V)
-#define GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_UNCOMPRESSED)
-#define GRPC_STATS_INC_HPACK_SEND_HUFFMAN() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_HUFFMAN)
-#define GRPC_STATS_INC_HPACK_SEND_BINARY() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_BINARY)
-#define GRPC_STATS_INC_HPACK_SEND_BINARY_BASE64() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_BINARY_BASE64)
-#define GRPC_STATS_INC_COMBINER_LOCKS_INITIATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_COMBINER_LOCKS_INITIATED)
-#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_ITEMS() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_ITEMS)
-#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS() \
- GRPC_STATS_INC_COUNTER( \
- GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS)
-#define GRPC_STATS_INC_COMBINER_LOCKS_OFFLOADED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_COMBINER_LOCKS_OFFLOADED)
-#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_INITIATED)
-#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS)
-#define GRPC_STATS_INC_CALL_COMBINER_SET_NOTIFY_ON_CANCEL() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_SET_NOTIFY_ON_CANCEL)
-#define GRPC_STATS_INC_CALL_COMBINER_CANCELLED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_CANCELLED)
-#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_SHORT_ITEMS)
-#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_LONG_ITEMS() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_LONG_ITEMS)
-#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_TO_SELF)
-#define GRPC_STATS_INC_EXECUTOR_WAKEUP_INITIATED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_WAKEUP_INITIATED)
-#define GRPC_STATS_INC_EXECUTOR_QUEUE_DRAINED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_QUEUE_DRAINED)
-#define GRPC_STATS_INC_EXECUTOR_PUSH_RETRIES() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_PUSH_RETRIES)
-#define GRPC_STATS_INC_SERVER_REQUESTED_CALLS() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_REQUESTED_CALLS)
-#define GRPC_STATS_INC_SERVER_SLOWPATH_REQUESTS_QUEUED() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_SLOWPATH_REQUESTS_QUEUED)
-#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_FAILURES() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_FAILURES)
-#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_SUCCESSES() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_SUCCESSES)
-#define GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES() \
- GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES)
-#define GRPC_STATS_INC_CALL_INITIAL_SIZE(value) \
- grpc_stats_inc_call_initial_size((int)(value))
-void grpc_stats_inc_call_initial_size(int x);
-#define GRPC_STATS_INC_POLL_EVENTS_RETURNED(value) \
- grpc_stats_inc_poll_events_returned((int)(value))
-void grpc_stats_inc_poll_events_returned(int x);
-#define GRPC_STATS_INC_TCP_WRITE_SIZE(value) \
- grpc_stats_inc_tcp_write_size((int)(value))
-void grpc_stats_inc_tcp_write_size(int x);
-#define GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(value) \
- grpc_stats_inc_tcp_write_iov_size((int)(value))
-void grpc_stats_inc_tcp_write_iov_size(int x);
-#define GRPC_STATS_INC_TCP_READ_SIZE(value) \
- grpc_stats_inc_tcp_read_size((int)(value))
-void grpc_stats_inc_tcp_read_size(int x);
-#define GRPC_STATS_INC_TCP_READ_OFFER(value) \
- grpc_stats_inc_tcp_read_offer((int)(value))
-void grpc_stats_inc_tcp_read_offer(int x);
-#define GRPC_STATS_INC_TCP_READ_OFFER_IOV_SIZE(value) \
- grpc_stats_inc_tcp_read_offer_iov_size((int)(value))
-void grpc_stats_inc_tcp_read_offer_iov_size(int x);
-#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE(value) \
- grpc_stats_inc_http2_send_message_size((int)(value))
-void grpc_stats_inc_http2_send_message_size(int x);
-#define GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE(value) \
- grpc_stats_inc_http2_send_initial_metadata_per_write((int)(value))
-void grpc_stats_inc_http2_send_initial_metadata_per_write(int x);
-#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(value) \
- grpc_stats_inc_http2_send_message_per_write((int)(value))
-void grpc_stats_inc_http2_send_message_per_write(int x);
-#define GRPC_STATS_INC_HTTP2_SEND_TRAILING_METADATA_PER_WRITE(value) \
- grpc_stats_inc_http2_send_trailing_metadata_per_write((int)(value))
-void grpc_stats_inc_http2_send_trailing_metadata_per_write(int x);
-#define GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(value) \
- grpc_stats_inc_http2_send_flowctl_per_write((int)(value))
-void grpc_stats_inc_http2_send_flowctl_per_write(int x);
-#define GRPC_STATS_INC_SERVER_CQS_CHECKED(value) \
- grpc_stats_inc_server_cqs_checked((int)(value))
-void grpc_stats_inc_server_cqs_checked(int x);
+#define GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HISTOGRAM_SLOW_LOOKUPS)
+#define GRPC_STATS_INC_SYSCALL_WRITE() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_WRITE)
+#define GRPC_STATS_INC_SYSCALL_READ() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_READ)
+#define GRPC_STATS_INC_TCP_BACKUP_POLLERS_CREATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_TCP_BACKUP_POLLERS_CREATED)
+#define GRPC_STATS_INC_TCP_BACKUP_POLLER_POLLS() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_TCP_BACKUP_POLLER_POLLS)
+#define GRPC_STATS_INC_HTTP2_OP_BATCHES() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_BATCHES)
+#define GRPC_STATS_INC_HTTP2_OP_CANCEL() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_CANCEL)
+#define GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_SEND_INITIAL_METADATA)
+#define GRPC_STATS_INC_HTTP2_OP_SEND_MESSAGE() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_SEND_MESSAGE)
+#define GRPC_STATS_INC_HTTP2_OP_SEND_TRAILING_METADATA() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_SEND_TRAILING_METADATA)
+#define GRPC_STATS_INC_HTTP2_OP_RECV_INITIAL_METADATA() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_RECV_INITIAL_METADATA)
+#define GRPC_STATS_INC_HTTP2_OP_RECV_MESSAGE() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_RECV_MESSAGE)
+#define GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_OP_RECV_TRAILING_METADATA)
+#define GRPC_STATS_INC_HTTP2_SETTINGS_WRITES() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_SETTINGS_WRITES)
+#define GRPC_STATS_INC_HTTP2_PINGS_SENT() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_PINGS_SENT)
+#define GRPC_STATS_INC_HTTP2_WRITES_BEGUN() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_WRITES_BEGUN)
+#define GRPC_STATS_INC_HTTP2_WRITES_OFFLOADED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_WRITES_OFFLOADED)
+#define GRPC_STATS_INC_HTTP2_WRITES_CONTINUED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_WRITES_CONTINUED)
+#define GRPC_STATS_INC_HTTP2_PARTIAL_WRITES() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_PARTIAL_WRITES)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE)
+#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM)
+#define GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HTTP2_SPURIOUS_WRITES_BEGUN)
+#define GRPC_STATS_INC_HPACK_RECV_INDEXED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_INDEXED)
+#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX)
+#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX_V() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_INCIDX_V)
+#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX)
+#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX_V() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NOTIDX_V)
+#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX)
+#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX_V() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_LITHDR_NVRIDX_V)
+#define GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_UNCOMPRESSED)
+#define GRPC_STATS_INC_HPACK_RECV_HUFFMAN() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_HUFFMAN)
+#define GRPC_STATS_INC_HPACK_RECV_BINARY() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_BINARY)
+#define GRPC_STATS_INC_HPACK_RECV_BINARY_BASE64() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_RECV_BINARY_BASE64)
+#define GRPC_STATS_INC_HPACK_SEND_INDEXED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_INDEXED)
+#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX)
+#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX_V() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_INCIDX_V)
+#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX)
+#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NOTIDX_V)
+#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX)
+#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX_V() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_LITHDR_NVRIDX_V)
+#define GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_UNCOMPRESSED)
+#define GRPC_STATS_INC_HPACK_SEND_HUFFMAN() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_HUFFMAN)
+#define GRPC_STATS_INC_HPACK_SEND_BINARY() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_BINARY)
+#define GRPC_STATS_INC_HPACK_SEND_BINARY_BASE64() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HPACK_SEND_BINARY_BASE64)
+#define GRPC_STATS_INC_COMBINER_LOCKS_INITIATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_COMBINER_LOCKS_INITIATED)
+#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_ITEMS() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_ITEMS)
+#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS() \
+ GRPC_STATS_INC_COUNTER( \
+ GRPC_STATS_COUNTER_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS)
+#define GRPC_STATS_INC_COMBINER_LOCKS_OFFLOADED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_COMBINER_LOCKS_OFFLOADED)
+#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_INITIATED)
+#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS)
+#define GRPC_STATS_INC_CALL_COMBINER_SET_NOTIFY_ON_CANCEL() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_SET_NOTIFY_ON_CANCEL)
+#define GRPC_STATS_INC_CALL_COMBINER_CANCELLED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CALL_COMBINER_CANCELLED)
+#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_SHORT_ITEMS)
+#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_LONG_ITEMS() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_LONG_ITEMS)
+#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_SCHEDULED_TO_SELF)
+#define GRPC_STATS_INC_EXECUTOR_WAKEUP_INITIATED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_WAKEUP_INITIATED)
+#define GRPC_STATS_INC_EXECUTOR_QUEUE_DRAINED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_QUEUE_DRAINED)
+#define GRPC_STATS_INC_EXECUTOR_PUSH_RETRIES() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_EXECUTOR_PUSH_RETRIES)
+#define GRPC_STATS_INC_SERVER_REQUESTED_CALLS() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_REQUESTED_CALLS)
+#define GRPC_STATS_INC_SERVER_SLOWPATH_REQUESTS_QUEUED() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SERVER_SLOWPATH_REQUESTS_QUEUED)
+#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_FAILURES() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_FAILURES)
+#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_SUCCESSES() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRYLOCK_SUCCESSES)
+#define GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES() \
+ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES)
+#define GRPC_STATS_INC_CALL_INITIAL_SIZE(value) \
+ grpc_stats_inc_call_initial_size((int)(value))
+void grpc_stats_inc_call_initial_size(int x);
+#define GRPC_STATS_INC_POLL_EVENTS_RETURNED(value) \
+ grpc_stats_inc_poll_events_returned((int)(value))
+void grpc_stats_inc_poll_events_returned(int x);
+#define GRPC_STATS_INC_TCP_WRITE_SIZE(value) \
+ grpc_stats_inc_tcp_write_size((int)(value))
+void grpc_stats_inc_tcp_write_size(int x);
+#define GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(value) \
+ grpc_stats_inc_tcp_write_iov_size((int)(value))
+void grpc_stats_inc_tcp_write_iov_size(int x);
+#define GRPC_STATS_INC_TCP_READ_SIZE(value) \
+ grpc_stats_inc_tcp_read_size((int)(value))
+void grpc_stats_inc_tcp_read_size(int x);
+#define GRPC_STATS_INC_TCP_READ_OFFER(value) \
+ grpc_stats_inc_tcp_read_offer((int)(value))
+void grpc_stats_inc_tcp_read_offer(int x);
+#define GRPC_STATS_INC_TCP_READ_OFFER_IOV_SIZE(value) \
+ grpc_stats_inc_tcp_read_offer_iov_size((int)(value))
+void grpc_stats_inc_tcp_read_offer_iov_size(int x);
+#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE(value) \
+ grpc_stats_inc_http2_send_message_size((int)(value))
+void grpc_stats_inc_http2_send_message_size(int x);
+#define GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE(value) \
+ grpc_stats_inc_http2_send_initial_metadata_per_write((int)(value))
+void grpc_stats_inc_http2_send_initial_metadata_per_write(int x);
+#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(value) \
+ grpc_stats_inc_http2_send_message_per_write((int)(value))
+void grpc_stats_inc_http2_send_message_per_write(int x);
+#define GRPC_STATS_INC_HTTP2_SEND_TRAILING_METADATA_PER_WRITE(value) \
+ grpc_stats_inc_http2_send_trailing_metadata_per_write((int)(value))
+void grpc_stats_inc_http2_send_trailing_metadata_per_write(int x);
+#define GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(value) \
+ grpc_stats_inc_http2_send_flowctl_per_write((int)(value))
+void grpc_stats_inc_http2_send_flowctl_per_write(int x);
+#define GRPC_STATS_INC_SERVER_CQS_CHECKED(value) \
+ grpc_stats_inc_server_cqs_checked((int)(value))
+void grpc_stats_inc_server_cqs_checked(int x);
#else
#define GRPC_STATS_INC_CLIENT_CALLS_CREATED()
#define GRPC_STATS_INC_SERVER_CALLS_CREATED()
@@ -547,9 +547,9 @@ void grpc_stats_inc_server_cqs_checked(int x);
#define GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(value)
#define GRPC_STATS_INC_SERVER_CQS_CHECKED(value)
#endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */
-extern const int grpc_stats_histo_buckets[13];
-extern const int grpc_stats_histo_start[13];
-extern const int* const grpc_stats_histo_bucket_boundaries[13];
-extern void (*const grpc_stats_inc_histogram[13])(int x);
-
-#endif /* GRPC_CORE_LIB_DEBUG_STATS_DATA_H */
+extern const int grpc_stats_histo_buckets[13];
+extern const int grpc_stats_histo_start[13];
+extern const int* const grpc_stats_histo_bucket_boundaries[13];
+extern void (*const grpc_stats_inc_histogram[13])(int x);
+
+#endif /* GRPC_CORE_LIB_DEBUG_STATS_DATA_H */
diff --git a/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql b/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql
index 7d1ab1dae9b..b8b3d431427 100644
--- a/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql
+++ b/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql
@@ -1,98 +1,98 @@
-client_calls_created_per_iteration:FLOAT,
-server_calls_created_per_iteration:FLOAT,
-cqs_created_per_iteration:FLOAT,
-client_channels_created_per_iteration:FLOAT,
-client_subchannels_created_per_iteration:FLOAT,
-server_channels_created_per_iteration:FLOAT,
-syscall_poll_per_iteration:FLOAT,
-syscall_wait_per_iteration:FLOAT,
-pollset_kick_per_iteration:FLOAT,
-pollset_kicked_without_poller_per_iteration:FLOAT,
-pollset_kicked_again_per_iteration:FLOAT,
-pollset_kick_wakeup_fd_per_iteration:FLOAT,
-pollset_kick_wakeup_cv_per_iteration:FLOAT,
-pollset_kick_own_thread_per_iteration:FLOAT,
+client_calls_created_per_iteration:FLOAT,
+server_calls_created_per_iteration:FLOAT,
+cqs_created_per_iteration:FLOAT,
+client_channels_created_per_iteration:FLOAT,
+client_subchannels_created_per_iteration:FLOAT,
+server_channels_created_per_iteration:FLOAT,
+syscall_poll_per_iteration:FLOAT,
+syscall_wait_per_iteration:FLOAT,
+pollset_kick_per_iteration:FLOAT,
+pollset_kicked_without_poller_per_iteration:FLOAT,
+pollset_kicked_again_per_iteration:FLOAT,
+pollset_kick_wakeup_fd_per_iteration:FLOAT,
+pollset_kick_wakeup_cv_per_iteration:FLOAT,
+pollset_kick_own_thread_per_iteration:FLOAT,
syscall_epoll_ctl_per_iteration:FLOAT,
pollset_fd_cache_hits_per_iteration:FLOAT,
-histogram_slow_lookups_per_iteration:FLOAT,
-syscall_write_per_iteration:FLOAT,
-syscall_read_per_iteration:FLOAT,
-tcp_backup_pollers_created_per_iteration:FLOAT,
-tcp_backup_poller_polls_per_iteration:FLOAT,
-http2_op_batches_per_iteration:FLOAT,
-http2_op_cancel_per_iteration:FLOAT,
-http2_op_send_initial_metadata_per_iteration:FLOAT,
-http2_op_send_message_per_iteration:FLOAT,
-http2_op_send_trailing_metadata_per_iteration:FLOAT,
-http2_op_recv_initial_metadata_per_iteration:FLOAT,
-http2_op_recv_message_per_iteration:FLOAT,
-http2_op_recv_trailing_metadata_per_iteration:FLOAT,
-http2_settings_writes_per_iteration:FLOAT,
-http2_pings_sent_per_iteration:FLOAT,
-http2_writes_begun_per_iteration:FLOAT,
-http2_writes_offloaded_per_iteration:FLOAT,
-http2_writes_continued_per_iteration:FLOAT,
-http2_partial_writes_per_iteration:FLOAT,
-http2_initiate_write_due_to_initial_write_per_iteration:FLOAT,
-http2_initiate_write_due_to_start_new_stream_per_iteration:FLOAT,
-http2_initiate_write_due_to_send_message_per_iteration:FLOAT,
-http2_initiate_write_due_to_send_initial_metadata_per_iteration:FLOAT,
-http2_initiate_write_due_to_send_trailing_metadata_per_iteration:FLOAT,
-http2_initiate_write_due_to_retry_send_ping_per_iteration:FLOAT,
-http2_initiate_write_due_to_continue_pings_per_iteration:FLOAT,
-http2_initiate_write_due_to_goaway_sent_per_iteration:FLOAT,
-http2_initiate_write_due_to_rst_stream_per_iteration:FLOAT,
-http2_initiate_write_due_to_close_from_api_per_iteration:FLOAT,
-http2_initiate_write_due_to_stream_flow_control_per_iteration:FLOAT,
-http2_initiate_write_due_to_transport_flow_control_per_iteration:FLOAT,
-http2_initiate_write_due_to_send_settings_per_iteration:FLOAT,
-http2_initiate_write_due_to_bdp_estimator_ping_per_iteration:FLOAT,
-http2_initiate_write_due_to_flow_control_unstalled_by_setting_per_iteration:FLOAT,
-http2_initiate_write_due_to_flow_control_unstalled_by_update_per_iteration:FLOAT,
-http2_initiate_write_due_to_application_ping_per_iteration:FLOAT,
-http2_initiate_write_due_to_keepalive_ping_per_iteration:FLOAT,
-http2_initiate_write_due_to_transport_flow_control_unstalled_per_iteration:FLOAT,
-http2_initiate_write_due_to_ping_response_per_iteration:FLOAT,
-http2_initiate_write_due_to_force_rst_stream_per_iteration:FLOAT,
-http2_spurious_writes_begun_per_iteration:FLOAT,
-hpack_recv_indexed_per_iteration:FLOAT,
-hpack_recv_lithdr_incidx_per_iteration:FLOAT,
-hpack_recv_lithdr_incidx_v_per_iteration:FLOAT,
-hpack_recv_lithdr_notidx_per_iteration:FLOAT,
-hpack_recv_lithdr_notidx_v_per_iteration:FLOAT,
-hpack_recv_lithdr_nvridx_per_iteration:FLOAT,
-hpack_recv_lithdr_nvridx_v_per_iteration:FLOAT,
-hpack_recv_uncompressed_per_iteration:FLOAT,
-hpack_recv_huffman_per_iteration:FLOAT,
-hpack_recv_binary_per_iteration:FLOAT,
-hpack_recv_binary_base64_per_iteration:FLOAT,
-hpack_send_indexed_per_iteration:FLOAT,
-hpack_send_lithdr_incidx_per_iteration:FLOAT,
-hpack_send_lithdr_incidx_v_per_iteration:FLOAT,
-hpack_send_lithdr_notidx_per_iteration:FLOAT,
-hpack_send_lithdr_notidx_v_per_iteration:FLOAT,
-hpack_send_lithdr_nvridx_per_iteration:FLOAT,
-hpack_send_lithdr_nvridx_v_per_iteration:FLOAT,
-hpack_send_uncompressed_per_iteration:FLOAT,
-hpack_send_huffman_per_iteration:FLOAT,
-hpack_send_binary_per_iteration:FLOAT,
-hpack_send_binary_base64_per_iteration:FLOAT,
-combiner_locks_initiated_per_iteration:FLOAT,
-combiner_locks_scheduled_items_per_iteration:FLOAT,
-combiner_locks_scheduled_final_items_per_iteration:FLOAT,
-combiner_locks_offloaded_per_iteration:FLOAT,
-call_combiner_locks_initiated_per_iteration:FLOAT,
-call_combiner_locks_scheduled_items_per_iteration:FLOAT,
-call_combiner_set_notify_on_cancel_per_iteration:FLOAT,
-call_combiner_cancelled_per_iteration:FLOAT,
-executor_scheduled_short_items_per_iteration:FLOAT,
-executor_scheduled_long_items_per_iteration:FLOAT,
-executor_scheduled_to_self_per_iteration:FLOAT,
-executor_wakeup_initiated_per_iteration:FLOAT,
-executor_queue_drained_per_iteration:FLOAT,
-executor_push_retries_per_iteration:FLOAT,
-server_requested_calls_per_iteration:FLOAT,
-server_slowpath_requests_queued_per_iteration:FLOAT,
-cq_ev_queue_trylock_failures_per_iteration:FLOAT,
-cq_ev_queue_trylock_successes_per_iteration:FLOAT,
-cq_ev_queue_transient_pop_failures_per_iteration:FLOAT
+histogram_slow_lookups_per_iteration:FLOAT,
+syscall_write_per_iteration:FLOAT,
+syscall_read_per_iteration:FLOAT,
+tcp_backup_pollers_created_per_iteration:FLOAT,
+tcp_backup_poller_polls_per_iteration:FLOAT,
+http2_op_batches_per_iteration:FLOAT,
+http2_op_cancel_per_iteration:FLOAT,
+http2_op_send_initial_metadata_per_iteration:FLOAT,
+http2_op_send_message_per_iteration:FLOAT,
+http2_op_send_trailing_metadata_per_iteration:FLOAT,
+http2_op_recv_initial_metadata_per_iteration:FLOAT,
+http2_op_recv_message_per_iteration:FLOAT,
+http2_op_recv_trailing_metadata_per_iteration:FLOAT,
+http2_settings_writes_per_iteration:FLOAT,
+http2_pings_sent_per_iteration:FLOAT,
+http2_writes_begun_per_iteration:FLOAT,
+http2_writes_offloaded_per_iteration:FLOAT,
+http2_writes_continued_per_iteration:FLOAT,
+http2_partial_writes_per_iteration:FLOAT,
+http2_initiate_write_due_to_initial_write_per_iteration:FLOAT,
+http2_initiate_write_due_to_start_new_stream_per_iteration:FLOAT,
+http2_initiate_write_due_to_send_message_per_iteration:FLOAT,
+http2_initiate_write_due_to_send_initial_metadata_per_iteration:FLOAT,
+http2_initiate_write_due_to_send_trailing_metadata_per_iteration:FLOAT,
+http2_initiate_write_due_to_retry_send_ping_per_iteration:FLOAT,
+http2_initiate_write_due_to_continue_pings_per_iteration:FLOAT,
+http2_initiate_write_due_to_goaway_sent_per_iteration:FLOAT,
+http2_initiate_write_due_to_rst_stream_per_iteration:FLOAT,
+http2_initiate_write_due_to_close_from_api_per_iteration:FLOAT,
+http2_initiate_write_due_to_stream_flow_control_per_iteration:FLOAT,
+http2_initiate_write_due_to_transport_flow_control_per_iteration:FLOAT,
+http2_initiate_write_due_to_send_settings_per_iteration:FLOAT,
+http2_initiate_write_due_to_bdp_estimator_ping_per_iteration:FLOAT,
+http2_initiate_write_due_to_flow_control_unstalled_by_setting_per_iteration:FLOAT,
+http2_initiate_write_due_to_flow_control_unstalled_by_update_per_iteration:FLOAT,
+http2_initiate_write_due_to_application_ping_per_iteration:FLOAT,
+http2_initiate_write_due_to_keepalive_ping_per_iteration:FLOAT,
+http2_initiate_write_due_to_transport_flow_control_unstalled_per_iteration:FLOAT,
+http2_initiate_write_due_to_ping_response_per_iteration:FLOAT,
+http2_initiate_write_due_to_force_rst_stream_per_iteration:FLOAT,
+http2_spurious_writes_begun_per_iteration:FLOAT,
+hpack_recv_indexed_per_iteration:FLOAT,
+hpack_recv_lithdr_incidx_per_iteration:FLOAT,
+hpack_recv_lithdr_incidx_v_per_iteration:FLOAT,
+hpack_recv_lithdr_notidx_per_iteration:FLOAT,
+hpack_recv_lithdr_notidx_v_per_iteration:FLOAT,
+hpack_recv_lithdr_nvridx_per_iteration:FLOAT,
+hpack_recv_lithdr_nvridx_v_per_iteration:FLOAT,
+hpack_recv_uncompressed_per_iteration:FLOAT,
+hpack_recv_huffman_per_iteration:FLOAT,
+hpack_recv_binary_per_iteration:FLOAT,
+hpack_recv_binary_base64_per_iteration:FLOAT,
+hpack_send_indexed_per_iteration:FLOAT,
+hpack_send_lithdr_incidx_per_iteration:FLOAT,
+hpack_send_lithdr_incidx_v_per_iteration:FLOAT,
+hpack_send_lithdr_notidx_per_iteration:FLOAT,
+hpack_send_lithdr_notidx_v_per_iteration:FLOAT,
+hpack_send_lithdr_nvridx_per_iteration:FLOAT,
+hpack_send_lithdr_nvridx_v_per_iteration:FLOAT,
+hpack_send_uncompressed_per_iteration:FLOAT,
+hpack_send_huffman_per_iteration:FLOAT,
+hpack_send_binary_per_iteration:FLOAT,
+hpack_send_binary_base64_per_iteration:FLOAT,
+combiner_locks_initiated_per_iteration:FLOAT,
+combiner_locks_scheduled_items_per_iteration:FLOAT,
+combiner_locks_scheduled_final_items_per_iteration:FLOAT,
+combiner_locks_offloaded_per_iteration:FLOAT,
+call_combiner_locks_initiated_per_iteration:FLOAT,
+call_combiner_locks_scheduled_items_per_iteration:FLOAT,
+call_combiner_set_notify_on_cancel_per_iteration:FLOAT,
+call_combiner_cancelled_per_iteration:FLOAT,
+executor_scheduled_short_items_per_iteration:FLOAT,
+executor_scheduled_long_items_per_iteration:FLOAT,
+executor_scheduled_to_self_per_iteration:FLOAT,
+executor_wakeup_initiated_per_iteration:FLOAT,
+executor_queue_drained_per_iteration:FLOAT,
+executor_push_retries_per_iteration:FLOAT,
+server_requested_calls_per_iteration:FLOAT,
+server_slowpath_requests_queued_per_iteration:FLOAT,
+cq_ev_queue_trylock_failures_per_iteration:FLOAT,
+cq_ev_queue_trylock_successes_per_iteration:FLOAT,
+cq_ev_queue_transient_pop_failures_per_iteration:FLOAT
diff --git a/contrib/libs/grpc/src/core/lib/debug/trace.cc b/contrib/libs/grpc/src/core/lib/debug/trace.cc
index 84c0a3805d3..1ebcd50972e 100644
--- a/contrib/libs/grpc/src/core/lib/debug/trace.cc
+++ b/contrib/libs/grpc/src/core/lib/debug/trace.cc
@@ -1,154 +1,154 @@
-/*
- *
- * 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/debug/trace.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/lib/debug/trace.h"
+
+#include <string.h>
#include <type_traits>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
+
+#include <grpc/grpc.h>
+#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.");
-int grpc_tracer_set_enabled(const char* name, int enabled);
-
-namespace grpc_core {
-
-TraceFlag* TraceFlagList::root_tracer_ = nullptr;
-
-bool TraceFlagList::Set(const char* name, bool enabled) {
- TraceFlag* t;
- if (0 == strcmp(name, "all")) {
- for (t = root_tracer_; t; t = t->next_tracer_) {
- t->set_enabled(enabled);
- }
- } else if (0 == strcmp(name, "list_tracers")) {
- LogAllTracers();
- } else if (0 == strcmp(name, "refcount")) {
- for (t = root_tracer_; t; t = t->next_tracer_) {
- if (strstr(t->name_, "refcount") != nullptr) {
- t->set_enabled(enabled);
- }
- }
- } else {
- bool found = false;
- for (t = root_tracer_; t; t = t->next_tracer_) {
- if (0 == strcmp(name, t->name_)) {
- t->set_enabled(enabled);
- found = true;
- }
- }
- // check for unknowns, but ignore "", to allow to GRPC_TRACE=
- if (!found && 0 != strcmp(name, "")) {
- gpr_log(GPR_ERROR, "Unknown trace var: '%s'", name);
- return false; /* early return */
- }
- }
- return true;
-}
-
-void TraceFlagList::Add(TraceFlag* flag) {
- flag->next_tracer_ = root_tracer_;
- root_tracer_ = flag;
-}
-
-void TraceFlagList::LogAllTracers() {
- gpr_log(GPR_DEBUG, "available tracers:");
- TraceFlag* t;
- for (t = root_tracer_; t != nullptr; t = t->next_tracer_) {
- gpr_log(GPR_DEBUG, "\t%s", t->name_);
- }
-}
-
-// Flags register themselves on the list during construction
-TraceFlag::TraceFlag(bool default_enabled, const char* name) : name_(name) {
+int grpc_tracer_set_enabled(const char* name, int enabled);
+
+namespace grpc_core {
+
+TraceFlag* TraceFlagList::root_tracer_ = nullptr;
+
+bool TraceFlagList::Set(const char* name, bool enabled) {
+ TraceFlag* t;
+ if (0 == strcmp(name, "all")) {
+ for (t = root_tracer_; t; t = t->next_tracer_) {
+ t->set_enabled(enabled);
+ }
+ } else if (0 == strcmp(name, "list_tracers")) {
+ LogAllTracers();
+ } else if (0 == strcmp(name, "refcount")) {
+ for (t = root_tracer_; t; t = t->next_tracer_) {
+ if (strstr(t->name_, "refcount") != nullptr) {
+ t->set_enabled(enabled);
+ }
+ }
+ } else {
+ bool found = false;
+ for (t = root_tracer_; t; t = t->next_tracer_) {
+ if (0 == strcmp(name, t->name_)) {
+ t->set_enabled(enabled);
+ found = true;
+ }
+ }
+ // check for unknowns, but ignore "", to allow to GRPC_TRACE=
+ if (!found && 0 != strcmp(name, "")) {
+ gpr_log(GPR_ERROR, "Unknown trace var: '%s'", name);
+ return false; /* early return */
+ }
+ }
+ return true;
+}
+
+void TraceFlagList::Add(TraceFlag* flag) {
+ flag->next_tracer_ = root_tracer_;
+ root_tracer_ = flag;
+}
+
+void TraceFlagList::LogAllTracers() {
+ gpr_log(GPR_DEBUG, "available tracers:");
+ TraceFlag* t;
+ for (t = root_tracer_; t != nullptr; t = t->next_tracer_) {
+ gpr_log(GPR_DEBUG, "\t%s", t->name_);
+ }
+}
+
+// Flags register themselves on the list during construction
+TraceFlag::TraceFlag(bool default_enabled, const char* name) : name_(name) {
static_assert(std::is_trivially_destructible<TraceFlag>::value,
"TraceFlag needs to be trivially destructible.");
- set_enabled(default_enabled);
- TraceFlagList::Add(this);
-}
-
-} // namespace grpc_core
-
-static void add(const char* beg, const char* end, char*** ss, size_t* ns) {
- size_t n = *ns;
- size_t np = n + 1;
- char* s;
- size_t len;
- GPR_ASSERT(end >= beg);
- len = static_cast<size_t>(end - beg);
- s = static_cast<char*>(gpr_malloc(len + 1));
- memcpy(s, beg, len);
- s[len] = 0;
- *ss = static_cast<char**>(gpr_realloc(*ss, sizeof(char**) * np));
- (*ss)[n] = s;
- *ns = np;
-}
-
-static void split(const char* s, char*** ss, size_t* ns) {
- const char* c = strchr(s, ',');
- if (c == nullptr) {
- add(s, s + strlen(s), ss, ns);
- } else {
- add(s, c, ss, ns);
- split(c + 1, ss, ns);
- }
-}
-
-static void parse(const char* s) {
- char** strings = nullptr;
- size_t nstrings = 0;
- size_t i;
- split(s, &strings, &nstrings);
-
- for (i = 0; i < nstrings; i++) {
- if (strings[i][0] == '-') {
- grpc_core::TraceFlagList::Set(strings[i] + 1, false);
- } else {
- grpc_core::TraceFlagList::Set(strings[i], true);
- }
- }
-
- for (i = 0; i < nstrings; i++) {
- gpr_free(strings[i]);
- }
- gpr_free(strings);
-}
-
+ set_enabled(default_enabled);
+ TraceFlagList::Add(this);
+}
+
+} // namespace grpc_core
+
+static void add(const char* beg, const char* end, char*** ss, size_t* ns) {
+ size_t n = *ns;
+ size_t np = n + 1;
+ char* s;
+ size_t len;
+ GPR_ASSERT(end >= beg);
+ len = static_cast<size_t>(end - beg);
+ s = static_cast<char*>(gpr_malloc(len + 1));
+ memcpy(s, beg, len);
+ s[len] = 0;
+ *ss = static_cast<char**>(gpr_realloc(*ss, sizeof(char**) * np));
+ (*ss)[n] = s;
+ *ns = np;
+}
+
+static void split(const char* s, char*** ss, size_t* ns) {
+ const char* c = strchr(s, ',');
+ if (c == nullptr) {
+ add(s, s + strlen(s), ss, ns);
+ } else {
+ add(s, c, ss, ns);
+ split(c + 1, ss, ns);
+ }
+}
+
+static void parse(const char* s) {
+ char** strings = nullptr;
+ size_t nstrings = 0;
+ size_t i;
+ split(s, &strings, &nstrings);
+
+ for (i = 0; i < nstrings; i++) {
+ if (strings[i][0] == '-') {
+ grpc_core::TraceFlagList::Set(strings[i] + 1, false);
+ } else {
+ grpc_core::TraceFlagList::Set(strings[i], true);
+ }
+ }
+
+ for (i = 0; i < nstrings; i++) {
+ gpr_free(strings[i]);
+ }
+ 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_shutdown(void) {}
-
-int grpc_tracer_set_enabled(const char* name, int enabled) {
- return grpc_core::TraceFlagList::Set(name, enabled != 0);
-}
+void grpc_tracer_shutdown(void) {}
+
+int grpc_tracer_set_enabled(const char* name, int enabled) {
+ return grpc_core::TraceFlagList::Set(name, enabled != 0);
+}
diff --git a/contrib/libs/grpc/src/core/lib/debug/trace.h b/contrib/libs/grpc/src/core/lib/debug/trace.h
index ac7b40e58a5..0b0311a4d0d 100644
--- a/contrib/libs/grpc/src/core/lib/debug/trace.h
+++ b/contrib/libs/grpc/src/core/lib/debug/trace.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,52 +21,52 @@
#include <grpc/support/port_platform.h>
-#include <grpc/support/atm.h>
-#include <stdbool.h>
-
+#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.
-void grpc_tracer_init(const char* env_var_name);
+void grpc_tracer_init(const char* env_var_name);
void grpc_tracer_init();
void grpc_tracer_shutdown(void);
-#if defined(__has_feature)
-#if __has_feature(thread_sanitizer)
-#define GRPC_THREADSAFE_TRACER
-#endif
-#endif
-
-namespace grpc_core {
-
-class TraceFlag;
-class TraceFlagList {
- public:
- static bool Set(const char* name, bool enabled);
- static void Add(TraceFlag* flag);
-
- private:
- static void LogAllTracers();
- static TraceFlag* root_tracer_;
-};
-
-namespace testing {
-void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag);
-}
-
-class TraceFlag {
- public:
- TraceFlag(bool default_enabled, const char* name);
+#if defined(__has_feature)
+#if __has_feature(thread_sanitizer)
+#define GRPC_THREADSAFE_TRACER
+#endif
+#endif
+
+namespace grpc_core {
+
+class TraceFlag;
+class TraceFlagList {
+ public:
+ static bool Set(const char* name, bool enabled);
+ static void Add(TraceFlag* flag);
+
+ private:
+ static void LogAllTracers();
+ static TraceFlag* root_tracer_;
+};
+
+namespace testing {
+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() = default;
-
- const char* name() const { return name_; }
-
+
+ const char* name() const { return name_; }
+
// Use the symbol GRPC_USE_TRACERS to determine if tracers will be enabled in
// opt builds (tracers are always on in dbg builds). The default in OSS is for
// tracers to be on since we support binary distributions of gRPC for the
@@ -77,55 +77,55 @@ class TraceFlag {
// 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() {
-#ifdef GRPC_THREADSAFE_TRACER
- return gpr_atm_no_barrier_load(&value_) != 0;
-#else
- return value_;
-#endif // GRPC_THREADSAFE_TRACER
- }
+ bool enabled() {
+#ifdef GRPC_THREADSAFE_TRACER
+ return gpr_atm_no_barrier_load(&value_) != 0;
+#else
+ return value_;
+#endif // GRPC_THREADSAFE_TRACER
+ }
#else
bool enabled() { return false; }
#endif /* defined(GRPC_USE_TRACERS) || !defined(NDEBUG) */
-
- private:
- friend void grpc_core::testing::grpc_tracer_enable_flag(TraceFlag* flag);
- friend class TraceFlagList;
-
- void set_enabled(bool enabled) {
-#ifdef GRPC_THREADSAFE_TRACER
- gpr_atm_no_barrier_store(&value_, enabled);
-#else
- value_ = enabled;
-#endif
- }
-
- TraceFlag* next_tracer_;
- const char* const name_;
-#ifdef GRPC_THREADSAFE_TRACER
- gpr_atm value_;
-#else
- bool value_;
-#endif
-};
-
+
+ private:
+ friend void grpc_core::testing::grpc_tracer_enable_flag(TraceFlag* flag);
+ friend class TraceFlagList;
+
+ void set_enabled(bool enabled) {
+#ifdef GRPC_THREADSAFE_TRACER
+ gpr_atm_no_barrier_store(&value_, enabled);
+#else
+ value_ = enabled;
+#endif
+ }
+
+ TraceFlag* next_tracer_;
+ const char* const name_;
+#ifdef GRPC_THREADSAFE_TRACER
+ gpr_atm value_;
+#else
+ bool value_;
+#endif
+};
+
#define GRPC_TRACE_FLAG_ENABLED(f) GPR_UNLIKELY((f).enabled())
-#ifndef NDEBUG
-typedef TraceFlag DebugOnlyTraceFlag;
-#else
-class DebugOnlyTraceFlag {
- public:
+#ifndef NDEBUG
+typedef TraceFlag DebugOnlyTraceFlag;
+#else
+class DebugOnlyTraceFlag {
+ public:
constexpr DebugOnlyTraceFlag(bool /*default_enabled*/, const char* /*name*/) {
}
constexpr bool enabled() const { return false; }
constexpr const char* name() const { return "DebugOnlyTraceFlag"; }
-
- private:
+
+ private:
void set_enabled(bool /*enabled*/) {}
-};
-#endif
-
-} // namespace grpc_core
-
+};
+#endif
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_LIB_DEBUG_TRACE_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/README.md b/contrib/libs/grpc/src/core/lib/gpr/README.md
index 21fb0c796db..65c824a71d5 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/README.md
+++ b/contrib/libs/grpc/src/core/lib/gpr/README.md
@@ -1,8 +1,8 @@
-# GPR - Google Portable Runtime for C
-
-The files in this directory contain basic utility code and platform
-abstractions for C code. None of this code is gRPC-specific; anything
-here may also be useful for other open source projects written in C.
-
-Note that this is one of the few places in src/core where we allow
-the use of portability macros.
+# GPR - Google Portable Runtime for C
+
+The files in this directory contain basic utility code and platform
+abstractions for C code. None of this code is gRPC-specific; anything
+here may also be useful for other open source projects written in C.
+
+Note that this is one of the few places in src/core where we allow
+the use of portability macros.
diff --git a/contrib/libs/grpc/src/core/lib/gpr/alloc.cc b/contrib/libs/grpc/src/core/lib/gpr/alloc.cc
index 8c7345b7db5..3fa566e95fa 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/alloc.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/alloc.cc
@@ -1,74 +1,74 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-
-#include <grpc/support/log.h>
-#include <stdlib.h>
-#include <string.h>
-#include "src/core/lib/profiling/timers.h"
-
-void* gpr_malloc(size_t size) {
- GPR_TIMER_SCOPE("gpr_malloc", 0);
- void* p;
- if (size == 0) return 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 <grpc/support/port_platform.h>
+
+#include <grpc/support/alloc.h>
+
+#include <grpc/support/log.h>
+#include <stdlib.h>
+#include <string.h>
+#include "src/core/lib/profiling/timers.h"
+
+void* gpr_malloc(size_t size) {
+ GPR_TIMER_SCOPE("gpr_malloc", 0);
+ void* p;
+ if (size == 0) return nullptr;
p = malloc(size);
- if (!p) {
- abort();
- }
- return p;
-}
-
-void* gpr_zalloc(size_t size) {
- GPR_TIMER_SCOPE("gpr_zalloc", 0);
- void* p;
- if (size == 0) return nullptr;
+ if (!p) {
+ abort();
+ }
+ return p;
+}
+
+void* gpr_zalloc(size_t size) {
+ GPR_TIMER_SCOPE("gpr_zalloc", 0);
+ void* p;
+ if (size == 0) return nullptr;
p = calloc(size, 1);
- if (!p) {
- abort();
- }
- return p;
-}
-
-void gpr_free(void* p) {
- GPR_TIMER_SCOPE("gpr_free", 0);
+ if (!p) {
+ abort();
+ }
+ return p;
+}
+
+void gpr_free(void* p) {
+ GPR_TIMER_SCOPE("gpr_free", 0);
free(p);
-}
-
-void* gpr_realloc(void* p, size_t size) {
- GPR_TIMER_SCOPE("gpr_realloc", 0);
- if ((size == 0) && (p == nullptr)) return nullptr;
+}
+
+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);
- if (!p) {
- abort();
- }
- return p;
-}
-
-void* gpr_malloc_aligned(size_t size, size_t alignment) {
- GPR_ASSERT(((alignment - 1) & alignment) == 0); // Must be power of 2.
- size_t extra = alignment - 1 + sizeof(void*);
- void* p = gpr_malloc(size + extra);
- void** ret = (void**)(((uintptr_t)p + extra) & ~(alignment - 1));
- ret[-1] = p;
- return (void*)ret;
-}
-
-void gpr_free_aligned(void* ptr) { gpr_free((static_cast<void**>(ptr))[-1]); }
+ if (!p) {
+ abort();
+ }
+ return p;
+}
+
+void* gpr_malloc_aligned(size_t size, size_t alignment) {
+ GPR_ASSERT(((alignment - 1) & alignment) == 0); // Must be power of 2.
+ size_t extra = alignment - 1 + sizeof(void*);
+ void* p = gpr_malloc(size + extra);
+ void** ret = (void**)(((uintptr_t)p + extra) & ~(alignment - 1));
+ ret[-1] = p;
+ return (void*)ret;
+}
+
+void gpr_free_aligned(void* ptr) { gpr_free((static_cast<void**>(ptr))[-1]); }
diff --git a/contrib/libs/grpc/src/core/lib/gpr/arena.h b/contrib/libs/grpc/src/core/lib/gpr/arena.h
index 4d70695149c..8b997e0810d 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/arena.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/arena.h
@@ -1,47 +1,47 @@
-/*
- *
- * 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
+/*
+ *
+ * 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
// 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>
-
+
+#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"
-
+
// 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
+// 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(); }
-// Allocate \a size bytes from the arena
+// Allocate \a size bytes from the arena
inline void* gpr_arena_alloc(gpr_arena* arena, size_t size) {
return arena->Alloc(size);
}
-
-#endif /* GRPC_CORE_LIB_GPR_ARENA_H */
+
+#endif /* GRPC_CORE_LIB_GPR_ARENA_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/atm.cc b/contrib/libs/grpc/src/core/lib/gpr/atm.cc
index 649d400d38e..a58d1c91aba 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/atm.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/atm.cc
@@ -1,35 +1,35 @@
-/*
- *
- * 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 <grpc/support/atm.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-gpr_atm gpr_atm_no_barrier_clamped_add(gpr_atm* value, gpr_atm delta,
- gpr_atm min, gpr_atm max) {
- gpr_atm current_value;
- gpr_atm new_value;
- do {
- current_value = gpr_atm_no_barrier_load(value);
- new_value = GPR_CLAMP(current_value + delta, min, max);
- if (new_value == current_value) break;
- } while (!gpr_atm_no_barrier_cas(value, current_value, new_value));
- return new_value;
-}
+/*
+ *
+ * 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 <grpc/support/atm.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+gpr_atm gpr_atm_no_barrier_clamped_add(gpr_atm* value, gpr_atm delta,
+ gpr_atm min, gpr_atm max) {
+ gpr_atm current_value;
+ gpr_atm new_value;
+ do {
+ current_value = gpr_atm_no_barrier_load(value);
+ new_value = GPR_CLAMP(current_value + delta, min, max);
+ if (new_value == current_value) break;
+ } while (!gpr_atm_no_barrier_cas(value, current_value, new_value));
+ return new_value;
+}
diff --git a/contrib/libs/grpc/src/core/lib/gpr/cpu_iphone.cc b/contrib/libs/grpc/src/core/lib/gpr/cpu_iphone.cc
index 2847e03ba58..cae236cbf4a 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/cpu_iphone.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/cpu_iphone.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/cpu.h>
-
-#ifdef GPR_CPU_IPHONE
-
-/* Probably 2 instead of 1, but see comment on gpr_cpu_current_cpu. */
-unsigned gpr_cpu_num_cores(void) { return 1; }
-
-/* Most code that's using this is using it to shard across work queues. So
- unless profiling shows it's a problem or there appears a way to detect the
- currently running CPU core, let's have it shard the default way.
- Note that the interface in cpu.h lets gpr_cpu_num_cores return 0, but doing
- it makes it impossible for gpr_cpu_current_cpu to satisfy its stated range,
- and some code might be relying on it. */
-unsigned gpr_cpu_current_cpu(void) { return 0; }
-
-#endif /* GPR_CPU_IPHONE */
+/*
+ *
+ * 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 <grpc/support/cpu.h>
+
+#ifdef GPR_CPU_IPHONE
+
+/* Probably 2 instead of 1, but see comment on gpr_cpu_current_cpu. */
+unsigned gpr_cpu_num_cores(void) { return 1; }
+
+/* Most code that's using this is using it to shard across work queues. So
+ unless profiling shows it's a problem or there appears a way to detect the
+ currently running CPU core, let's have it shard the default way.
+ Note that the interface in cpu.h lets gpr_cpu_num_cores return 0, but doing
+ it makes it impossible for gpr_cpu_current_cpu to satisfy its stated range,
+ and some code might be relying on it. */
+unsigned gpr_cpu_current_cpu(void) { return 0; }
+
+#endif /* GPR_CPU_IPHONE */
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 2e16e3d992e..7e23f4d4c16 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/cpu_linux.cc
@@ -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 _GNU_SOURCE
-#define _GNU_SOURCE
-#endif /* _GNU_SOURCE */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_CPU_LINUX
-
-#include <errno.h>
-#include <sched.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <grpc/support/cpu.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-static int ncpus = 0;
-
-static void init_num_cpus() {
-#ifndef GPR_MUSL_LIBC_COMPAT
- if (sched_getcpu() < 0) {
- gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));
- ncpus = 1;
- return;
- }
-#endif
- /* This must be signed. sysconf returns -1 when the number cannot be
- determined */
- ncpus = static_cast<int>(sysconf(_SC_NPROCESSORS_CONF));
- if (ncpus < 1) {
- gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
- ncpus = 1;
- }
-}
-
-unsigned gpr_cpu_num_cores(void) {
- static gpr_once once = GPR_ONCE_INIT;
- gpr_once_init(&once, init_num_cpus);
- return static_cast<unsigned>(ncpus);
-}
-
-unsigned gpr_cpu_current_cpu(void) {
-#ifdef GPR_MUSL_LIBC_COMPAT
- // sched_getcpu() is undefined on musl
- return 0;
-#else
- if (gpr_cpu_num_cores() == 1) {
- return 0;
- }
- int cpu = sched_getcpu();
- if (cpu < 0) {
- gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));
- return 0;
- }
- if (static_cast<unsigned>(cpu) >= gpr_cpu_num_cores()) {
+/*
+ *
+ * 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 _GNU_SOURCE
+#define _GNU_SOURCE
+#endif /* _GNU_SOURCE */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_CPU_LINUX
+
+#include <errno.h>
+#include <sched.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grpc/support/cpu.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+static int ncpus = 0;
+
+static void init_num_cpus() {
+#ifndef GPR_MUSL_LIBC_COMPAT
+ if (sched_getcpu() < 0) {
+ gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));
+ ncpus = 1;
+ return;
+ }
+#endif
+ /* This must be signed. sysconf returns -1 when the number cannot be
+ determined */
+ ncpus = static_cast<int>(sysconf(_SC_NPROCESSORS_CONF));
+ if (ncpus < 1) {
+ gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
+ ncpus = 1;
+ }
+}
+
+unsigned gpr_cpu_num_cores(void) {
+ static gpr_once once = GPR_ONCE_INIT;
+ gpr_once_init(&once, init_num_cpus);
+ return static_cast<unsigned>(ncpus);
+}
+
+unsigned gpr_cpu_current_cpu(void) {
+#ifdef GPR_MUSL_LIBC_COMPAT
+ // sched_getcpu() is undefined on musl
+ return 0;
+#else
+ if (gpr_cpu_num_cores() == 1) {
+ return 0;
+ }
+ int cpu = sched_getcpu();
+ if (cpu < 0) {
+ gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));
+ return 0;
+ }
+ if (static_cast<unsigned>(cpu) >= gpr_cpu_num_cores()) {
gpr_log(GPR_DEBUG, "Cannot handle hot-plugged CPUs");
- return 0;
- }
- return static_cast<unsigned>(cpu);
-#endif
-}
-
-#endif /* GPR_CPU_LINUX */
+ return 0;
+ }
+ return static_cast<unsigned>(cpu);
+#endif
+}
+
+#endif /* GPR_CPU_LINUX */
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 982ccbd6ffe..9d45ea762be 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/cpu_posix.cc
@@ -1,83 +1,83 @@
-/*
- *
- * 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>
-
-#if defined(GPR_CPU_POSIX)
-
-#include <errno.h>
-#include <pthread.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <grpc/support/cpu.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-static long ncpus = 0;
-
-static pthread_key_t thread_id_key;
-
-static void init_ncpus() {
- ncpus = sysconf(_SC_NPROCESSORS_CONF);
- if (ncpus < 1 || ncpus > INT32_MAX) {
- gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
- ncpus = 1;
- }
-}
-
-unsigned gpr_cpu_num_cores(void) {
- static gpr_once once = GPR_ONCE_INIT;
- gpr_once_init(&once, init_ncpus);
- return (unsigned)ncpus;
-}
-
-static void delete_thread_id(void* value) {
- 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#if defined(GPR_CPU_POSIX)
+
+#include <errno.h>
+#include <pthread.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grpc/support/cpu.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+static long ncpus = 0;
+
+static pthread_key_t thread_id_key;
+
+static void init_ncpus() {
+ ncpus = sysconf(_SC_NPROCESSORS_CONF);
+ if (ncpus < 1 || ncpus > INT32_MAX) {
+ gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
+ ncpus = 1;
+ }
+}
+
+unsigned gpr_cpu_num_cores(void) {
+ static gpr_once once = GPR_ONCE_INIT;
+ gpr_once_init(&once, init_ncpus);
+ return (unsigned)ncpus;
+}
+
+static void delete_thread_id(void* value) {
+ if (value) {
free(value);
- }
-}
-
-static void init_thread_id_key(void) {
- pthread_key_create(&thread_id_key, delete_thread_id);
-}
-
-unsigned gpr_cpu_current_cpu(void) {
- /* NOTE: there's no way I know to return the actual cpu index portably...
- most code that's using this is using it to shard across work queues though,
- so here we use thread identity instead to achieve a similar though not
- identical effect */
- static gpr_once once = GPR_ONCE_INIT;
- gpr_once_init(&once, init_thread_id_key);
-
- unsigned int* thread_id =
- static_cast<unsigned int*>(pthread_getspecific(thread_id_key));
- if (thread_id == nullptr) {
+ }
+}
+
+static void init_thread_id_key(void) {
+ pthread_key_create(&thread_id_key, delete_thread_id);
+}
+
+unsigned gpr_cpu_current_cpu(void) {
+ /* NOTE: there's no way I know to return the actual cpu index portably...
+ most code that's using this is using it to shard across work queues though,
+ so here we use thread identity instead to achieve a similar though not
+ identical effect */
+ static gpr_once once = GPR_ONCE_INIT;
+ gpr_once_init(&once, init_thread_id_key);
+
+ 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)));
- pthread_setspecific(thread_id_key, thread_id);
- }
-
- return (unsigned)GPR_HASH_POINTER(thread_id, gpr_cpu_num_cores());
-}
-
-#endif /* GPR_CPU_POSIX */
+ pthread_setspecific(thread_id_key, thread_id);
+ }
+
+ return (unsigned)GPR_HASH_POINTER(thread_id, gpr_cpu_num_cores());
+}
+
+#endif /* GPR_CPU_POSIX */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/cpu_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/cpu_windows.cc
index 8d894534039..d9fb6f566e9 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/cpu_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/cpu_windows.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS
-#include <grpc/support/cpu.h>
-#include <grpc/support/log.h>
-
-unsigned gpr_cpu_num_cores(void) {
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- return si.dwNumberOfProcessors;
-}
-
-unsigned gpr_cpu_current_cpu(void) { return GetCurrentProcessorNumber(); }
-
-#endif /* GPR_WINDOWS */
+/*
+ *
+ * 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_WINDOWS
+#include <grpc/support/cpu.h>
+#include <grpc/support/log.h>
+
+unsigned gpr_cpu_num_cores(void) {
+ SYSTEM_INFO si;
+ GetSystemInfo(&si);
+ return si.dwNumberOfProcessors;
+}
+
+unsigned gpr_cpu_current_cpu(void) { return GetCurrentProcessorNumber(); }
+
+#endif /* GPR_WINDOWS */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/env.h b/contrib/libs/grpc/src/core/lib/gpr/env.h
index f5016c6fa06..3b8ec3e9ef9 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/env.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPR_ENV_H
-#define GRPC_CORE_LIB_GPR_ENV_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdio.h>
-
-/* Env utility functions */
-
-/* Gets the environment variable value with the specified 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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPR_ENV_H
+#define GRPC_CORE_LIB_GPR_ENV_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdio.h>
+
+/* 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
- gpr_free the return value if not NULL (which means that the environment
- variable exists). */
-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);
-
+ gpr_free the return value if not NULL (which means that the environment
+ variable exists). */
+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);
-
-#endif /* GRPC_CORE_LIB_GPR_ENV_H */
+
+#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 6a78dc14155..fa06df75ccc 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/env_linux.cc
@@ -1,50 +1,50 @@
-/*
- *
- * 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.
- *
- */
-
-/* for secure_getenv. */
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_LINUX_ENV
-
-#include "src/core/lib/gpr/env.h"
-
-#include <dlfcn.h>
-#include <features.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.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.
+ *
+ */
+
+/* for secure_getenv. */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_LINUX_ENV
+
+#include "src/core/lib/gpr/env.h"
+
+#include <dlfcn.h>
+#include <features.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
+
char* gpr_getenv(const char* name) {
- char* result = nullptr;
-#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE)
- typedef char* (*getenv_type)(const char*);
+ char* result = nullptr;
+#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE)
+ typedef char* (*getenv_type)(const char*);
static getenv_type getenv_func = nullptr;
- /* Check to see which getenv variant is supported (go from most
- * to least secure) */
+ /* 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++) {
@@ -52,25 +52,25 @@ char* gpr_getenv(const char* name) {
if (getenv_func != nullptr) {
break;
}
- }
- }
- result = getenv_func(name);
-#elif __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17)
- result = secure_getenv(name);
-#else
- result = getenv(name);
-#endif
+ }
+ }
+ result = getenv_func(name);
+#elif __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17)
+ result = secure_getenv(name);
+#else
+ result = getenv(name);
+#endif
return result == nullptr ? result : gpr_strdup(result);
-}
-
-void gpr_setenv(const char* name, const char* value) {
- int res = setenv(name, value, 1);
- GPR_ASSERT(res == 0);
-}
-
+}
+
+void gpr_setenv(const char* name, const char* value) {
+ int res = setenv(name, value, 1);
+ GPR_ASSERT(res == 0);
+}
+
void gpr_unsetenv(const char* name) {
int res = unsetenv(name);
GPR_ASSERT(res == 0);
}
-#endif /* GPR_LINUX_ENV */
+#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 232095b4e22..1d5113096b4 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/env_posix.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 <grpc/support/port_platform.h>
-
-#ifdef GPR_POSIX_ENV
-
-#include "src/core/lib/gpr/env.h"
-
-#include <stdlib.h>
-
-#include <grpc/support/log.h>
-
-#include <grpc/support/string_util.h>
-#include "src/core/lib/gpr/string.h"
-
-char* gpr_getenv(const char* name) {
- char* result = getenv(name);
- return result == nullptr ? result : gpr_strdup(result);
-}
-
-void gpr_setenv(const char* name, const char* value) {
- int res = setenv(name, value, 1);
- GPR_ASSERT(res == 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 <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_ENV
+
+#include "src/core/lib/gpr/env.h"
+
+#include <stdlib.h>
+
+#include <grpc/support/log.h>
+
+#include <grpc/support/string_util.h>
+#include "src/core/lib/gpr/string.h"
+
+char* gpr_getenv(const char* name) {
+ char* result = getenv(name);
+ return result == nullptr ? result : gpr_strdup(result);
+}
+
+void gpr_setenv(const char* name, const char* value) {
+ int res = setenv(name, value, 1);
+ GPR_ASSERT(res == 0);
+}
+
void gpr_unsetenv(const char* name) {
int res = unsetenv(name);
GPR_ASSERT(res == 0);
}
-#endif /* GPR_POSIX_ENV */
+#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 76c45fb87a7..c1ae23a02a3 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/env_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/env_windows.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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS_ENV
-
-#include <windows.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 "src/core/lib/gpr/string_windows.h"
-
-char* gpr_getenv(const char* name) {
- char* result = NULL;
- DWORD size;
- LPTSTR tresult = NULL;
- LPTSTR tname = gpr_char_to_tchar(name);
- DWORD ret;
-
- ret = GetEnvironmentVariable(tname, NULL, 0);
- if (ret == 0) {
- gpr_free(tname);
- return NULL;
- }
- size = ret * (DWORD)sizeof(TCHAR);
- tresult = (LPTSTR)gpr_malloc(size);
- ret = GetEnvironmentVariable(tname, tresult, size);
- gpr_free(tname);
- if (ret == 0) {
- gpr_free(tresult);
- return NULL;
- }
- result = gpr_tchar_to_char(tresult);
- gpr_free(tresult);
- return result;
-}
-
-void gpr_setenv(const char* name, const char* value) {
- LPTSTR tname = gpr_char_to_tchar(name);
- LPTSTR tvalue = gpr_char_to_tchar(value);
- BOOL res = SetEnvironmentVariable(tname, tvalue);
- gpr_free(tname);
- gpr_free(tvalue);
- GPR_ASSERT(res);
-}
-
+/*
+ *
+ * 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_WINDOWS_ENV
+
+#include <windows.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 "src/core/lib/gpr/string_windows.h"
+
+char* gpr_getenv(const char* name) {
+ char* result = NULL;
+ DWORD size;
+ LPTSTR tresult = NULL;
+ LPTSTR tname = gpr_char_to_tchar(name);
+ DWORD ret;
+
+ ret = GetEnvironmentVariable(tname, NULL, 0);
+ if (ret == 0) {
+ gpr_free(tname);
+ return NULL;
+ }
+ size = ret * (DWORD)sizeof(TCHAR);
+ tresult = (LPTSTR)gpr_malloc(size);
+ ret = GetEnvironmentVariable(tname, tresult, size);
+ gpr_free(tname);
+ if (ret == 0) {
+ gpr_free(tresult);
+ return NULL;
+ }
+ result = gpr_tchar_to_char(tresult);
+ gpr_free(tresult);
+ return result;
+}
+
+void gpr_setenv(const char* name, const char* value) {
+ LPTSTR tname = gpr_char_to_tchar(name);
+ LPTSTR tvalue = gpr_char_to_tchar(value);
+ BOOL res = SetEnvironmentVariable(tname, tvalue);
+ gpr_free(tname);
+ gpr_free(tvalue);
+ GPR_ASSERT(res);
+}
+
void gpr_unsetenv(const char* name) {
LPTSTR tname = gpr_char_to_tchar(name);
BOOL res = SetEnvironmentVariable(tname, NULL);
@@ -71,4 +71,4 @@ void gpr_unsetenv(const char* name) {
GPR_ASSERT(res);
}
-#endif /* GPR_WINDOWS_ENV */
+#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 8a229b2adf1..f4377bc51c6 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log.cc
@@ -1,98 +1,98 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/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 <grpc/support/alloc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/global_config.h"
-
-#include <stdio.h>
-#include <string.h>
-
+
+#include <stdio.h>
+#include <string.h>
+
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;
-
-const char* gpr_log_severity_string(gpr_log_severity severity) {
- switch (severity) {
- case GPR_LOG_SEVERITY_DEBUG:
- return "D";
- case GPR_LOG_SEVERITY_INFO:
- return "I";
- case GPR_LOG_SEVERITY_ERROR:
- return "E";
- }
- GPR_UNREACHABLE_CODE(return "UNKNOWN");
-}
-
-int gpr_should_log(gpr_log_severity severity) {
- return static_cast<gpr_atm>(severity) >=
- gpr_atm_no_barrier_load(&g_min_severity_to_print)
- ? 1
- : 0;
-}
-
-void gpr_log_message(const char* file, int line, gpr_log_severity severity,
- const char* message) {
- if (gpr_should_log(severity) == 0) {
- return;
- }
-
- gpr_log_func_args lfargs;
- memset(&lfargs, 0, sizeof(lfargs));
- lfargs.file = file;
- lfargs.line = line;
- lfargs.severity = severity;
- lfargs.message = message;
- ((gpr_log_func)gpr_atm_no_barrier_load(&g_log_func))(&lfargs);
-}
-
-void gpr_set_log_verbosity(gpr_log_severity min_severity_to_print) {
- gpr_atm_no_barrier_store(&g_min_severity_to_print,
- (gpr_atm)min_severity_to_print);
-}
-
-void gpr_log_verbosity_init() {
+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;
+
+const char* gpr_log_severity_string(gpr_log_severity severity) {
+ switch (severity) {
+ case GPR_LOG_SEVERITY_DEBUG:
+ return "D";
+ case GPR_LOG_SEVERITY_INFO:
+ return "I";
+ case GPR_LOG_SEVERITY_ERROR:
+ return "E";
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
+
+int gpr_should_log(gpr_log_severity severity) {
+ return static_cast<gpr_atm>(severity) >=
+ gpr_atm_no_barrier_load(&g_min_severity_to_print)
+ ? 1
+ : 0;
+}
+
+void gpr_log_message(const char* file, int line, gpr_log_severity severity,
+ const char* message) {
+ if (gpr_should_log(severity) == 0) {
+ return;
+ }
+
+ gpr_log_func_args lfargs;
+ memset(&lfargs, 0, sizeof(lfargs));
+ lfargs.file = file;
+ lfargs.line = line;
+ lfargs.severity = severity;
+ lfargs.message = message;
+ ((gpr_log_func)gpr_atm_no_barrier_load(&g_log_func))(&lfargs);
+}
+
+void gpr_set_log_verbosity(gpr_log_severity min_severity_to_print) {
+ gpr_atm_no_barrier_store(&g_min_severity_to_print,
+ (gpr_atm)min_severity_to_print);
+}
+
+void gpr_log_verbosity_init() {
grpc_core::UniquePtr<char> verbosity = GPR_GLOBAL_CONFIG_GET(grpc_verbosity);
-
- gpr_atm min_severity_to_print = GPR_LOG_SEVERITY_ERROR;
+
+ gpr_atm min_severity_to_print = GPR_LOG_SEVERITY_ERROR;
if (strlen(verbosity.get()) > 0) {
if (gpr_stricmp(verbosity.get(), "DEBUG") == 0) {
- min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_DEBUG);
+ min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_DEBUG);
} else if (gpr_stricmp(verbosity.get(), "INFO") == 0) {
- min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_INFO);
+ min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_INFO);
} else if (gpr_stricmp(verbosity.get(), "ERROR") == 0) {
- min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_ERROR);
- }
- }
- if ((gpr_atm_no_barrier_load(&g_min_severity_to_print)) ==
- GPR_LOG_VERBOSITY_UNSET) {
- gpr_atm_no_barrier_store(&g_min_severity_to_print, min_severity_to_print);
- }
-}
-
-void gpr_set_log_function(gpr_log_func f) {
- gpr_atm_no_barrier_store(&g_log_func, (gpr_atm)(f ? f : gpr_default_log));
-}
+ min_severity_to_print = static_cast<gpr_atm>(GPR_LOG_SEVERITY_ERROR);
+ }
+ }
+ if ((gpr_atm_no_barrier_load(&g_min_severity_to_print)) ==
+ GPR_LOG_VERBOSITY_UNSET) {
+ gpr_atm_no_barrier_store(&g_min_severity_to_print, min_severity_to_print);
+ }
+}
+
+void gpr_set_log_function(gpr_log_func f) {
+ gpr_atm_no_barrier_store(&g_log_func, (gpr_atm)(f ? f : gpr_default_log));
+}
diff --git a/contrib/libs/grpc/src/core/lib/gpr/log_android.cc b/contrib/libs/grpc/src/core/lib/gpr/log_android.cc
index 40ef4c640da..0ab4aec67cd 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log_android.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log_android.cc
@@ -1,76 +1,76 @@
-/*
- *
- * 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_ANDROID
-
-#include <android/log.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-static android_LogPriority severity_to_log_priority(gpr_log_severity severity) {
- switch (severity) {
- case GPR_LOG_SEVERITY_DEBUG:
- return ANDROID_LOG_DEBUG;
- case GPR_LOG_SEVERITY_INFO:
- return ANDROID_LOG_INFO;
- case GPR_LOG_SEVERITY_ERROR:
- return ANDROID_LOG_ERROR;
- }
- return ANDROID_LOG_DEFAULT;
-}
-
-void gpr_log(const char* file, int line, gpr_log_severity severity,
- const char* format, ...) {
- /* Avoid message construction if gpr_log_message won't log */
- if (gpr_should_log(severity) == 0) {
- return;
- }
- char* message = NULL;
- va_list args;
- va_start(args, format);
- vasprintf(&message, format, args);
- va_end(args);
- gpr_log_message(file, line, severity, message);
- free(message);
-}
-
-void gpr_default_log(gpr_log_func_args* args) {
- const char* final_slash;
- const char* display_file;
- char* output = NULL;
-
- final_slash = strrchr(args->file, '/');
- if (final_slash == NULL)
- display_file = args->file;
- else
- display_file = final_slash + 1;
-
- asprintf(&output, "%s:%d] %s", display_file, args->line, args->message);
-
- __android_log_write(severity_to_log_priority(args->severity), "GRPC", output);
-
- /* allocated by asprintf => use free, not gpr_free */
- free(output);
-}
-
-#endif /* GPR_ANDROID */
+/*
+ *
+ * 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_ANDROID
+
+#include <android/log.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+static android_LogPriority severity_to_log_priority(gpr_log_severity severity) {
+ switch (severity) {
+ case GPR_LOG_SEVERITY_DEBUG:
+ return ANDROID_LOG_DEBUG;
+ case GPR_LOG_SEVERITY_INFO:
+ return ANDROID_LOG_INFO;
+ case GPR_LOG_SEVERITY_ERROR:
+ return ANDROID_LOG_ERROR;
+ }
+ return ANDROID_LOG_DEFAULT;
+}
+
+void gpr_log(const char* file, int line, gpr_log_severity severity,
+ const char* format, ...) {
+ /* Avoid message construction if gpr_log_message won't log */
+ if (gpr_should_log(severity) == 0) {
+ return;
+ }
+ char* message = NULL;
+ va_list args;
+ va_start(args, format);
+ vasprintf(&message, format, args);
+ va_end(args);
+ gpr_log_message(file, line, severity, message);
+ free(message);
+}
+
+void gpr_default_log(gpr_log_func_args* args) {
+ const char* final_slash;
+ const char* display_file;
+ char* output = NULL;
+
+ final_slash = strrchr(args->file, '/');
+ if (final_slash == NULL)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ asprintf(&output, "%s:%d] %s", display_file, args->line, args->message);
+
+ __android_log_write(severity_to_log_priority(args->severity), "GRPC", output);
+
+ /* allocated by asprintf => use free, not gpr_free */
+ free(output);
+}
+
+#endif /* GPR_ANDROID */
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 7b098d4711e..01c9faa0e4b 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log_linux.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.
- *
- */
-
-#ifndef _POSIX_SOURCE
-#define _POSIX_SOURCE
-#endif
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_LINUX_LOG
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <inttypes.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/syscall.h>
-#include <time.h>
-#include <unistd.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 _POSIX_SOURCE
+#define _POSIX_SOURCE
+#endif
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_LINUX_LOG
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <inttypes.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/syscall.h>
+#include <time.h>
+#include <unistd.h>
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-
+
static long sys_gettid(void) { return syscall(__NR_gettid); }
-
-void gpr_log(const char* file, int line, gpr_log_severity severity,
- const char* format, ...) {
- /* Avoid message construction if gpr_log_message won't log */
- if (gpr_should_log(severity) == 0) {
- return;
- }
- char* message = nullptr;
- va_list args;
- va_start(args, format);
- if (vasprintf(&message, format, args) == -1) {
- va_end(args);
- return;
- }
- va_end(args);
- gpr_log_message(file, line, severity, message);
- /* message has been allocated by vasprintf above, and needs free */
- free(message);
-}
-
-void gpr_default_log(gpr_log_func_args* args) {
- const char* final_slash;
- const char* display_file;
- char time_buffer[64];
- time_t timer;
- gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
- struct tm tm;
- static __thread long tid = 0;
+
+void gpr_log(const char* file, int line, gpr_log_severity severity,
+ const char* format, ...) {
+ /* Avoid message construction if gpr_log_message won't log */
+ if (gpr_should_log(severity) == 0) {
+ return;
+ }
+ char* message = nullptr;
+ va_list args;
+ va_start(args, format);
+ if (vasprintf(&message, format, args) == -1) {
+ va_end(args);
+ return;
+ }
+ va_end(args);
+ gpr_log_message(file, line, severity, message);
+ /* message has been allocated by vasprintf above, and needs free */
+ free(message);
+}
+
+void gpr_default_log(gpr_log_func_args* args) {
+ const char* final_slash;
+ const char* display_file;
+ char time_buffer[64];
+ time_t timer;
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ struct tm tm;
+ static __thread long tid = 0;
if (tid == 0) tid = sys_gettid();
-
- timer = static_cast<time_t>(now.tv_sec);
- final_slash = strrchr(args->file, '/');
- if (final_slash == nullptr)
- display_file = args->file;
- else
- display_file = final_slash + 1;
-
- if (!localtime_r(&timer, &tm)) {
- strcpy(time_buffer, "error:localtime");
- } else if (0 ==
- strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
- strcpy(time_buffer, "error:strftime");
- }
-
+
+ timer = static_cast<time_t>(now.tv_sec);
+ final_slash = strrchr(args->file, '/');
+ if (final_slash == nullptr)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ if (!localtime_r(&timer, &tm)) {
+ strcpy(time_buffer, "error:localtime");
+ } else if (0 ==
+ strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
+ strcpy(time_buffer, "error:strftime");
+ }
+
TString prefix = y_absl::StrFormat(
"%s%s.%09" PRId32 " %7ld %s:%d]", gpr_log_severity_string(args->severity),
time_buffer, now.tv_nsec, tid, display_file, args->line);
fprintf(stderr, "%-60s %s\n", prefix.c_str(), args->message);
-}
-
-#endif /* GPR_LINUX_LOG */
+}
+
+#endif /* GPR_LINUX_LOG */
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 bc02118d948..b882df4e016 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_POSIX_LOG
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.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>
+
+#ifdef GPR_POSIX_LOG
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
#include <inttypes.h>
-#include <pthread.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-#include <time.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-
+
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, ...) {
- /* Avoid message construction if gpr_log_message won't log */
- if (gpr_should_log(severity) == 0) {
- return;
- }
- char buf[64];
- char* allocated = nullptr;
- char* message = nullptr;
- int ret;
- va_list args;
- va_start(args, format);
- ret = vsnprintf(buf, sizeof(buf), format, args);
- va_end(args);
- if (ret < 0) {
- message = nullptr;
- } else if ((size_t)ret <= sizeof(buf) - 1) {
- message = buf;
- } else {
- message = allocated = (char*)gpr_malloc((size_t)ret + 1);
- va_start(args, format);
- vsnprintf(message, (size_t)(ret + 1), format, args);
- va_end(args);
- }
- gpr_log_message(file, line, severity, message);
- gpr_free(allocated);
-}
-
-void gpr_default_log(gpr_log_func_args* args) {
- const char* final_slash;
- const char* display_file;
- char time_buffer[64];
- time_t timer;
- gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
- struct tm tm;
-
- timer = (time_t)now.tv_sec;
- final_slash = strrchr(args->file, '/');
- if (final_slash == nullptr)
- display_file = args->file;
- else
- display_file = final_slash + 1;
-
- if (!localtime_r(&timer, &tm)) {
- strcpy(time_buffer, "error:localtime");
- } else if (0 ==
- strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
- strcpy(time_buffer, "error:strftime");
- }
-
+
+void gpr_log(const char* file, int line, gpr_log_severity severity,
+ const char* format, ...) {
+ /* Avoid message construction if gpr_log_message won't log */
+ if (gpr_should_log(severity) == 0) {
+ return;
+ }
+ char buf[64];
+ char* allocated = nullptr;
+ char* message = nullptr;
+ int ret;
+ va_list args;
+ va_start(args, format);
+ ret = vsnprintf(buf, sizeof(buf), format, args);
+ va_end(args);
+ if (ret < 0) {
+ message = nullptr;
+ } else if ((size_t)ret <= sizeof(buf) - 1) {
+ message = buf;
+ } else {
+ message = allocated = (char*)gpr_malloc((size_t)ret + 1);
+ va_start(args, format);
+ vsnprintf(message, (size_t)(ret + 1), format, args);
+ va_end(args);
+ }
+ gpr_log_message(file, line, severity, message);
+ gpr_free(allocated);
+}
+
+void gpr_default_log(gpr_log_func_args* args) {
+ const char* final_slash;
+ const char* display_file;
+ char time_buffer[64];
+ time_t timer;
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ struct tm tm;
+
+ timer = (time_t)now.tv_sec;
+ final_slash = strrchr(args->file, '/');
+ if (final_slash == nullptr)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ if (!localtime_r(&timer, &tm)) {
+ strcpy(time_buffer, "error:localtime");
+ } else if (0 ==
+ strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
+ strcpy(time_buffer, "error:strftime");
+ }
+
TString prefix = y_absl::StrFormat(
"%s%s.%09d %7" PRIdPTR " %s:%d]", gpr_log_severity_string(args->severity),
time_buffer, (int)(now.tv_nsec), sys_gettid(), display_file, args->line);
fprintf(stderr, "%-70s %s\n", prefix.c_str(), args->message);
-}
-
-#endif /* defined(GPR_POSIX_LOG) */
+}
+
+#endif /* defined(GPR_POSIX_LOG) */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/log_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/log_windows.cc
index 060be572b80..1f7da776e5a 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/log_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/log_windows.cc
@@ -1,102 +1,102 @@
-/*
- *
- * 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_WINDOWS_LOG
-
-#include <stdarg.h>
-#include <stdio.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/log_windows.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/string_windows.h"
-
-void gpr_log(const char* file, int line, gpr_log_severity severity,
- const char* format, ...) {
- /* Avoid message construction if gpr_log_message won't log */
- if (gpr_should_log(severity) == 0) {
- return;
- }
-
- char* message = NULL;
- va_list args;
- int ret;
-
- /* Determine the length. */
- va_start(args, format);
- ret = _vscprintf(format, args);
- va_end(args);
- if (ret < 0) {
- message = NULL;
- } else {
- /* Allocate a new buffer, with space for the NUL terminator. */
- size_t strp_buflen = (size_t)ret + 1;
- message = (char*)gpr_malloc(strp_buflen);
-
- /* Print to the buffer. */
- va_start(args, format);
- ret = vsnprintf_s(message, strp_buflen, _TRUNCATE, format, args);
- va_end(args);
- if ((size_t)ret != strp_buflen - 1) {
- /* This should never happen. */
- gpr_free(message);
- message = NULL;
- }
- }
-
- gpr_log_message(file, line, severity, message);
- gpr_free(message);
-}
-
-/* Simple starter implementation */
-void gpr_default_log(gpr_log_func_args* args) {
- const char* final_slash;
- const char* display_file;
- char time_buffer[64];
- time_t timer;
- gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
- struct tm tm;
-
- timer = (time_t)now.tv_sec;
- final_slash = strrchr(args->file, '\\');
- if (final_slash == NULL)
- display_file = args->file;
- else
- display_file = final_slash + 1;
-
- if (localtime_s(&tm, &timer)) {
- strcpy(time_buffer, "error:localtime");
- } else if (0 ==
- strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
- strcpy(time_buffer, "error:strftime");
- }
-
- fprintf(stderr, "%s%s.%09u %5lu %s:%d] %s\n",
- gpr_log_severity_string(args->severity), time_buffer,
- (int)(now.tv_nsec), GetCurrentThreadId(), display_file, args->line,
- args->message);
- fflush(stderr);
-}
-
-#endif /* GPR_WINDOWS_LOG */
+/*
+ *
+ * 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_WINDOWS_LOG
+
+#include <stdarg.h>
+#include <stdio.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_windows.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/string_windows.h"
+
+void gpr_log(const char* file, int line, gpr_log_severity severity,
+ const char* format, ...) {
+ /* Avoid message construction if gpr_log_message won't log */
+ if (gpr_should_log(severity) == 0) {
+ return;
+ }
+
+ char* message = NULL;
+ va_list args;
+ int ret;
+
+ /* Determine the length. */
+ va_start(args, format);
+ ret = _vscprintf(format, args);
+ va_end(args);
+ if (ret < 0) {
+ message = NULL;
+ } else {
+ /* Allocate a new buffer, with space for the NUL terminator. */
+ size_t strp_buflen = (size_t)ret + 1;
+ message = (char*)gpr_malloc(strp_buflen);
+
+ /* Print to the buffer. */
+ va_start(args, format);
+ ret = vsnprintf_s(message, strp_buflen, _TRUNCATE, format, args);
+ va_end(args);
+ if ((size_t)ret != strp_buflen - 1) {
+ /* This should never happen. */
+ gpr_free(message);
+ message = NULL;
+ }
+ }
+
+ gpr_log_message(file, line, severity, message);
+ gpr_free(message);
+}
+
+/* Simple starter implementation */
+void gpr_default_log(gpr_log_func_args* args) {
+ const char* final_slash;
+ const char* display_file;
+ char time_buffer[64];
+ time_t timer;
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ struct tm tm;
+
+ timer = (time_t)now.tv_sec;
+ final_slash = strrchr(args->file, '\\');
+ if (final_slash == NULL)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ if (localtime_s(&tm, &timer)) {
+ strcpy(time_buffer, "error:localtime");
+ } else if (0 ==
+ strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
+ strcpy(time_buffer, "error:strftime");
+ }
+
+ fprintf(stderr, "%s%s.%09u %5lu %s:%d] %s\n",
+ gpr_log_severity_string(args->severity), time_buffer,
+ (int)(now.tv_nsec), GetCurrentThreadId(), display_file, args->line,
+ args->message);
+ fflush(stderr);
+}
+
+#endif /* GPR_WINDOWS_LOG */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.cc b/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.cc
index cf25abf40d5..c112b57d14a 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/gpr/murmur_hash.h"
-
-#include <string.h>
-
-#define ROTL32(x, r) ((x) << (r)) | ((x) >> (32 - (r)))
-
-#define FMIX32(h) \
- (h) ^= (h) >> 16; \
- (h) *= 0x85ebca6b; \
- (h) ^= (h) >> 13; \
- (h) *= 0xc2b2ae35; \
- (h) ^= (h) >> 16;
-
-uint32_t gpr_murmur_hash3(const void* key, size_t len, uint32_t seed) {
- uint32_t h1 = seed;
- uint32_t k1;
-
- const uint32_t c1 = 0xcc9e2d51;
- const uint32_t c2 = 0x1b873593;
-
- const uint8_t* keyptr = static_cast<const uint8_t*>(key);
- const size_t bsize = sizeof(k1);
- const size_t nblocks = len / bsize;
-
- /* body */
- for (size_t i = 0; i < nblocks; i++, keyptr += bsize) {
- memcpy(&k1, keyptr, bsize);
-
- k1 *= c1;
- k1 = ROTL32(k1, 15);
- k1 *= c2;
-
- h1 ^= k1;
- h1 = ROTL32(h1, 13);
- h1 = h1 * 5 + 0xe6546b64;
- }
-
- k1 = 0;
-
- /* tail */
- switch (len & 3) {
- case 3:
- k1 ^= (static_cast<uint32_t>(keyptr[2])) << 16;
- /* fallthrough */
- case 2:
- k1 ^= (static_cast<uint32_t>(keyptr[1])) << 8;
- /* fallthrough */
- case 1:
- k1 ^= keyptr[0];
- k1 *= c1;
- k1 = ROTL32(k1, 15);
- k1 *= c2;
- h1 ^= k1;
- };
-
- /* finalization */
- h1 ^= static_cast<uint32_t>(len);
- FMIX32(h1);
- return h1;
-}
+/*
+ *
+ * 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/gpr/murmur_hash.h"
+
+#include <string.h>
+
+#define ROTL32(x, r) ((x) << (r)) | ((x) >> (32 - (r)))
+
+#define FMIX32(h) \
+ (h) ^= (h) >> 16; \
+ (h) *= 0x85ebca6b; \
+ (h) ^= (h) >> 13; \
+ (h) *= 0xc2b2ae35; \
+ (h) ^= (h) >> 16;
+
+uint32_t gpr_murmur_hash3(const void* key, size_t len, uint32_t seed) {
+ uint32_t h1 = seed;
+ uint32_t k1;
+
+ const uint32_t c1 = 0xcc9e2d51;
+ const uint32_t c2 = 0x1b873593;
+
+ const uint8_t* keyptr = static_cast<const uint8_t*>(key);
+ const size_t bsize = sizeof(k1);
+ const size_t nblocks = len / bsize;
+
+ /* body */
+ for (size_t i = 0; i < nblocks; i++, keyptr += bsize) {
+ memcpy(&k1, keyptr, bsize);
+
+ k1 *= c1;
+ k1 = ROTL32(k1, 15);
+ k1 *= c2;
+
+ h1 ^= k1;
+ h1 = ROTL32(h1, 13);
+ h1 = h1 * 5 + 0xe6546b64;
+ }
+
+ k1 = 0;
+
+ /* tail */
+ switch (len & 3) {
+ case 3:
+ k1 ^= (static_cast<uint32_t>(keyptr[2])) << 16;
+ /* fallthrough */
+ case 2:
+ k1 ^= (static_cast<uint32_t>(keyptr[1])) << 8;
+ /* fallthrough */
+ case 1:
+ k1 ^= keyptr[0];
+ k1 *= c1;
+ k1 = ROTL32(k1, 15);
+ k1 *= c2;
+ h1 ^= k1;
+ };
+
+ /* finalization */
+ h1 ^= static_cast<uint32_t>(len);
+ FMIX32(h1);
+ return h1;
+}
diff --git a/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.h b/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.h
index 8004889a9a5..56856f8a81a 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/murmur_hash.h
@@ -1,29 +1,29 @@
-/*
- *
- * 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_GPR_MURMUR_HASH_H
-#define GRPC_CORE_LIB_GPR_MURMUR_HASH_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stddef.h>
-
-/* compute the hash of key (length len) */
-uint32_t gpr_murmur_hash3(const void* key, size_t len, uint32_t seed);
-
-#endif /* GRPC_CORE_LIB_GPR_MURMUR_HASH_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_GPR_MURMUR_HASH_H
+#define GRPC_CORE_LIB_GPR_MURMUR_HASH_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stddef.h>
+
+/* compute the hash of key (length len) */
+uint32_t gpr_murmur_hash3(const void* key, size_t len, uint32_t seed);
+
+#endif /* GRPC_CORE_LIB_GPR_MURMUR_HASH_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/spinlock.h b/contrib/libs/grpc/src/core/lib/gpr/spinlock.h
index a9c0e62d92c..4c78f9cc2e2 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/spinlock.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/spinlock.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPR_SPINLOCK_H
-#define GRPC_CORE_LIB_GPR_SPINLOCK_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/atm.h>
-
-/* Simple spinlock. No backoff strategy, gpr_spinlock_lock is almost always
- a concurrency code smell. */
+/*
+ *
+ * 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_GPR_SPINLOCK_H
+#define GRPC_CORE_LIB_GPR_SPINLOCK_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/atm.h>
+
+/* Simple spinlock. No backoff strategy, gpr_spinlock_lock is almost always
+ a concurrency code smell. */
struct gpr_spinlock {
- gpr_atm atm;
+ gpr_atm atm;
};
-#ifdef __cplusplus
-#define GPR_SPINLOCK_INITIALIZER (gpr_spinlock{0})
-#else
-#define GPR_SPINLOCK_INITIALIZER ((gpr_spinlock){0})
-#endif
-#define GPR_SPINLOCK_STATIC_INITIALIZER \
- { 0 }
-
-#define gpr_spinlock_trylock(lock) (gpr_atm_acq_cas(&(lock)->atm, 0, 1))
-#define gpr_spinlock_unlock(lock) (gpr_atm_rel_store(&(lock)->atm, 0))
-#define gpr_spinlock_lock(lock) \
- do { \
- } while (!gpr_spinlock_trylock((lock)))
-
-#endif /* GRPC_CORE_LIB_GPR_SPINLOCK_H */
+#ifdef __cplusplus
+#define GPR_SPINLOCK_INITIALIZER (gpr_spinlock{0})
+#else
+#define GPR_SPINLOCK_INITIALIZER ((gpr_spinlock){0})
+#endif
+#define GPR_SPINLOCK_STATIC_INITIALIZER \
+ { 0 }
+
+#define gpr_spinlock_trylock(lock) (gpr_atm_acq_cas(&(lock)->atm, 0, 1))
+#define gpr_spinlock_unlock(lock) (gpr_atm_rel_store(&(lock)->atm, 0))
+#define gpr_spinlock_lock(lock) \
+ do { \
+ } while (!gpr_spinlock_trylock((lock)))
+
+#endif /* GRPC_CORE_LIB_GPR_SPINLOCK_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/string.cc b/contrib/libs/grpc/src/core/lib/gpr/string.cc
index 28f1ae437d0..92a97ad5ca7 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/string.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/gpr/string.h"
-
-#include <ctype.h>
-#include <limits.h>
-#include <stddef.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/gpr/string.h"
+
+#include <ctype.h>
+#include <limits.h>
+#include <stddef.h>
#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include <stdlib.h>
+#include <string.h>
#include <time.h>
-
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-char* gpr_strdup(const char* src) {
- char* dst;
- size_t len;
-
- if (!src) {
- return nullptr;
- }
-
- len = strlen(src) + 1;
- dst = static_cast<char*>(gpr_malloc(len));
-
- memcpy(dst, src, len);
-
- return dst;
-}
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+char* gpr_strdup(const char* src) {
+ char* dst;
+ size_t len;
+
+ if (!src) {
+ return nullptr;
+ }
+
+ len = strlen(src) + 1;
+ dst = static_cast<char*>(gpr_malloc(len));
+
+ memcpy(dst, src, len);
+
+ return dst;
+}
+
TString gpr_format_timespec(gpr_timespec tm) {
char time_buffer[35];
char ns_buffer[11]; // '.' + 9 digits of precision
@@ -82,261 +82,261 @@ struct dump_out {
char* data;
};
-static dump_out dump_out_create(void) {
- dump_out r = {0, 0, nullptr};
- return r;
-}
-
-static void dump_out_append(dump_out* out, char c) {
- if (out->length == out->capacity) {
- out->capacity = GPR_MAX(8, 2 * out->capacity);
- out->data = static_cast<char*>(gpr_realloc(out->data, out->capacity));
- }
- out->data[out->length++] = c;
-}
-
-static void hexdump(dump_out* out, const char* buf, size_t len) {
- static const char* hex = "0123456789abcdef";
-
- const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
- const uint8_t* const end = beg + len;
- const uint8_t* cur;
-
- for (cur = beg; cur != end; ++cur) {
- if (cur != beg) dump_out_append(out, ' ');
- dump_out_append(out, hex[*cur >> 4]);
- dump_out_append(out, hex[*cur & 0xf]);
- }
-}
-
-static void asciidump(dump_out* out, const char* buf, size_t len) {
- const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
- const uint8_t* const end = beg + len;
- const uint8_t* cur;
- int out_was_empty = (out->length == 0);
- if (!out_was_empty) {
- dump_out_append(out, ' ');
- dump_out_append(out, '\'');
- }
- for (cur = beg; cur != end; ++cur) {
- dump_out_append(out, (isprint(*cur) ? *(char*)cur : '.'));
- }
- if (!out_was_empty) {
- dump_out_append(out, '\'');
- }
-}
-
+static dump_out dump_out_create(void) {
+ dump_out r = {0, 0, nullptr};
+ return r;
+}
+
+static void dump_out_append(dump_out* out, char c) {
+ if (out->length == out->capacity) {
+ out->capacity = GPR_MAX(8, 2 * out->capacity);
+ out->data = static_cast<char*>(gpr_realloc(out->data, out->capacity));
+ }
+ out->data[out->length++] = c;
+}
+
+static void hexdump(dump_out* out, const char* buf, size_t len) {
+ static const char* hex = "0123456789abcdef";
+
+ const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
+ const uint8_t* const end = beg + len;
+ const uint8_t* cur;
+
+ for (cur = beg; cur != end; ++cur) {
+ if (cur != beg) dump_out_append(out, ' ');
+ dump_out_append(out, hex[*cur >> 4]);
+ dump_out_append(out, hex[*cur & 0xf]);
+ }
+}
+
+static void asciidump(dump_out* out, const char* buf, size_t len) {
+ const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
+ const uint8_t* const end = beg + len;
+ const uint8_t* cur;
+ int out_was_empty = (out->length == 0);
+ if (!out_was_empty) {
+ dump_out_append(out, ' ');
+ dump_out_append(out, '\'');
+ }
+ for (cur = beg; cur != end; ++cur) {
+ dump_out_append(out, (isprint(*cur) ? *(char*)cur : '.'));
+ }
+ if (!out_was_empty) {
+ dump_out_append(out, '\'');
+ }
+}
+
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);
- }
- if (flags & GPR_DUMP_ASCII) {
- asciidump(&out, buf, len);
- }
- dump_out_append(&out, 0);
+ dump_out out = dump_out_create();
+ if (flags & GPR_DUMP_HEX) {
+ hexdump(&out, buf, len);
+ }
+ if (flags & GPR_DUMP_ASCII) {
+ asciidump(&out, buf, len);
+ }
+ dump_out_append(&out, 0);
*out_len = out.length;
- return out.data;
-}
-
+ 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);
}
-int gpr_parse_bytes_to_uint32(const char* buf, size_t len, uint32_t* result) {
- uint32_t out = 0;
- uint32_t new_val;
- size_t i;
-
- if (len == 0) return 0; /* must have some bytes */
-
- for (i = 0; i < len; i++) {
- if (buf[i] < '0' || buf[i] > '9') return 0; /* bad char */
- new_val = 10 * out + static_cast<uint32_t>(buf[i] - '0');
- if (new_val < out) return 0; /* overflow */
- out = new_val;
- }
-
- *result = out;
- return 1;
-}
-
-void gpr_reverse_bytes(char* str, int len) {
- char *p1, *p2;
- for (p1 = str, p2 = str + len - 1; p2 > p1; ++p1, --p2) {
- char temp = *p1;
- *p1 = *p2;
- *p2 = temp;
- }
-}
-
-int gpr_ltoa(long value, char* string) {
- long sign;
- int i = 0;
-
- if (value == 0) {
- string[0] = '0';
- string[1] = 0;
- return 1;
- }
-
- sign = value < 0 ? -1 : 1;
- while (value) {
- string[i++] = static_cast<char>('0' + sign * (value % 10));
- value /= 10;
- }
- if (sign < 0) string[i++] = '-';
- gpr_reverse_bytes(string, i);
- string[i] = 0;
- return i;
-}
-
-int int64_ttoa(int64_t value, char* string) {
- int64_t sign;
- int i = 0;
-
- if (value == 0) {
- string[0] = '0';
- string[1] = 0;
- return 1;
- }
-
- sign = value < 0 ? -1 : 1;
- while (value) {
- string[i++] = static_cast<char>('0' + sign * (value % 10));
- value /= 10;
- }
- if (sign < 0) string[i++] = '-';
- gpr_reverse_bytes(string, i);
- string[i] = 0;
- return i;
-}
-
-int gpr_parse_nonnegative_int(const char* value) {
- char* end;
- long result = strtol(value, &end, 0);
- if (*end != '\0' || result < 0 || result > INT_MAX) return -1;
- return static_cast<int>(result);
-}
-
-char* gpr_leftpad(const char* str, char flag, size_t length) {
- const size_t str_length = strlen(str);
- const size_t out_length = str_length > length ? str_length : length;
- char* out = static_cast<char*>(gpr_malloc(out_length + 1));
- memset(out, flag, out_length - str_length);
- memcpy(out + out_length - str_length, str, str_length);
- out[out_length] = 0;
- return out;
-}
-
-char* gpr_strjoin(const char** strs, size_t nstrs, size_t* final_length) {
- return gpr_strjoin_sep(strs, nstrs, "", final_length);
-}
-
-char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
- size_t* final_length) {
- const size_t sep_len = strlen(sep);
- size_t out_length = 0;
- size_t i;
- char* out;
- for (i = 0; i < nstrs; i++) {
- out_length += strlen(strs[i]);
- }
- out_length += 1; /* null terminator */
- if (nstrs > 0) {
- out_length += sep_len * (nstrs - 1); /* separators */
- }
- out = static_cast<char*>(gpr_malloc(out_length));
- out_length = 0;
- for (i = 0; i < nstrs; i++) {
- const size_t slen = strlen(strs[i]);
- if (i != 0) {
- memcpy(out + out_length, sep, sep_len);
- out_length += sep_len;
- }
- memcpy(out + out_length, strs[i], slen);
- out_length += slen;
- }
- out[out_length] = 0;
- if (final_length != nullptr) {
- *final_length = out_length;
- }
- return out;
-}
-
+int gpr_parse_bytes_to_uint32(const char* buf, size_t len, uint32_t* result) {
+ uint32_t out = 0;
+ uint32_t new_val;
+ size_t i;
+
+ if (len == 0) return 0; /* must have some bytes */
+
+ for (i = 0; i < len; i++) {
+ if (buf[i] < '0' || buf[i] > '9') return 0; /* bad char */
+ new_val = 10 * out + static_cast<uint32_t>(buf[i] - '0');
+ if (new_val < out) return 0; /* overflow */
+ out = new_val;
+ }
+
+ *result = out;
+ return 1;
+}
+
+void gpr_reverse_bytes(char* str, int len) {
+ char *p1, *p2;
+ for (p1 = str, p2 = str + len - 1; p2 > p1; ++p1, --p2) {
+ char temp = *p1;
+ *p1 = *p2;
+ *p2 = temp;
+ }
+}
+
+int gpr_ltoa(long value, char* string) {
+ long sign;
+ int i = 0;
+
+ if (value == 0) {
+ string[0] = '0';
+ string[1] = 0;
+ return 1;
+ }
+
+ sign = value < 0 ? -1 : 1;
+ while (value) {
+ string[i++] = static_cast<char>('0' + sign * (value % 10));
+ value /= 10;
+ }
+ if (sign < 0) string[i++] = '-';
+ gpr_reverse_bytes(string, i);
+ string[i] = 0;
+ return i;
+}
+
+int int64_ttoa(int64_t value, char* string) {
+ int64_t sign;
+ int i = 0;
+
+ if (value == 0) {
+ string[0] = '0';
+ string[1] = 0;
+ return 1;
+ }
+
+ sign = value < 0 ? -1 : 1;
+ while (value) {
+ string[i++] = static_cast<char>('0' + sign * (value % 10));
+ value /= 10;
+ }
+ if (sign < 0) string[i++] = '-';
+ gpr_reverse_bytes(string, i);
+ string[i] = 0;
+ return i;
+}
+
+int gpr_parse_nonnegative_int(const char* value) {
+ char* end;
+ long result = strtol(value, &end, 0);
+ if (*end != '\0' || result < 0 || result > INT_MAX) return -1;
+ return static_cast<int>(result);
+}
+
+char* gpr_leftpad(const char* str, char flag, size_t length) {
+ const size_t str_length = strlen(str);
+ const size_t out_length = str_length > length ? str_length : length;
+ char* out = static_cast<char*>(gpr_malloc(out_length + 1));
+ memset(out, flag, out_length - str_length);
+ memcpy(out + out_length - str_length, str, str_length);
+ out[out_length] = 0;
+ return out;
+}
+
+char* gpr_strjoin(const char** strs, size_t nstrs, size_t* final_length) {
+ return gpr_strjoin_sep(strs, nstrs, "", final_length);
+}
+
+char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
+ size_t* final_length) {
+ const size_t sep_len = strlen(sep);
+ size_t out_length = 0;
+ size_t i;
+ char* out;
+ for (i = 0; i < nstrs; i++) {
+ out_length += strlen(strs[i]);
+ }
+ out_length += 1; /* null terminator */
+ if (nstrs > 0) {
+ out_length += sep_len * (nstrs - 1); /* separators */
+ }
+ out = static_cast<char*>(gpr_malloc(out_length));
+ out_length = 0;
+ for (i = 0; i < nstrs; i++) {
+ const size_t slen = strlen(strs[i]);
+ if (i != 0) {
+ memcpy(out + out_length, sep, sep_len);
+ out_length += sep_len;
+ }
+ memcpy(out + out_length, strs[i], slen);
+ out_length += slen;
+ }
+ out[out_length] = 0;
+ if (final_length != nullptr) {
+ *final_length = out_length;
+ }
+ return out;
+}
+
int gpr_strincmp(const char* a, const char* b, size_t n) {
- int ca, cb;
- do {
- ca = tolower(*a);
- cb = tolower(*b);
- ++a;
- ++b;
+ int ca, cb;
+ do {
+ ca = tolower(*a);
+ cb = tolower(*b);
+ ++a;
+ ++b;
--n;
} while (ca == cb && ca != 0 && cb != 0 && n != 0);
- return ca - cb;
-}
-
+ return ca - cb;
+}
+
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 =
- static_cast<char*>(gpr_malloc(static_cast<size_t>(end - beg) + 1));
- memcpy(out, beg, static_cast<size_t>(end - beg));
- out[end - beg] = 0;
- if (*nstrs == *capstrs) {
- *capstrs = GPR_MAX(8, 2 * *capstrs);
- *strs = static_cast<char**>(gpr_realloc(*strs, sizeof(*strs) * *capstrs));
- }
- (*strs)[*nstrs] = out;
- ++*nstrs;
-}
-
-void gpr_string_split(const char* input, const char* sep, char*** strs,
- size_t* nstrs) {
- const char* next;
- *strs = nullptr;
- *nstrs = 0;
- size_t capstrs = 0;
- while ((next = strstr(input, sep))) {
- add_string_to_split(input, next, strs, nstrs, &capstrs);
- input = next + strlen(sep);
- }
- add_string_to_split(input, input + strlen(input), strs, nstrs, &capstrs);
-}
-
-void* gpr_memrchr(const void* s, int c, size_t n) {
- if (s == nullptr) return nullptr;
- char* b = (char*)s;
- size_t i;
- for (i = 0; i < n; i++) {
- if (b[n - i - 1] == c) {
- return &b[n - i - 1];
- }
- }
- return nullptr;
-}
-
+static void add_string_to_split(const char* beg, const char* end, char*** strs,
+ size_t* nstrs, size_t* capstrs) {
+ char* out =
+ static_cast<char*>(gpr_malloc(static_cast<size_t>(end - beg) + 1));
+ memcpy(out, beg, static_cast<size_t>(end - beg));
+ out[end - beg] = 0;
+ if (*nstrs == *capstrs) {
+ *capstrs = GPR_MAX(8, 2 * *capstrs);
+ *strs = static_cast<char**>(gpr_realloc(*strs, sizeof(*strs) * *capstrs));
+ }
+ (*strs)[*nstrs] = out;
+ ++*nstrs;
+}
+
+void gpr_string_split(const char* input, const char* sep, char*** strs,
+ size_t* nstrs) {
+ const char* next;
+ *strs = nullptr;
+ *nstrs = 0;
+ size_t capstrs = 0;
+ while ((next = strstr(input, sep))) {
+ add_string_to_split(input, next, strs, nstrs, &capstrs);
+ input = next + strlen(sep);
+ }
+ add_string_to_split(input, input + strlen(input), strs, nstrs, &capstrs);
+}
+
+void* gpr_memrchr(const void* s, int c, size_t n) {
+ if (s == nullptr) return nullptr;
+ char* b = (char*)s;
+ size_t i;
+ for (i = 0; i < n; i++) {
+ if (b[n - i - 1] == c) {
+ return &b[n - i - 1];
+ }
+ }
+ 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");
- if (s == nullptr) {
- return false;
- }
+ 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;
+ return true;
} else if (gpr_stricmp(s, kFalse[i]) == 0) {
*dst = false;
return true;
- }
- }
+ }
+ }
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 4b348198b82..aacf2fe656b 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/string.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPR_STRING_H
-#define GRPC_CORE_LIB_GPR_STRING_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_GPR_STRING_H
+#define GRPC_CORE_LIB_GPR_STRING_H
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/gpr_types.h>
-#include <stdbool.h>
-#include <stddef.h>
-
+#include <stdbool.h>
+#include <stddef.h>
+
#include <util/generic/string.h>
-/* String utility functions */
-
-/* Flags for gpr_dump function. */
-#define GPR_DUMP_HEX 0x00000001
-#define GPR_DUMP_ASCII 0x00000002
-
+/* String utility functions */
+
+/* Flags for gpr_dump function. */
+#define GPR_DUMP_HEX 0x00000001
+#define GPR_DUMP_ASCII 0x00000002
+
/* 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);
+ 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);
-
-/* Parses an array of bytes into an integer (base 10). Returns 1 on success,
- 0 on failure. */
-int gpr_parse_bytes_to_uint32(const char* data, size_t length,
- uint32_t* result);
-
-/* Minimum buffer size for calling ltoa */
-#define GPR_LTOA_MIN_BUFSIZE (3 * sizeof(long))
-
-/* Convert a long to a string in base 10; returns the length of the
- output string (or 0 on failure).
- output must be at least GPR_LTOA_MIN_BUFSIZE bytes long. */
-int gpr_ltoa(long value, char* output);
-
-/* Minimum buffer size for calling int64toa */
-#define GPR_INT64TOA_MIN_BUFSIZE (3 * sizeof(int64_t))
-
-/* Convert an int64 to a string in base 10; returns the length of the
-output string (or 0 on failure).
-output must be at least GPR_INT64TOA_MIN_BUFSIZE bytes long.
-NOTE: This function ensures sufficient bit width even on Win x64,
-where long is 32bit is size.*/
-int int64_ttoa(int64_t value, char* output);
-
-// Parses a non-negative number from a value string. Returns -1 on error.
-int gpr_parse_nonnegative_int(const char* value);
-
-/* Reverse a run of bytes */
-void gpr_reverse_bytes(char* str, int len);
-
-/* Pad a string with flag characters. The given length specifies the minimum
- field width. The input string is never truncated. */
-char* gpr_leftpad(const char* str, char flag, size_t length);
-
-/* Join a set of strings, returning the resulting string.
- Total combined length (excluding null terminator) is returned in total_length
- if it is non-null. */
-char* gpr_strjoin(const char** strs, size_t nstrs, size_t* total_length);
-
-/* Join a set of strings using a separator, returning the resulting string.
- Total combined length (excluding null terminator) is returned in total_length
- if it is non-null. */
-char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
- size_t* total_length);
-
-void gpr_string_split(const char* input, const char* sep, char*** strs,
- size_t* nstrs);
-
+
+/* Parses an array of bytes into an integer (base 10). Returns 1 on success,
+ 0 on failure. */
+int gpr_parse_bytes_to_uint32(const char* data, size_t length,
+ uint32_t* result);
+
+/* Minimum buffer size for calling ltoa */
+#define GPR_LTOA_MIN_BUFSIZE (3 * sizeof(long))
+
+/* Convert a long to a string in base 10; returns the length of the
+ output string (or 0 on failure).
+ output must be at least GPR_LTOA_MIN_BUFSIZE bytes long. */
+int gpr_ltoa(long value, char* output);
+
+/* Minimum buffer size for calling int64toa */
+#define GPR_INT64TOA_MIN_BUFSIZE (3 * sizeof(int64_t))
+
+/* Convert an int64 to a string in base 10; returns the length of the
+output string (or 0 on failure).
+output must be at least GPR_INT64TOA_MIN_BUFSIZE bytes long.
+NOTE: This function ensures sufficient bit width even on Win x64,
+where long is 32bit is size.*/
+int int64_ttoa(int64_t value, char* output);
+
+// Parses a non-negative number from a value string. Returns -1 on error.
+int gpr_parse_nonnegative_int(const char* value);
+
+/* Reverse a run of bytes */
+void gpr_reverse_bytes(char* str, int len);
+
+/* Pad a string with flag characters. The given length specifies the minimum
+ field width. The input string is never truncated. */
+char* gpr_leftpad(const char* str, char flag, size_t length);
+
+/* Join a set of strings, returning the resulting string.
+ Total combined length (excluding null terminator) is returned in total_length
+ if it is non-null. */
+char* gpr_strjoin(const char** strs, size_t nstrs, size_t* total_length);
+
+/* Join a set of strings using a separator, returning the resulting string.
+ Total combined length (excluding null terminator) is returned in total_length
+ if it is non-null. */
+char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
+ size_t* total_length);
+
+void gpr_string_split(const char* input, const char* sep, char*** strs,
+ size_t* nstrs);
+
/* Returns a string that represents tm according to RFC-3339, and,
more specifically, follows:
https://developers.google.com/protocol-buffers/docs/proto3#json
@@ -98,16 +98,16 @@ void gpr_string_split(const char* input, const char* sep, char*** strs,
0, 3, 6 or 9 fractional digits. */
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);
+/** 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);
-
-void* gpr_memrchr(const void* s, int c, 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);
-
-#endif /* GRPC_CORE_LIB_GPR_STRING_H */
+
+#endif /* GRPC_CORE_LIB_GPR_STRING_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/string_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/string_posix.cc
index d32775fb3b4..b4227d52f3a 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/string_posix.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 <grpc/support/port_platform.h>
-
-#ifdef GPR_POSIX_STRING
-
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-int gpr_asprintf(char** strp, const char* format, ...) {
- va_list args;
- int ret;
- char buf[64];
- size_t strp_buflen;
-
- /* Use a constant-sized buffer to determine the length. */
- va_start(args, format);
- ret = vsnprintf(buf, sizeof(buf), format, args);
- va_end(args);
- if (ret < 0) {
- *strp = nullptr;
- return -1;
- }
-
- /* Allocate a new buffer, with space for the NUL terminator. */
- strp_buflen = static_cast<size_t>(ret) + 1;
- if ((*strp = static_cast<char*>(gpr_malloc(strp_buflen))) == nullptr) {
- /* This shouldn't happen, because gpr_malloc() calls abort(). */
- return -1;
- }
-
- /* Return early if we have all the bytes. */
- if (strp_buflen <= sizeof(buf)) {
- memcpy(*strp, buf, strp_buflen);
- return ret;
- }
-
- /* Try again using the larger buffer. */
- va_start(args, format);
- ret = vsnprintf(*strp, strp_buflen, format, args);
- va_end(args);
- if (static_cast<size_t>(ret) == strp_buflen - 1) {
- return ret;
- }
-
- /* This should never happen. */
- gpr_free(*strp);
- *strp = nullptr;
- return -1;
-}
-
-#endif /* GPR_POSIX_STRING */
+/*
+ *
+ * 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_STRING
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+int gpr_asprintf(char** strp, const char* format, ...) {
+ va_list args;
+ int ret;
+ char buf[64];
+ size_t strp_buflen;
+
+ /* Use a constant-sized buffer to determine the length. */
+ va_start(args, format);
+ ret = vsnprintf(buf, sizeof(buf), format, args);
+ va_end(args);
+ if (ret < 0) {
+ *strp = nullptr;
+ return -1;
+ }
+
+ /* Allocate a new buffer, with space for the NUL terminator. */
+ strp_buflen = static_cast<size_t>(ret) + 1;
+ if ((*strp = static_cast<char*>(gpr_malloc(strp_buflen))) == nullptr) {
+ /* This shouldn't happen, because gpr_malloc() calls abort(). */
+ return -1;
+ }
+
+ /* Return early if we have all the bytes. */
+ if (strp_buflen <= sizeof(buf)) {
+ memcpy(*strp, buf, strp_buflen);
+ return ret;
+ }
+
+ /* Try again using the larger buffer. */
+ va_start(args, format);
+ ret = vsnprintf(*strp, strp_buflen, format, args);
+ va_end(args);
+ if (static_cast<size_t>(ret) == strp_buflen - 1) {
+ return ret;
+ }
+
+ /* This should never happen. */
+ gpr_free(*strp);
+ *strp = nullptr;
+ return -1;
+}
+
+#endif /* GPR_POSIX_STRING */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/string_util_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/string_util_windows.cc
index 8c8c99cd211..090952a9e9b 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string_util_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/string_util_windows.cc
@@ -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.
- *
- */
-
-/* Posix code for gpr snprintf support. */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS
-
-/* Some platforms (namely msys) need wchar to be included BEFORE
- anything else, especially strsafe.h. */
-#include <wchar.h>
-
-#include <inttypes.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-#include <strsafe.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log_windows.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/string_windows.h"
-
-#if defined UNICODE || defined _UNICODE
-LPTSTR
-gpr_char_to_tchar(LPCSTR input) {
- LPTSTR ret;
- int needed = MultiByteToWideChar(CP_UTF8, 0, input, -1, NULL, 0);
- if (needed <= 0) return NULL;
- ret = (LPTSTR)gpr_malloc((unsigned)needed * sizeof(TCHAR));
- MultiByteToWideChar(CP_UTF8, 0, input, -1, ret, needed);
- return ret;
-}
-
-LPSTR
-gpr_tchar_to_char(LPCTSTR input) {
- LPSTR ret;
- int needed = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
- if (needed <= 0) return NULL;
- ret = (LPSTR)gpr_malloc((unsigned)needed);
- WideCharToMultiByte(CP_UTF8, 0, input, -1, ret, needed, NULL, NULL);
- return ret;
-}
-#else
-LPSTR gpr_tchar_to_char(LPCTSTR input) { return (LPSTR)gpr_strdup(input); }
-
-LPTSTR gpr_char_to_tchar(LPCTSTR input) { return (LPTSTR)gpr_strdup(input); }
-#endif
-
-char* gpr_format_message(int messageid) {
- LPTSTR tmessage;
- char* message;
- DWORD status = FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL, (DWORD)messageid, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
- (LPTSTR)(&tmessage), 0, NULL);
- if (status == 0) return gpr_strdup("Unable to retrieve error string");
- message = gpr_tchar_to_char(tmessage);
- LocalFree(tmessage);
- return message;
-}
-
-#endif /* GPR_WINDOWS */
+/*
+ *
+ * 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.
+ *
+ */
+
+/* Posix code for gpr snprintf support. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WINDOWS
+
+/* Some platforms (namely msys) need wchar to be included BEFORE
+ anything else, especially strsafe.h. */
+#include <wchar.h>
+
+#include <inttypes.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <strsafe.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log_windows.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/string_windows.h"
+
+#if defined UNICODE || defined _UNICODE
+LPTSTR
+gpr_char_to_tchar(LPCSTR input) {
+ LPTSTR ret;
+ int needed = MultiByteToWideChar(CP_UTF8, 0, input, -1, NULL, 0);
+ if (needed <= 0) return NULL;
+ ret = (LPTSTR)gpr_malloc((unsigned)needed * sizeof(TCHAR));
+ MultiByteToWideChar(CP_UTF8, 0, input, -1, ret, needed);
+ return ret;
+}
+
+LPSTR
+gpr_tchar_to_char(LPCTSTR input) {
+ LPSTR ret;
+ int needed = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
+ if (needed <= 0) return NULL;
+ ret = (LPSTR)gpr_malloc((unsigned)needed);
+ WideCharToMultiByte(CP_UTF8, 0, input, -1, ret, needed, NULL, NULL);
+ return ret;
+}
+#else
+LPSTR gpr_tchar_to_char(LPCTSTR input) { return (LPSTR)gpr_strdup(input); }
+
+LPTSTR gpr_char_to_tchar(LPCTSTR input) { return (LPTSTR)gpr_strdup(input); }
+#endif
+
+char* gpr_format_message(int messageid) {
+ LPTSTR tmessage;
+ char* message;
+ DWORD status = FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, (DWORD)messageid, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
+ (LPTSTR)(&tmessage), 0, NULL);
+ if (status == 0) return gpr_strdup("Unable to retrieve error string");
+ message = gpr_tchar_to_char(tmessage);
+ LocalFree(tmessage);
+ return message;
+}
+
+#endif /* GPR_WINDOWS */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/string_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/string_windows.cc
index 25bfd412e44..e7197e26e50 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/string_windows.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.
- *
- */
-
-/* Windows code for gpr snprintf support. */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS_STRING
-
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string.h"
-
-int gpr_asprintf(char** strp, const char* format, ...) {
- va_list args;
- int ret;
- size_t strp_buflen;
-
- /* Determine the length. */
- va_start(args, format);
- ret = _vscprintf(format, args);
- va_end(args);
- if (ret < 0) {
- *strp = NULL;
- return -1;
- }
-
- /* Allocate a new buffer, with space for the NUL terminator. */
- strp_buflen = (size_t)ret + 1;
- if ((*strp = (char*)gpr_malloc(strp_buflen)) == NULL) {
- /* This shouldn't happen, because gpr_malloc() calls abort(). */
- return -1;
- }
-
- /* Print to the buffer. */
- va_start(args, format);
- ret = vsnprintf_s(*strp, strp_buflen, _TRUNCATE, format, args);
- va_end(args);
- if ((size_t)ret == strp_buflen - 1) {
- return ret;
- }
-
- /* This should never happen. */
- gpr_free(*strp);
- *strp = NULL;
- return -1;
-}
-
-#endif /* GPR_WINDOWS_STRING */
+/*
+ *
+ * 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.
+ *
+ */
+
+/* Windows code for gpr snprintf support. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WINDOWS_STRING
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string.h"
+
+int gpr_asprintf(char** strp, const char* format, ...) {
+ va_list args;
+ int ret;
+ size_t strp_buflen;
+
+ /* Determine the length. */
+ va_start(args, format);
+ ret = _vscprintf(format, args);
+ va_end(args);
+ if (ret < 0) {
+ *strp = NULL;
+ return -1;
+ }
+
+ /* Allocate a new buffer, with space for the NUL terminator. */
+ strp_buflen = (size_t)ret + 1;
+ if ((*strp = (char*)gpr_malloc(strp_buflen)) == NULL) {
+ /* This shouldn't happen, because gpr_malloc() calls abort(). */
+ return -1;
+ }
+
+ /* Print to the buffer. */
+ va_start(args, format);
+ ret = vsnprintf_s(*strp, strp_buflen, _TRUNCATE, format, args);
+ va_end(args);
+ if ((size_t)ret == strp_buflen - 1) {
+ return ret;
+ }
+
+ /* This should never happen. */
+ gpr_free(*strp);
+ *strp = NULL;
+ return -1;
+}
+
+#endif /* GPR_WINDOWS_STRING */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/string_windows.h b/contrib/libs/grpc/src/core/lib/gpr/string_windows.h
index e370f802cf9..1e644ed08b3 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/string_windows.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/string_windows.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_CORE_LIB_GPR_STRING_WINDOWS_H
-#define GRPC_CORE_LIB_GPR_STRING_WINDOWS_H
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS
-
-/* These allocate new strings using gpr_malloc to convert from and to utf-8. */
-LPTSTR gpr_char_to_tchar(LPCSTR input);
-LPSTR gpr_tchar_to_char(LPCTSTR input);
-
-#endif /* GPR_WINDOWS */
-
-#endif /* GRPC_CORE_LIB_GPR_STRING_WINDOWS_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_GPR_STRING_WINDOWS_H
+#define GRPC_CORE_LIB_GPR_STRING_WINDOWS_H
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WINDOWS
+
+/* These allocate new strings using gpr_malloc to convert from and to utf-8. */
+LPTSTR gpr_char_to_tchar(LPCSTR input);
+LPSTR gpr_tchar_to_char(LPCTSTR input);
+
+#endif /* GPR_WINDOWS */
+
+#endif /* GRPC_CORE_LIB_GPR_STRING_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/sync.cc b/contrib/libs/grpc/src/core/lib/gpr/sync.cc
index 2f18fc5ecb4..1ad2dd33818 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/sync.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/sync.cc
@@ -1,124 +1,124 @@
-/*
- *
- * 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.
- *
- */
-
-/* Generic implementation of synchronization primitives. */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include <assert.h>
-
-/* Number of mutexes to allocate for events, to avoid lock contention.
- Should be a prime. */
-enum { event_sync_partitions = 31 };
-
-/* Events are partitioned by address to avoid lock contention. */
-static struct sync_array_s {
- gpr_mu mu;
- gpr_cv cv;
-} sync_array[event_sync_partitions];
-
-/* This routine is executed once on first use, via event_once */
-static gpr_once event_once = GPR_ONCE_INIT;
-static void event_initialize(void) {
- int i;
- for (i = 0; i != event_sync_partitions; i++) {
- gpr_mu_init(&sync_array[i].mu);
- gpr_cv_init(&sync_array[i].cv);
- }
-}
-
-/* Hash ev into an element of sync_array[]. */
-static struct sync_array_s* hash(gpr_event* ev) {
- return &sync_array[((uintptr_t)ev) % event_sync_partitions];
-}
-
-void gpr_event_init(gpr_event* ev) {
- gpr_once_init(&event_once, &event_initialize);
- ev->state = 0;
-}
-
-void gpr_event_set(gpr_event* ev, void* value) {
- struct sync_array_s* s = hash(ev);
- gpr_mu_lock(&s->mu);
- GPR_ASSERT(gpr_atm_acq_load(&ev->state) == 0);
- gpr_atm_rel_store(&ev->state, (gpr_atm)value);
- gpr_cv_broadcast(&s->cv);
- gpr_mu_unlock(&s->mu);
- GPR_ASSERT(value != nullptr);
-}
-
-void* gpr_event_get(gpr_event* ev) {
- return (void*)gpr_atm_acq_load(&ev->state);
-}
-
-void* gpr_event_wait(gpr_event* ev, gpr_timespec abs_deadline) {
- void* result = (void*)gpr_atm_acq_load(&ev->state);
- if (result == nullptr) {
- struct sync_array_s* s = hash(ev);
- gpr_mu_lock(&s->mu);
- do {
- result = (void*)gpr_atm_acq_load(&ev->state);
- } while (result == nullptr && !gpr_cv_wait(&s->cv, &s->mu, abs_deadline));
- gpr_mu_unlock(&s->mu);
- }
- return result;
-}
-
-void gpr_ref_init(gpr_refcount* r, int n) { gpr_atm_rel_store(&r->count, n); }
-
-void gpr_ref(gpr_refcount* r) { gpr_atm_no_barrier_fetch_add(&r->count, 1); }
-
-void gpr_ref_non_zero(gpr_refcount* r) {
-#ifndef NDEBUG
- gpr_atm prior = gpr_atm_no_barrier_fetch_add(&r->count, 1);
- assert(prior > 0);
-#else
- gpr_ref(r);
-#endif
-}
-
-void gpr_refn(gpr_refcount* r, int n) {
- gpr_atm_no_barrier_fetch_add(&r->count, n);
-}
-
-int gpr_unref(gpr_refcount* r) {
- gpr_atm prior = gpr_atm_full_fetch_add(&r->count, -1);
- GPR_ASSERT(prior > 0);
- return prior == 1;
-}
-
-int gpr_ref_is_unique(gpr_refcount* r) {
- return gpr_atm_acq_load(&r->count) == 1;
-}
-
-void gpr_stats_init(gpr_stats_counter* c, intptr_t n) {
- gpr_atm_rel_store(&c->value, n);
-}
-
-void gpr_stats_inc(gpr_stats_counter* c, intptr_t inc) {
- gpr_atm_no_barrier_fetch_add(&c->value, inc);
-}
-
-intptr_t gpr_stats_read(const gpr_stats_counter* c) {
- /* don't need acquire-load, but we have no no-barrier load yet */
- return gpr_atm_acq_load(&c->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.
+ *
+ */
+
+/* Generic implementation of synchronization primitives. */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include <assert.h>
+
+/* Number of mutexes to allocate for events, to avoid lock contention.
+ Should be a prime. */
+enum { event_sync_partitions = 31 };
+
+/* Events are partitioned by address to avoid lock contention. */
+static struct sync_array_s {
+ gpr_mu mu;
+ gpr_cv cv;
+} sync_array[event_sync_partitions];
+
+/* This routine is executed once on first use, via event_once */
+static gpr_once event_once = GPR_ONCE_INIT;
+static void event_initialize(void) {
+ int i;
+ for (i = 0; i != event_sync_partitions; i++) {
+ gpr_mu_init(&sync_array[i].mu);
+ gpr_cv_init(&sync_array[i].cv);
+ }
+}
+
+/* Hash ev into an element of sync_array[]. */
+static struct sync_array_s* hash(gpr_event* ev) {
+ return &sync_array[((uintptr_t)ev) % event_sync_partitions];
+}
+
+void gpr_event_init(gpr_event* ev) {
+ gpr_once_init(&event_once, &event_initialize);
+ ev->state = 0;
+}
+
+void gpr_event_set(gpr_event* ev, void* value) {
+ struct sync_array_s* s = hash(ev);
+ gpr_mu_lock(&s->mu);
+ GPR_ASSERT(gpr_atm_acq_load(&ev->state) == 0);
+ gpr_atm_rel_store(&ev->state, (gpr_atm)value);
+ gpr_cv_broadcast(&s->cv);
+ gpr_mu_unlock(&s->mu);
+ GPR_ASSERT(value != nullptr);
+}
+
+void* gpr_event_get(gpr_event* ev) {
+ return (void*)gpr_atm_acq_load(&ev->state);
+}
+
+void* gpr_event_wait(gpr_event* ev, gpr_timespec abs_deadline) {
+ void* result = (void*)gpr_atm_acq_load(&ev->state);
+ if (result == nullptr) {
+ struct sync_array_s* s = hash(ev);
+ gpr_mu_lock(&s->mu);
+ do {
+ result = (void*)gpr_atm_acq_load(&ev->state);
+ } while (result == nullptr && !gpr_cv_wait(&s->cv, &s->mu, abs_deadline));
+ gpr_mu_unlock(&s->mu);
+ }
+ return result;
+}
+
+void gpr_ref_init(gpr_refcount* r, int n) { gpr_atm_rel_store(&r->count, n); }
+
+void gpr_ref(gpr_refcount* r) { gpr_atm_no_barrier_fetch_add(&r->count, 1); }
+
+void gpr_ref_non_zero(gpr_refcount* r) {
+#ifndef NDEBUG
+ gpr_atm prior = gpr_atm_no_barrier_fetch_add(&r->count, 1);
+ assert(prior > 0);
+#else
+ gpr_ref(r);
+#endif
+}
+
+void gpr_refn(gpr_refcount* r, int n) {
+ gpr_atm_no_barrier_fetch_add(&r->count, n);
+}
+
+int gpr_unref(gpr_refcount* r) {
+ gpr_atm prior = gpr_atm_full_fetch_add(&r->count, -1);
+ GPR_ASSERT(prior > 0);
+ return prior == 1;
+}
+
+int gpr_ref_is_unique(gpr_refcount* r) {
+ return gpr_atm_acq_load(&r->count) == 1;
+}
+
+void gpr_stats_init(gpr_stats_counter* c, intptr_t n) {
+ gpr_atm_rel_store(&c->value, n);
+}
+
+void gpr_stats_inc(gpr_stats_counter* c, intptr_t inc) {
+ gpr_atm_no_barrier_fetch_add(&c->value, inc);
+}
+
+intptr_t gpr_stats_read(const gpr_stats_counter* c) {
+ /* don't need acquire-load, but we have no no-barrier load yet */
+ return gpr_atm_acq_load(&c->value);
+}
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 fdd278be233..e9556cadb8e 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc
@@ -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.
- *
- */
-
-#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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
#if defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC)
#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
#include <errno.h>
-#include <time.h>
-
-#include "src/core/lib/profiling/timers.h"
-
-#ifdef GPR_LOW_LEVEL_COUNTERS
-gpr_atm gpr_mu_locks = 0;
-gpr_atm gpr_counter_atm_cas = 0;
-gpr_atm gpr_counter_atm_add = 0;
-#endif
-
-void gpr_mu_init(gpr_mu* mu) {
+#include <time.h>
+
+#include "src/core/lib/profiling/timers.h"
+
+#ifdef GPR_LOW_LEVEL_COUNTERS
+gpr_atm gpr_mu_locks = 0;
+gpr_atm gpr_counter_atm_cas = 0;
+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
- GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0);
+ GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0);
#endif
-}
-
+}
+
void gpr_mu_destroy(gpr_mu* mu) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_destroy(&mu->mutex) == 0);
@@ -55,58 +55,58 @@ void gpr_mu_destroy(gpr_mu* mu) {
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);
+
+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
- GPR_ASSERT(pthread_mutex_lock(mu) == 0);
+ GPR_ASSERT(pthread_mutex_lock(mu) == 0);
#endif
-}
-
-void gpr_mu_unlock(gpr_mu* mu) {
- GPR_TIMER_SCOPE("gpr_mu_unlock", 0);
+}
+
+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
- GPR_ASSERT(pthread_mutex_unlock(mu) == 0);
+ GPR_ASSERT(pthread_mutex_unlock(mu) == 0);
#endif
-}
-
-int gpr_mu_trylock(gpr_mu* mu) {
- GPR_TIMER_SCOPE("gpr_mu_trylock", 0);
+}
+
+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
- GPR_ASSERT(err == 0 || err == EBUSY);
- return err == 0;
-}
-
-/*----------------------------------------*/
-
-void gpr_cv_init(gpr_cv* cv) {
- pthread_condattr_t attr;
- GPR_ASSERT(pthread_condattr_init(&attr) == 0);
-#if GPR_LINUX
- GPR_ASSERT(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0);
-#endif // GPR_LINUX
+ GPR_ASSERT(err == 0 || err == EBUSY);
+ return err == 0;
+}
+
+/*----------------------------------------*/
+
+void gpr_cv_init(gpr_cv* cv) {
+ pthread_condattr_t attr;
+ GPR_ASSERT(pthread_condattr_init(&attr) == 0);
+#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
- GPR_ASSERT(pthread_cond_init(cv, &attr) == 0);
+ GPR_ASSERT(pthread_cond_init(cv, &attr) == 0);
#endif
-}
-
+}
+
void gpr_cv_destroy(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_destroy(&cv->cond_var) == 0);
@@ -116,34 +116,34 @@ void gpr_cv_destroy(gpr_cv* cv) {
#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) {
+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
- err = pthread_cond_wait(cv, mu);
+ err = pthread_cond_wait(cv, mu);
#endif
- } else {
- struct timespec abs_deadline_ts;
-#if GPR_LINUX
+ } else {
+ struct timespec abs_deadline_ts;
+#if GPR_LINUX
abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_MONOTONIC);
-#else
+#else
abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
-#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;
+#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
- err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);
+ err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);
#endif
- }
- GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN);
- return err == ETIMEDOUT;
-}
-
+ }
+ GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN);
+ return err == ETIMEDOUT;
+}
+
void gpr_cv_signal(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_signal(&cv->cond_var) == 0);
@@ -151,20 +151,20 @@ void gpr_cv_signal(gpr_cv* cv) {
GPR_ASSERT(pthread_cond_signal(cv) == 0);
#endif
}
-
-void gpr_cv_broadcast(gpr_cv* cv) {
+
+void gpr_cv_broadcast(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_broadcast(&cv->cond_var) == 0);
#else
- GPR_ASSERT(pthread_cond_broadcast(cv) == 0);
+ GPR_ASSERT(pthread_cond_broadcast(cv) == 0);
#endif
-}
-
-/*----------------------------------------*/
-
-void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
- GPR_ASSERT(pthread_once(once, init_function) == 0);
-}
-
+}
+
+/*----------------------------------------*/
+
+void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
+ GPR_ASSERT(pthread_once(once, init_function) == 0);
+}
+
#endif /* defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC) */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/sync_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/sync_windows.cc
index 64eec7c2e11..afbe61d37d0 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/sync_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/sync_windows.cc
@@ -1,120 +1,120 @@
-/*
- *
- * 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.
- *
- */
-
-/* Win32 code for gpr synchronization support. */
-
-#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.
+ *
+ */
+
+/* Win32 code for gpr synchronization support. */
+
+#include <grpc/support/port_platform.h>
+
#if defined(GPR_WINDOWS) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC)
-
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-
-void gpr_mu_init(gpr_mu* mu) {
- InitializeCriticalSection(&mu->cs);
- mu->locked = 0;
-}
-
-void gpr_mu_destroy(gpr_mu* mu) { DeleteCriticalSection(&mu->cs); }
-
-void gpr_mu_lock(gpr_mu* mu) {
- EnterCriticalSection(&mu->cs);
- GPR_ASSERT(!mu->locked);
- mu->locked = 1;
-}
-
-void gpr_mu_unlock(gpr_mu* mu) {
- mu->locked = 0;
- LeaveCriticalSection(&mu->cs);
-}
-
-int gpr_mu_trylock(gpr_mu* mu) {
- int result = TryEnterCriticalSection(&mu->cs);
- if (result) {
- if (mu->locked) { /* This thread already holds the lock. */
- LeaveCriticalSection(&mu->cs); /* Decrement lock count. */
- result = 0; /* Indicate failure */
- }
- mu->locked = 1;
- }
- return result;
-}
-
-/*----------------------------------------*/
-
-void gpr_cv_init(gpr_cv* cv) { InitializeConditionVariable(cv); }
-
-void gpr_cv_destroy(gpr_cv* cv) {
- /* Condition variables don't need destruction in Win32. */
-}
-
-int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
- int timeout = 0;
- DWORD timeout_max_ms;
- mu->locked = 0;
- if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
- 0) {
- SleepConditionVariableCS(cv, &mu->cs, INFINITE);
- } else {
- abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
- gpr_timespec now = gpr_now(abs_deadline.clock_type);
- int64_t now_ms = (int64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
- int64_t deadline_ms =
- (int64_t)abs_deadline.tv_sec * 1000 + abs_deadline.tv_nsec / 1000000;
- if (now_ms >= deadline_ms) {
- timeout = 1;
- } else {
- if ((deadline_ms - now_ms) >= INFINITE) {
- timeout_max_ms = INFINITE - 1;
- } else {
- timeout_max_ms = (DWORD)(deadline_ms - now_ms);
- }
- timeout = (SleepConditionVariableCS(cv, &mu->cs, timeout_max_ms) == 0 &&
- GetLastError() == ERROR_TIMEOUT);
- }
- }
- mu->locked = 1;
- return timeout;
-}
-
-void gpr_cv_signal(gpr_cv* cv) { WakeConditionVariable(cv); }
-
-void gpr_cv_broadcast(gpr_cv* cv) { WakeAllConditionVariable(cv); }
-
-/*----------------------------------------*/
-
-static void* dummy;
-struct run_once_func_arg {
- void (*init_function)(void);
-};
-static BOOL CALLBACK run_once_func(gpr_once* once, void* v, void** pv) {
- struct run_once_func_arg* arg = (struct run_once_func_arg*)v;
- (*arg->init_function)();
- return 1;
-}
-
-void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
- struct run_once_func_arg arg;
- arg.init_function = init_function;
- InitOnceExecuteOnce(once, run_once_func, &arg, &dummy);
-}
-
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+
+void gpr_mu_init(gpr_mu* mu) {
+ InitializeCriticalSection(&mu->cs);
+ mu->locked = 0;
+}
+
+void gpr_mu_destroy(gpr_mu* mu) { DeleteCriticalSection(&mu->cs); }
+
+void gpr_mu_lock(gpr_mu* mu) {
+ EnterCriticalSection(&mu->cs);
+ GPR_ASSERT(!mu->locked);
+ mu->locked = 1;
+}
+
+void gpr_mu_unlock(gpr_mu* mu) {
+ mu->locked = 0;
+ LeaveCriticalSection(&mu->cs);
+}
+
+int gpr_mu_trylock(gpr_mu* mu) {
+ int result = TryEnterCriticalSection(&mu->cs);
+ if (result) {
+ if (mu->locked) { /* This thread already holds the lock. */
+ LeaveCriticalSection(&mu->cs); /* Decrement lock count. */
+ result = 0; /* Indicate failure */
+ }
+ mu->locked = 1;
+ }
+ return result;
+}
+
+/*----------------------------------------*/
+
+void gpr_cv_init(gpr_cv* cv) { InitializeConditionVariable(cv); }
+
+void gpr_cv_destroy(gpr_cv* cv) {
+ /* Condition variables don't need destruction in Win32. */
+}
+
+int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
+ int timeout = 0;
+ DWORD timeout_max_ms;
+ mu->locked = 0;
+ if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
+ 0) {
+ SleepConditionVariableCS(cv, &mu->cs, INFINITE);
+ } else {
+ abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
+ gpr_timespec now = gpr_now(abs_deadline.clock_type);
+ int64_t now_ms = (int64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
+ int64_t deadline_ms =
+ (int64_t)abs_deadline.tv_sec * 1000 + abs_deadline.tv_nsec / 1000000;
+ if (now_ms >= deadline_ms) {
+ timeout = 1;
+ } else {
+ if ((deadline_ms - now_ms) >= INFINITE) {
+ timeout_max_ms = INFINITE - 1;
+ } else {
+ timeout_max_ms = (DWORD)(deadline_ms - now_ms);
+ }
+ timeout = (SleepConditionVariableCS(cv, &mu->cs, timeout_max_ms) == 0 &&
+ GetLastError() == ERROR_TIMEOUT);
+ }
+ }
+ mu->locked = 1;
+ return timeout;
+}
+
+void gpr_cv_signal(gpr_cv* cv) { WakeConditionVariable(cv); }
+
+void gpr_cv_broadcast(gpr_cv* cv) { WakeAllConditionVariable(cv); }
+
+/*----------------------------------------*/
+
+static void* dummy;
+struct run_once_func_arg {
+ void (*init_function)(void);
+};
+static BOOL CALLBACK run_once_func(gpr_once* once, void* v, void** pv) {
+ struct run_once_func_arg* arg = (struct run_once_func_arg*)v;
+ (*arg->init_function)();
+ return 1;
+}
+
+void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
+ struct run_once_func_arg arg;
+ arg.init_function = init_function;
+ InitOnceExecuteOnce(once, run_once_func, &arg, &dummy);
+}
+
#endif /* defined(GPR_WINDOWS) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC) */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/time.cc b/contrib/libs/grpc/src/core/lib/gpr/time.cc
index db5a7f64f70..efb4ff22929 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/time.cc
@@ -1,263 +1,263 @@
-/*
- *
- * 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.
- *
- */
-
-/* Generic implementation of time calls. */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <limits.h>
-#include <stdio.h>
-#include <string.h>
-
-int gpr_time_cmp(gpr_timespec a, gpr_timespec b) {
- int cmp = (a.tv_sec > b.tv_sec) - (a.tv_sec < b.tv_sec);
- GPR_ASSERT(a.clock_type == b.clock_type);
- if (cmp == 0 && a.tv_sec != INT64_MAX && a.tv_sec != INT64_MIN) {
- cmp = (a.tv_nsec > b.tv_nsec) - (a.tv_nsec < b.tv_nsec);
- }
- return cmp;
-}
-
-gpr_timespec gpr_time_min(gpr_timespec a, gpr_timespec b) {
- return gpr_time_cmp(a, b) < 0 ? a : b;
-}
-
-gpr_timespec gpr_time_max(gpr_timespec a, gpr_timespec b) {
- return gpr_time_cmp(a, b) > 0 ? a : b;
-}
-
-gpr_timespec gpr_time_0(gpr_clock_type type) {
- gpr_timespec out;
- out.tv_sec = 0;
- out.tv_nsec = 0;
- out.clock_type = type;
- return out;
-}
-
-gpr_timespec gpr_inf_future(gpr_clock_type type) {
- gpr_timespec out;
- out.tv_sec = INT64_MAX;
- out.tv_nsec = 0;
- out.clock_type = type;
- return out;
-}
-
-gpr_timespec gpr_inf_past(gpr_clock_type type) {
- gpr_timespec out;
- out.tv_sec = INT64_MIN;
- out.tv_nsec = 0;
- out.clock_type = type;
- return out;
-}
-
-static gpr_timespec to_seconds_from_sub_second_time(int64_t time_in_units,
- int64_t units_per_sec,
- gpr_clock_type type) {
- gpr_timespec out;
- if (time_in_units == INT64_MAX) {
- out = gpr_inf_future(type);
- } else if (time_in_units == INT64_MIN) {
- out = gpr_inf_past(type);
- } else {
- if (time_in_units >= 0) {
- out.tv_sec = time_in_units / units_per_sec;
- } else {
- out.tv_sec = (-((units_per_sec - 1) - (time_in_units + units_per_sec)) /
- units_per_sec) -
- 1;
- }
- out.tv_nsec =
- static_cast<int32_t>((time_in_units - out.tv_sec * units_per_sec) *
- GPR_NS_PER_SEC / units_per_sec);
- out.clock_type = type;
- }
- return out;
-}
-
-static gpr_timespec to_seconds_from_above_second_time(int64_t time_in_units,
- int64_t secs_per_unit,
- gpr_clock_type type) {
- gpr_timespec out;
- if (time_in_units >= INT64_MAX / secs_per_unit) {
- out = gpr_inf_future(type);
- } else if (time_in_units <= INT64_MIN / secs_per_unit) {
- out = gpr_inf_past(type);
- } else {
- out.tv_sec = time_in_units * secs_per_unit;
- out.tv_nsec = 0;
- out.clock_type = type;
- }
- return out;
-}
-
-gpr_timespec gpr_time_from_nanos(int64_t ns, gpr_clock_type type) {
- return to_seconds_from_sub_second_time(ns, GPR_NS_PER_SEC, type);
-}
-
-gpr_timespec gpr_time_from_micros(int64_t us, gpr_clock_type type) {
- return to_seconds_from_sub_second_time(us, GPR_US_PER_SEC, type);
-}
-
-gpr_timespec gpr_time_from_millis(int64_t ms, gpr_clock_type type) {
- return to_seconds_from_sub_second_time(ms, GPR_MS_PER_SEC, type);
-}
-
-gpr_timespec gpr_time_from_seconds(int64_t s, gpr_clock_type type) {
- return to_seconds_from_sub_second_time(s, 1, type);
-}
-
-gpr_timespec gpr_time_from_minutes(int64_t m, gpr_clock_type type) {
- return to_seconds_from_above_second_time(m, 60, type);
-}
-
-gpr_timespec gpr_time_from_hours(int64_t h, gpr_clock_type type) {
- return to_seconds_from_above_second_time(h, 3600, type);
-}
-
-gpr_timespec gpr_time_add(gpr_timespec a, gpr_timespec b) {
- gpr_timespec sum;
- int64_t inc = 0;
- GPR_ASSERT(b.clock_type == GPR_TIMESPAN);
+/*
+ *
+ * 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.
+ *
+ */
+
+/* Generic implementation of time calls. */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+int gpr_time_cmp(gpr_timespec a, gpr_timespec b) {
+ int cmp = (a.tv_sec > b.tv_sec) - (a.tv_sec < b.tv_sec);
+ GPR_ASSERT(a.clock_type == b.clock_type);
+ if (cmp == 0 && a.tv_sec != INT64_MAX && a.tv_sec != INT64_MIN) {
+ cmp = (a.tv_nsec > b.tv_nsec) - (a.tv_nsec < b.tv_nsec);
+ }
+ return cmp;
+}
+
+gpr_timespec gpr_time_min(gpr_timespec a, gpr_timespec b) {
+ return gpr_time_cmp(a, b) < 0 ? a : b;
+}
+
+gpr_timespec gpr_time_max(gpr_timespec a, gpr_timespec b) {
+ return gpr_time_cmp(a, b) > 0 ? a : b;
+}
+
+gpr_timespec gpr_time_0(gpr_clock_type type) {
+ gpr_timespec out;
+ out.tv_sec = 0;
+ out.tv_nsec = 0;
+ out.clock_type = type;
+ return out;
+}
+
+gpr_timespec gpr_inf_future(gpr_clock_type type) {
+ gpr_timespec out;
+ out.tv_sec = INT64_MAX;
+ out.tv_nsec = 0;
+ out.clock_type = type;
+ return out;
+}
+
+gpr_timespec gpr_inf_past(gpr_clock_type type) {
+ gpr_timespec out;
+ out.tv_sec = INT64_MIN;
+ out.tv_nsec = 0;
+ out.clock_type = type;
+ return out;
+}
+
+static gpr_timespec to_seconds_from_sub_second_time(int64_t time_in_units,
+ int64_t units_per_sec,
+ gpr_clock_type type) {
+ gpr_timespec out;
+ if (time_in_units == INT64_MAX) {
+ out = gpr_inf_future(type);
+ } else if (time_in_units == INT64_MIN) {
+ out = gpr_inf_past(type);
+ } else {
+ if (time_in_units >= 0) {
+ out.tv_sec = time_in_units / units_per_sec;
+ } else {
+ out.tv_sec = (-((units_per_sec - 1) - (time_in_units + units_per_sec)) /
+ units_per_sec) -
+ 1;
+ }
+ out.tv_nsec =
+ static_cast<int32_t>((time_in_units - out.tv_sec * units_per_sec) *
+ GPR_NS_PER_SEC / units_per_sec);
+ out.clock_type = type;
+ }
+ return out;
+}
+
+static gpr_timespec to_seconds_from_above_second_time(int64_t time_in_units,
+ int64_t secs_per_unit,
+ gpr_clock_type type) {
+ gpr_timespec out;
+ if (time_in_units >= INT64_MAX / secs_per_unit) {
+ out = gpr_inf_future(type);
+ } else if (time_in_units <= INT64_MIN / secs_per_unit) {
+ out = gpr_inf_past(type);
+ } else {
+ out.tv_sec = time_in_units * secs_per_unit;
+ out.tv_nsec = 0;
+ out.clock_type = type;
+ }
+ return out;
+}
+
+gpr_timespec gpr_time_from_nanos(int64_t ns, gpr_clock_type type) {
+ return to_seconds_from_sub_second_time(ns, GPR_NS_PER_SEC, type);
+}
+
+gpr_timespec gpr_time_from_micros(int64_t us, gpr_clock_type type) {
+ return to_seconds_from_sub_second_time(us, GPR_US_PER_SEC, type);
+}
+
+gpr_timespec gpr_time_from_millis(int64_t ms, gpr_clock_type type) {
+ return to_seconds_from_sub_second_time(ms, GPR_MS_PER_SEC, type);
+}
+
+gpr_timespec gpr_time_from_seconds(int64_t s, gpr_clock_type type) {
+ return to_seconds_from_sub_second_time(s, 1, type);
+}
+
+gpr_timespec gpr_time_from_minutes(int64_t m, gpr_clock_type type) {
+ return to_seconds_from_above_second_time(m, 60, type);
+}
+
+gpr_timespec gpr_time_from_hours(int64_t h, gpr_clock_type type) {
+ return to_seconds_from_above_second_time(h, 3600, type);
+}
+
+gpr_timespec gpr_time_add(gpr_timespec a, gpr_timespec b) {
+ gpr_timespec sum;
+ int64_t inc = 0;
+ GPR_ASSERT(b.clock_type == GPR_TIMESPAN);
// tv_nsec in a timespan is always +ve. -ve timespan is represented as (-ve
// tv_sec, +ve tv_nsec). For example, timespan = -2.5 seconds is represented
// as {-3, 5e8, GPR_TIMESPAN}
GPR_ASSERT(b.tv_nsec >= 0);
- sum.clock_type = a.clock_type;
- sum.tv_nsec = a.tv_nsec + b.tv_nsec;
- if (sum.tv_nsec >= GPR_NS_PER_SEC) {
- sum.tv_nsec -= GPR_NS_PER_SEC;
- inc++;
- }
- if (a.tv_sec == INT64_MAX || a.tv_sec == INT64_MIN) {
- sum = a;
- } else if (b.tv_sec == INT64_MAX ||
- (b.tv_sec >= 0 && a.tv_sec >= INT64_MAX - b.tv_sec)) {
- sum = gpr_inf_future(sum.clock_type);
- } else if (b.tv_sec == INT64_MIN ||
- (b.tv_sec <= 0 && a.tv_sec <= INT64_MIN - b.tv_sec)) {
- sum = gpr_inf_past(sum.clock_type);
- } else {
- sum.tv_sec = a.tv_sec + b.tv_sec;
- if (inc != 0 && sum.tv_sec == INT64_MAX - 1) {
- sum = gpr_inf_future(sum.clock_type);
- } else {
- sum.tv_sec += inc;
- }
- }
- return sum;
-}
-
-gpr_timespec gpr_time_sub(gpr_timespec a, gpr_timespec b) {
- gpr_timespec diff;
- int64_t dec = 0;
- if (b.clock_type == GPR_TIMESPAN) {
- diff.clock_type = a.clock_type;
+ sum.clock_type = a.clock_type;
+ sum.tv_nsec = a.tv_nsec + b.tv_nsec;
+ if (sum.tv_nsec >= GPR_NS_PER_SEC) {
+ sum.tv_nsec -= GPR_NS_PER_SEC;
+ inc++;
+ }
+ if (a.tv_sec == INT64_MAX || a.tv_sec == INT64_MIN) {
+ sum = a;
+ } else if (b.tv_sec == INT64_MAX ||
+ (b.tv_sec >= 0 && a.tv_sec >= INT64_MAX - b.tv_sec)) {
+ sum = gpr_inf_future(sum.clock_type);
+ } else if (b.tv_sec == INT64_MIN ||
+ (b.tv_sec <= 0 && a.tv_sec <= INT64_MIN - b.tv_sec)) {
+ sum = gpr_inf_past(sum.clock_type);
+ } else {
+ sum.tv_sec = a.tv_sec + b.tv_sec;
+ if (inc != 0 && sum.tv_sec == INT64_MAX - 1) {
+ sum = gpr_inf_future(sum.clock_type);
+ } else {
+ sum.tv_sec += inc;
+ }
+ }
+ return sum;
+}
+
+gpr_timespec gpr_time_sub(gpr_timespec a, gpr_timespec b) {
+ gpr_timespec diff;
+ int64_t dec = 0;
+ if (b.clock_type == GPR_TIMESPAN) {
+ diff.clock_type = a.clock_type;
// tv_nsec in a timespan is always +ve. -ve timespan is represented as (-ve
// tv_sec, +ve tv_nsec). For example, timespan = -2.5 seconds is represented
// as {-3, 5e8, GPR_TIMESPAN}
GPR_ASSERT(b.tv_nsec >= 0);
- } else {
- GPR_ASSERT(a.clock_type == b.clock_type);
- diff.clock_type = GPR_TIMESPAN;
- }
- diff.tv_nsec = a.tv_nsec - b.tv_nsec;
- if (diff.tv_nsec < 0) {
- diff.tv_nsec += GPR_NS_PER_SEC;
- dec++;
- }
- if (a.tv_sec == INT64_MAX || a.tv_sec == INT64_MIN) {
- diff = a;
- } else if (b.tv_sec == INT64_MIN ||
- (b.tv_sec <= 0 && a.tv_sec >= INT64_MAX + b.tv_sec)) {
- diff = gpr_inf_future(GPR_CLOCK_REALTIME);
- } else if (b.tv_sec == INT64_MAX ||
- (b.tv_sec >= 0 && a.tv_sec <= INT64_MIN + b.tv_sec)) {
- diff = gpr_inf_past(GPR_CLOCK_REALTIME);
- } else {
- diff.tv_sec = a.tv_sec - b.tv_sec;
- if (dec != 0 && diff.tv_sec == INT64_MIN + 1) {
- diff = gpr_inf_past(GPR_CLOCK_REALTIME);
- } else {
- diff.tv_sec -= dec;
- }
- }
- return diff;
-}
-
-int gpr_time_similar(gpr_timespec a, gpr_timespec b, gpr_timespec threshold) {
- int cmp_ab;
-
- GPR_ASSERT(a.clock_type == b.clock_type);
- GPR_ASSERT(threshold.clock_type == GPR_TIMESPAN);
-
- cmp_ab = gpr_time_cmp(a, b);
- if (cmp_ab == 0) return 1;
- if (cmp_ab < 0) {
- return gpr_time_cmp(gpr_time_sub(b, a), threshold) <= 0;
- } else {
- return gpr_time_cmp(gpr_time_sub(a, b), threshold) <= 0;
- }
-}
-
-int32_t gpr_time_to_millis(gpr_timespec t) {
- if (t.tv_sec >= 2147483) {
- if (t.tv_sec == 2147483 && t.tv_nsec < 648 * GPR_NS_PER_MS) {
- return 2147483 * GPR_MS_PER_SEC + t.tv_nsec / GPR_NS_PER_MS;
- }
- return 2147483647;
- } else if (t.tv_sec <= -2147483) {
- /* TODO(ctiller): correct handling here (it's so far in the past do we
- care?) */
- return -2147483647;
- } else {
- return static_cast<int32_t>(t.tv_sec * GPR_MS_PER_SEC +
- t.tv_nsec / GPR_NS_PER_MS);
- }
-}
-
-double gpr_timespec_to_micros(gpr_timespec t) {
- return static_cast<double>(t.tv_sec) * GPR_US_PER_SEC + t.tv_nsec * 1e-3;
-}
-
-gpr_timespec gpr_convert_clock_type(gpr_timespec t, gpr_clock_type clock_type) {
- if (t.clock_type == clock_type) {
- return t;
- }
-
- if (t.tv_sec == INT64_MAX || t.tv_sec == INT64_MIN) {
- t.clock_type = clock_type;
- return t;
- }
-
- if (clock_type == GPR_TIMESPAN) {
- return gpr_time_sub(t, gpr_now(t.clock_type));
- }
-
- if (t.clock_type == GPR_TIMESPAN) {
- return gpr_time_add(gpr_now(clock_type), t);
- }
-
+ } else {
+ GPR_ASSERT(a.clock_type == b.clock_type);
+ diff.clock_type = GPR_TIMESPAN;
+ }
+ diff.tv_nsec = a.tv_nsec - b.tv_nsec;
+ if (diff.tv_nsec < 0) {
+ diff.tv_nsec += GPR_NS_PER_SEC;
+ dec++;
+ }
+ if (a.tv_sec == INT64_MAX || a.tv_sec == INT64_MIN) {
+ diff = a;
+ } else if (b.tv_sec == INT64_MIN ||
+ (b.tv_sec <= 0 && a.tv_sec >= INT64_MAX + b.tv_sec)) {
+ diff = gpr_inf_future(GPR_CLOCK_REALTIME);
+ } else if (b.tv_sec == INT64_MAX ||
+ (b.tv_sec >= 0 && a.tv_sec <= INT64_MIN + b.tv_sec)) {
+ diff = gpr_inf_past(GPR_CLOCK_REALTIME);
+ } else {
+ diff.tv_sec = a.tv_sec - b.tv_sec;
+ if (dec != 0 && diff.tv_sec == INT64_MIN + 1) {
+ diff = gpr_inf_past(GPR_CLOCK_REALTIME);
+ } else {
+ diff.tv_sec -= dec;
+ }
+ }
+ return diff;
+}
+
+int gpr_time_similar(gpr_timespec a, gpr_timespec b, gpr_timespec threshold) {
+ int cmp_ab;
+
+ GPR_ASSERT(a.clock_type == b.clock_type);
+ GPR_ASSERT(threshold.clock_type == GPR_TIMESPAN);
+
+ cmp_ab = gpr_time_cmp(a, b);
+ if (cmp_ab == 0) return 1;
+ if (cmp_ab < 0) {
+ return gpr_time_cmp(gpr_time_sub(b, a), threshold) <= 0;
+ } else {
+ return gpr_time_cmp(gpr_time_sub(a, b), threshold) <= 0;
+ }
+}
+
+int32_t gpr_time_to_millis(gpr_timespec t) {
+ if (t.tv_sec >= 2147483) {
+ if (t.tv_sec == 2147483 && t.tv_nsec < 648 * GPR_NS_PER_MS) {
+ return 2147483 * GPR_MS_PER_SEC + t.tv_nsec / GPR_NS_PER_MS;
+ }
+ return 2147483647;
+ } else if (t.tv_sec <= -2147483) {
+ /* TODO(ctiller): correct handling here (it's so far in the past do we
+ care?) */
+ return -2147483647;
+ } else {
+ return static_cast<int32_t>(t.tv_sec * GPR_MS_PER_SEC +
+ t.tv_nsec / GPR_NS_PER_MS);
+ }
+}
+
+double gpr_timespec_to_micros(gpr_timespec t) {
+ return static_cast<double>(t.tv_sec) * GPR_US_PER_SEC + t.tv_nsec * 1e-3;
+}
+
+gpr_timespec gpr_convert_clock_type(gpr_timespec t, gpr_clock_type clock_type) {
+ if (t.clock_type == clock_type) {
+ return t;
+ }
+
+ if (t.tv_sec == INT64_MAX || t.tv_sec == INT64_MIN) {
+ t.clock_type = clock_type;
+ return t;
+ }
+
+ if (clock_type == GPR_TIMESPAN) {
+ return gpr_time_sub(t, gpr_now(t.clock_type));
+ }
+
+ if (t.clock_type == GPR_TIMESPAN) {
+ return gpr_time_add(gpr_now(clock_type), t);
+ }
+
// If the given input hits this code, the same result is not guaranteed for
// the same input because it relies on `gpr_now` to calculate the difference
// between two different clocks. Please be careful when you want to use this
// function in unit tests. (e.g. https://github.com/grpc/grpc/pull/22655)
- return gpr_time_add(gpr_now(clock_type),
- gpr_time_sub(t, gpr_now(t.clock_type)));
-}
+ return gpr_time_add(gpr_now(clock_type),
+ gpr_time_sub(t, gpr_now(t.clock_type)));
+}
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 0a9e1158b32..3d03c872507 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc
@@ -1,132 +1,132 @@
-/*
- *
- * 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/gpr/time_precise.h"
-
-#ifdef GPR_POSIX_TIME
-
-#include <stdlib.h>
-#include <time.h>
-#include <unistd.h>
-#ifdef __linux__
-#include <sys/syscall.h>
-#endif
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-
-static struct timespec timespec_from_gpr(gpr_timespec gts) {
- struct timespec rv;
- if (sizeof(time_t) < sizeof(int64_t)) {
- /* fine to assert, as this is only used in gpr_sleep_until */
- GPR_ASSERT(gts.tv_sec <= INT32_MAX && gts.tv_sec >= INT32_MIN);
- }
- rv.tv_sec = static_cast<time_t>(gts.tv_sec);
- rv.tv_nsec = gts.tv_nsec;
- return rv;
-}
-
-#if _POSIX_TIMERS > 0 || defined(__OpenBSD__)
-static gpr_timespec gpr_from_timespec(struct timespec ts,
- gpr_clock_type clock_type) {
- /*
- * timespec.tv_sec can have smaller size than gpr_timespec.tv_sec,
- * but we are only using this function to implement gpr_now
- * so there's no need to handle "infinity" values.
- */
- gpr_timespec rv;
- rv.tv_sec = ts.tv_sec;
- rv.tv_nsec = static_cast<int32_t>(ts.tv_nsec);
- rv.clock_type = clock_type;
- return rv;
-}
-
-/** maps gpr_clock_type --> clockid_t for clock_gettime */
-static const clockid_t clockid_for_gpr_clock[] = {CLOCK_MONOTONIC,
- CLOCK_REALTIME};
-
-void gpr_time_init(void) { gpr_precise_clock_init(); }
-
-static gpr_timespec now_impl(gpr_clock_type clock_type) {
- struct timespec now;
- GPR_ASSERT(clock_type != GPR_TIMESPAN);
- if (clock_type == GPR_CLOCK_PRECISE) {
- gpr_timespec ret;
- gpr_precise_clock_now(&ret);
- return ret;
- } else {
+/*
+ *
+ * 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/gpr/time_precise.h"
+
+#ifdef GPR_POSIX_TIME
+
+#include <stdlib.h>
+#include <time.h>
+#include <unistd.h>
+#ifdef __linux__
+#include <sys/syscall.h>
+#endif
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+
+static struct timespec timespec_from_gpr(gpr_timespec gts) {
+ struct timespec rv;
+ if (sizeof(time_t) < sizeof(int64_t)) {
+ /* fine to assert, as this is only used in gpr_sleep_until */
+ GPR_ASSERT(gts.tv_sec <= INT32_MAX && gts.tv_sec >= INT32_MIN);
+ }
+ rv.tv_sec = static_cast<time_t>(gts.tv_sec);
+ rv.tv_nsec = gts.tv_nsec;
+ return rv;
+}
+
+#if _POSIX_TIMERS > 0 || defined(__OpenBSD__)
+static gpr_timespec gpr_from_timespec(struct timespec ts,
+ gpr_clock_type clock_type) {
+ /*
+ * timespec.tv_sec can have smaller size than gpr_timespec.tv_sec,
+ * but we are only using this function to implement gpr_now
+ * so there's no need to handle "infinity" values.
+ */
+ gpr_timespec rv;
+ rv.tv_sec = ts.tv_sec;
+ rv.tv_nsec = static_cast<int32_t>(ts.tv_nsec);
+ rv.clock_type = clock_type;
+ return rv;
+}
+
+/** maps gpr_clock_type --> clockid_t for clock_gettime */
+static const clockid_t clockid_for_gpr_clock[] = {CLOCK_MONOTONIC,
+ CLOCK_REALTIME};
+
+void gpr_time_init(void) { gpr_precise_clock_init(); }
+
+static gpr_timespec now_impl(gpr_clock_type clock_type) {
+ struct timespec now;
+ GPR_ASSERT(clock_type != GPR_TIMESPAN);
+ if (clock_type == GPR_CLOCK_PRECISE) {
+ gpr_timespec ret;
+ gpr_precise_clock_now(&ret);
+ return ret;
+ } else {
#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE) && defined(__linux__)
- /* avoid ABI problems by invoking syscalls directly */
- syscall(SYS_clock_gettime, clockid_for_gpr_clock[clock_type], &now);
-#else
- clock_gettime(clockid_for_gpr_clock[clock_type], &now);
-#endif
- return gpr_from_timespec(now, clock_type);
- }
-}
-#else
+ /* avoid ABI problems by invoking syscalls directly */
+ syscall(SYS_clock_gettime, clockid_for_gpr_clock[clock_type], &now);
+#else
+ clock_gettime(clockid_for_gpr_clock[clock_type], &now);
+#endif
+ return gpr_from_timespec(now, clock_type);
+ }
+}
+#else
/* For some reason Apple's OSes haven't implemented clock_gettime. */
-
-#include <mach/mach.h>
-#include <mach/mach_time.h>
-#include <sys/time.h>
-
-static double g_time_scale;
-static uint64_t g_time_start;
-
-void gpr_time_init(void) {
- mach_timebase_info_data_t tb = {0, 1};
- gpr_precise_clock_init();
- mach_timebase_info(&tb);
- g_time_scale = tb.numer;
- g_time_scale /= tb.denom;
- g_time_start = mach_absolute_time();
-}
-
-static gpr_timespec now_impl(gpr_clock_type clock) {
- gpr_timespec now;
- struct timeval now_tv;
- double now_dbl;
-
- now.clock_type = clock;
- switch (clock) {
- case GPR_CLOCK_REALTIME:
+
+#include <mach/mach.h>
+#include <mach/mach_time.h>
+#include <sys/time.h>
+
+static double g_time_scale;
+static uint64_t g_time_start;
+
+void gpr_time_init(void) {
+ mach_timebase_info_data_t tb = {0, 1};
+ gpr_precise_clock_init();
+ mach_timebase_info(&tb);
+ g_time_scale = tb.numer;
+ g_time_scale /= tb.denom;
+ g_time_start = mach_absolute_time();
+}
+
+static gpr_timespec now_impl(gpr_clock_type clock) {
+ gpr_timespec now;
+ struct timeval now_tv;
+ double now_dbl;
+
+ 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(&now_tv, nullptr);
- now.tv_sec = now_tv.tv_sec;
- now.tv_nsec = now_tv.tv_usec * 1000;
- break;
- case GPR_CLOCK_MONOTONIC:
- now_dbl = ((double)(mach_absolute_time() - g_time_start)) * g_time_scale;
- now.tv_sec = (int64_t)(now_dbl * 1e-9);
- now.tv_nsec = (int32_t)(now_dbl - ((double)now.tv_sec) * 1e9);
- break;
- case GPR_CLOCK_PRECISE:
- gpr_precise_clock_now(&now);
- break;
- case GPR_TIMESPAN:
- abort();
- }
-
+ gettimeofday(&now_tv, nullptr);
+ now.tv_sec = now_tv.tv_sec;
+ now.tv_nsec = now_tv.tv_usec * 1000;
+ break;
+ case GPR_CLOCK_MONOTONIC:
+ now_dbl = ((double)(mach_absolute_time() - g_time_start)) * g_time_scale;
+ now.tv_sec = (int64_t)(now_dbl * 1e-9);
+ now.tv_nsec = (int32_t)(now_dbl - ((double)now.tv_sec) * 1e9);
+ break;
+ case GPR_CLOCK_PRECISE:
+ gpr_precise_clock_now(&now);
+ break;
+ case GPR_TIMESPAN:
+ abort();
+ }
+
// Guard the tv_nsec field in valid range for all clock types
while (GPR_UNLIKELY(now.tv_nsec >= 1e9)) {
now.tv_sec++;
@@ -137,19 +137,19 @@ static gpr_timespec now_impl(gpr_clock_type clock) {
now.tv_nsec += 1e9;
}
- return now;
-}
-#endif
-
-gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl;
-
-#ifdef GPR_LOW_LEVEL_COUNTERS
-gpr_atm gpr_now_call_count;
-#endif
-gpr_timespec gpr_now(gpr_clock_type clock_type) {
-#ifdef GPR_LOW_LEVEL_COUNTERS
- __atomic_fetch_add(&gpr_now_call_count, 1, __ATOMIC_RELAXED);
-#endif
+ return now;
+}
+#endif
+
+gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl;
+
+#ifdef GPR_LOW_LEVEL_COUNTERS
+gpr_atm gpr_now_call_count;
+#endif
+gpr_timespec gpr_now(gpr_clock_type clock_type) {
+#ifdef GPR_LOW_LEVEL_COUNTERS
+ __atomic_fetch_add(&gpr_now_call_count, 1, __ATOMIC_RELAXED);
+#endif
// validate clock type
GPR_ASSERT(clock_type == GPR_CLOCK_MONOTONIC ||
clock_type == GPR_CLOCK_REALTIME ||
@@ -158,29 +158,29 @@ gpr_timespec gpr_now(gpr_clock_type clock_type) {
// tv_nsecs must be in the range [0, 1e9).
GPR_ASSERT(ts.tv_nsec >= 0 && ts.tv_nsec < 1e9);
return ts;
-}
-
-void gpr_sleep_until(gpr_timespec until) {
- gpr_timespec now;
- gpr_timespec delta;
- struct timespec delta_ts;
- int ns_result;
-
- for (;;) {
- /* We could simplify by using clock_nanosleep instead, but it might be
- * slightly less portable. */
- now = gpr_now(until.clock_type);
- if (gpr_time_cmp(until, now) <= 0) {
- return;
- }
-
- delta = gpr_time_sub(until, now);
- delta_ts = timespec_from_gpr(delta);
- ns_result = nanosleep(&delta_ts, nullptr);
- if (ns_result == 0) {
- break;
- }
- }
-}
-
-#endif /* GPR_POSIX_TIME */
+}
+
+void gpr_sleep_until(gpr_timespec until) {
+ gpr_timespec now;
+ gpr_timespec delta;
+ struct timespec delta_ts;
+ int ns_result;
+
+ for (;;) {
+ /* We could simplify by using clock_nanosleep instead, but it might be
+ * slightly less portable. */
+ now = gpr_now(until.clock_type);
+ if (gpr_time_cmp(until, now) <= 0) {
+ return;
+ }
+
+ delta = gpr_time_sub(until, now);
+ delta_ts = timespec_from_gpr(delta);
+ ns_result = nanosleep(&delta_ts, nullptr);
+ if (ns_result == 0) {
+ break;
+ }
+ }
+}
+
+#endif /* GPR_POSIX_TIME */
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 4d1b64b8b26..8e5262c3c19 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time_precise.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/time_precise.cc
@@ -1,23 +1,23 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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>
+
#if GPR_LINUX
#include <fcntl.h>
#include <unistd.h>
@@ -26,11 +26,11 @@
#include <algorithm>
#include <grpc/impl/codegen/gpr_types.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/gpr/time_precise.h"
-
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/gpr/time_precise.h"
+
#ifndef GPR_CYCLE_COUNTER_CUSTOM
#if GPR_CYCLE_COUNTER_RDTSC_32 || GPR_CYCLE_COUNTER_RDTSC_64
#if GPR_LINUX
@@ -53,9 +53,9 @@ static bool read_freq_from_kernel(double* freq) {
}
close(fd);
return ret;
-}
+}
#endif /* GPR_LINUX */
-
+
static double cycles_per_second = 0;
static gpr_cycle_counter start_cycle;
@@ -69,10 +69,10 @@ static bool is_fake_clock() {
}
// 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");
+}
+
+void gpr_precise_clock_init(void) {
+ gpr_log(GPR_DEBUG, "Calibrating timers");
#if GPR_LINUX
if (read_freq_from_kernel(&cycles_per_second)) {
@@ -110,9 +110,9 @@ void gpr_precise_clock_init(void) {
last_freq = freq;
}
cycles_per_second = last_freq;
- gpr_log(GPR_DEBUG, "... cycles_per_second = %f\n", cycles_per_second);
-}
-
+ 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;
@@ -134,13 +134,13 @@ gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
return ts;
}
-void gpr_precise_clock_now(gpr_timespec* clk) {
+void gpr_precise_clock_now(gpr_timespec* clk) {
int64_t counter = gpr_get_cycle_counter();
*clk = gpr_cycle_counter_to_time(counter);
-}
+}
#elif GPR_CYCLE_COUNTER_FALLBACK
-void gpr_precise_clock_init(void) {}
-
+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);
@@ -154,10 +154,10 @@ gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
return ts;
}
-void gpr_precise_clock_now(gpr_timespec* clk) {
- *clk = gpr_now(GPR_CLOCK_REALTIME);
- clk->clock_type = GPR_CLOCK_PRECISE;
-}
+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),
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 1dcfa3b57e6..696c3ec739e 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time_precise.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/time_precise.h
@@ -1,29 +1,29 @@
-/*
- *
- * 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_GPR_TIME_PRECISE_H
-#define GRPC_CORE_LIB_GPR_TIME_PRECISE_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_GPR_TIME_PRECISE_H
+#define GRPC_CORE_LIB_GPR_TIME_PRECISE_H
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/gpr_types.h>
-#include <grpc/support/time.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.
@@ -62,9 +62,9 @@ gpr_cycle_counter gpr_get_cycle_counter();
GPR_CYCLE_COUNTER_FALLBACK
#endif
-void gpr_precise_clock_init(void);
-void gpr_precise_clock_now(gpr_timespec* clk);
+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);
-
-#endif /* GRPC_CORE_LIB_GPR_TIME_PRECISE_H */
+
+#endif /* GRPC_CORE_LIB_GPR_TIME_PRECISE_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/time_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/time_windows.cc
index 247cc164682..037a58d09ad 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/time_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/time_windows.cc
@@ -1,98 +1,98 @@
-/*
- *
- * 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.
- *
- */
-
-/* Win32 code for gpr time support. */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS_TIME
-
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-#include <limits.h>
-#include <process.h>
-#include <sys/timeb.h>
-
-#include "src/core/lib/gpr/time_precise.h"
-
-static LARGE_INTEGER g_start_time;
-static double g_time_scale;
-
-void gpr_time_init(void) {
- LARGE_INTEGER frequency;
- QueryPerformanceFrequency(&frequency);
- QueryPerformanceCounter(&g_start_time);
- g_time_scale = 1.0 / (double)frequency.QuadPart;
-}
-
-static gpr_timespec now_impl(gpr_clock_type clock) {
- gpr_timespec now_tv;
- LONGLONG diff;
- struct _timeb now_tb;
- LARGE_INTEGER timestamp;
- double now_dbl;
- now_tv.clock_type = clock;
- switch (clock) {
- case GPR_CLOCK_REALTIME:
- _ftime_s(&now_tb);
- now_tv.tv_sec = (int64_t)now_tb.time;
- now_tv.tv_nsec = now_tb.millitm * 1000000;
- break;
- case GPR_CLOCK_MONOTONIC:
- case GPR_CLOCK_PRECISE:
- QueryPerformanceCounter(&timestamp);
- diff = timestamp.QuadPart - g_start_time.QuadPart;
- now_dbl = (double)diff * g_time_scale;
- now_tv.tv_sec = (int64_t)now_dbl;
- now_tv.tv_nsec = (int32_t)((now_dbl - (double)now_tv.tv_sec) * 1e9);
- break;
- case GPR_TIMESPAN:
- abort();
- break;
- }
- return now_tv;
-}
-
-gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl;
-
-gpr_timespec gpr_now(gpr_clock_type clock_type) {
- return gpr_now_impl(clock_type);
-}
-
-void gpr_sleep_until(gpr_timespec until) {
- gpr_timespec now;
- gpr_timespec delta;
- int64_t sleep_millis;
-
- for (;;) {
- /* We could simplify by using clock_nanosleep instead, but it might be
- * slightly less portable. */
- now = gpr_now(until.clock_type);
- if (gpr_time_cmp(until, now) <= 0) {
- return;
- }
-
- delta = gpr_time_sub(until, now);
- sleep_millis =
- delta.tv_sec * GPR_MS_PER_SEC + delta.tv_nsec / GPR_NS_PER_MS;
- GPR_ASSERT((sleep_millis >= 0) && (sleep_millis <= INT_MAX));
- Sleep((DWORD)sleep_millis);
- }
-}
-
-#endif /* GPR_WINDOWS_TIME */
+/*
+ *
+ * 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.
+ *
+ */
+
+/* Win32 code for gpr time support. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WINDOWS_TIME
+
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <limits.h>
+#include <process.h>
+#include <sys/timeb.h>
+
+#include "src/core/lib/gpr/time_precise.h"
+
+static LARGE_INTEGER g_start_time;
+static double g_time_scale;
+
+void gpr_time_init(void) {
+ LARGE_INTEGER frequency;
+ QueryPerformanceFrequency(&frequency);
+ QueryPerformanceCounter(&g_start_time);
+ g_time_scale = 1.0 / (double)frequency.QuadPart;
+}
+
+static gpr_timespec now_impl(gpr_clock_type clock) {
+ gpr_timespec now_tv;
+ LONGLONG diff;
+ struct _timeb now_tb;
+ LARGE_INTEGER timestamp;
+ double now_dbl;
+ now_tv.clock_type = clock;
+ switch (clock) {
+ case GPR_CLOCK_REALTIME:
+ _ftime_s(&now_tb);
+ now_tv.tv_sec = (int64_t)now_tb.time;
+ now_tv.tv_nsec = now_tb.millitm * 1000000;
+ break;
+ case GPR_CLOCK_MONOTONIC:
+ case GPR_CLOCK_PRECISE:
+ QueryPerformanceCounter(&timestamp);
+ diff = timestamp.QuadPart - g_start_time.QuadPart;
+ now_dbl = (double)diff * g_time_scale;
+ now_tv.tv_sec = (int64_t)now_dbl;
+ now_tv.tv_nsec = (int32_t)((now_dbl - (double)now_tv.tv_sec) * 1e9);
+ break;
+ case GPR_TIMESPAN:
+ abort();
+ break;
+ }
+ return now_tv;
+}
+
+gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl;
+
+gpr_timespec gpr_now(gpr_clock_type clock_type) {
+ return gpr_now_impl(clock_type);
+}
+
+void gpr_sleep_until(gpr_timespec until) {
+ gpr_timespec now;
+ gpr_timespec delta;
+ int64_t sleep_millis;
+
+ for (;;) {
+ /* We could simplify by using clock_nanosleep instead, but it might be
+ * slightly less portable. */
+ now = gpr_now(until.clock_type);
+ if (gpr_time_cmp(until, now) <= 0) {
+ return;
+ }
+
+ delta = gpr_time_sub(until, now);
+ sleep_millis =
+ delta.tv_sec * GPR_MS_PER_SEC + delta.tv_nsec / GPR_NS_PER_MS;
+ GPR_ASSERT((sleep_millis >= 0) && (sleep_millis <= INT_MAX));
+ Sleep((DWORD)sleep_millis);
+ }
+}
+
+#endif /* GPR_WINDOWS_TIME */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tls.h b/contrib/libs/grpc/src/core/lib/gpr/tls.h
index aee8f4d941d..91d0163daf9 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tls.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/tls.h
@@ -1,68 +1,68 @@
-/*
- *
- * 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_GPR_TLS_H
-#define GRPC_CORE_LIB_GPR_TLS_H
-
-#include <grpc/support/port_platform.h>
-
-/** Thread local storage.
-
- A minimal wrapper that should be implementable across many compilers,
- and implementable efficiently across most modern compilers.
-
- Thread locals have type intptr_t.
-
- Declaring a thread local variable 'foo':
- GPR_TLS_DECL(foo);
- Thread locals always have static scope.
-
- Declaring a thread local class variable 'foo':
- GPR_TLS_CLASS_DECL(foo);
-
- Defining the thread local class variable:
- GPR_TLS_CLASS_DEF(foo);
-
- Initializing a thread local (must be done at library initialization
- time):
- gpr_tls_init(&foo);
-
- Destroying a thread local:
- gpr_tls_destroy(&foo);
-
- Setting a thread local (returns new_value):
- gpr_tls_set(&foo, new_value);
-
- Accessing a thread local:
- current_value = gpr_tls_get(&foo);
-
- ALL functions here may be implemented as macros. */
-
-#ifdef GPR_GCC_TLS
-#include "src/core/lib/gpr/tls_gcc.h"
-#endif
-
-#ifdef GPR_MSVC_TLS
-#include "src/core/lib/gpr/tls_msvc.h"
-#endif
-
-#ifdef GPR_PTHREAD_TLS
-#include "src/core/lib/gpr/tls_pthread.h"
-#endif
-
-#endif /* GRPC_CORE_LIB_GPR_TLS_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_GPR_TLS_H
+#define GRPC_CORE_LIB_GPR_TLS_H
+
+#include <grpc/support/port_platform.h>
+
+/** Thread local storage.
+
+ A minimal wrapper that should be implementable across many compilers,
+ and implementable efficiently across most modern compilers.
+
+ Thread locals have type intptr_t.
+
+ Declaring a thread local variable 'foo':
+ GPR_TLS_DECL(foo);
+ Thread locals always have static scope.
+
+ Declaring a thread local class variable 'foo':
+ GPR_TLS_CLASS_DECL(foo);
+
+ Defining the thread local class variable:
+ GPR_TLS_CLASS_DEF(foo);
+
+ Initializing a thread local (must be done at library initialization
+ time):
+ gpr_tls_init(&foo);
+
+ Destroying a thread local:
+ gpr_tls_destroy(&foo);
+
+ Setting a thread local (returns new_value):
+ gpr_tls_set(&foo, new_value);
+
+ Accessing a thread local:
+ current_value = gpr_tls_get(&foo);
+
+ ALL functions here may be implemented as macros. */
+
+#ifdef GPR_GCC_TLS
+#include "src/core/lib/gpr/tls_gcc.h"
+#endif
+
+#ifdef GPR_MSVC_TLS
+#include "src/core/lib/gpr/tls_msvc.h"
+#endif
+
+#ifdef GPR_PTHREAD_TLS
+#include "src/core/lib/gpr/tls_pthread.h"
+#endif
+
+#endif /* GRPC_CORE_LIB_GPR_TLS_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tls_gcc.h b/contrib/libs/grpc/src/core/lib/gpr/tls_gcc.h
index 72b360b0211..824082cd4fb 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tls_gcc.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/tls_gcc.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPR_TLS_GCC_H
-#define GRPC_CORE_LIB_GPR_TLS_GCC_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include <grpc/support/log.h>
-
-/** Thread local storage based on gcc compiler primitives.
- #include tls.h to use this - and see that file for documentation */
-
-struct gpr_gcc_thread_local {
- intptr_t value;
-};
-
-#define GPR_TLS_DECL(name) \
- static __thread struct gpr_gcc_thread_local name = {0}
-
-#define GPR_TLS_CLASS_DECL(name) \
- static __thread struct gpr_gcc_thread_local name
-
-#define GPR_TLS_CLASS_DEF(name) __thread struct gpr_gcc_thread_local name = {0}
-
-#define gpr_tls_init(tls) \
- do { \
- } while (0)
-#define gpr_tls_destroy(tls) \
- do { \
- } while (0)
-#define gpr_tls_set(tls, new_value) (((tls)->value) = (new_value))
-#define gpr_tls_get(tls) ((tls)->value)
-
-#endif /* GRPC_CORE_LIB_GPR_TLS_GCC_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_GPR_TLS_GCC_H
+#define GRPC_CORE_LIB_GPR_TLS_GCC_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include <grpc/support/log.h>
+
+/** Thread local storage based on gcc compiler primitives.
+ #include tls.h to use this - and see that file for documentation */
+
+struct gpr_gcc_thread_local {
+ intptr_t value;
+};
+
+#define GPR_TLS_DECL(name) \
+ static __thread struct gpr_gcc_thread_local name = {0}
+
+#define GPR_TLS_CLASS_DECL(name) \
+ static __thread struct gpr_gcc_thread_local name
+
+#define GPR_TLS_CLASS_DEF(name) __thread struct gpr_gcc_thread_local name = {0}
+
+#define gpr_tls_init(tls) \
+ do { \
+ } while (0)
+#define gpr_tls_destroy(tls) \
+ do { \
+ } while (0)
+#define gpr_tls_set(tls, new_value) (((tls)->value) = (new_value))
+#define gpr_tls_get(tls) ((tls)->value)
+
+#endif /* GRPC_CORE_LIB_GPR_TLS_GCC_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tls_msvc.h b/contrib/libs/grpc/src/core/lib/gpr/tls_msvc.h
index f4b3f0f50f6..95a0fd525be 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tls_msvc.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/tls_msvc.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPR_TLS_MSVC_H
-#define GRPC_CORE_LIB_GPR_TLS_MSVC_H
-
-/** Thread local storage based on ms visual c compiler primitives.
-#include <grpc/support/port_platform.h>
-
- #include tls.h to use this - and see that file for documentation */
-
-struct gpr_msvc_thread_local {
- intptr_t value;
-};
-
-/** Use GPR_TLS_DECL to declare tls static variables outside a class */
-#define GPR_TLS_DECL(name) \
- static __declspec(thread) struct gpr_msvc_thread_local name = {0}
-
-/** Use GPR_TLS_CLASS_DECL to declare tls static variable members of a class.
- * GPR_TLS_CLASS_DEF needs to be called to define this member. */
-#define GPR_TLS_CLASS_DECL(name) \
- static __declspec(thread) struct gpr_msvc_thread_local name
-
-#define GPR_TLS_CLASS_DEF(name) \
- __declspec(thread) struct gpr_msvc_thread_local name = {0}
-
-#define gpr_tls_init(tls) \
- do { \
- } while (0)
-#define gpr_tls_destroy(tls) \
- do { \
- } while (0)
-#define gpr_tls_set(tls, new_value) (((tls)->value) = (new_value))
-#define gpr_tls_get(tls) ((tls)->value)
-
-#endif /* GRPC_CORE_LIB_GPR_TLS_MSVC_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_GPR_TLS_MSVC_H
+#define GRPC_CORE_LIB_GPR_TLS_MSVC_H
+
+/** Thread local storage based on ms visual c compiler primitives.
+#include <grpc/support/port_platform.h>
+
+ #include tls.h to use this - and see that file for documentation */
+
+struct gpr_msvc_thread_local {
+ intptr_t value;
+};
+
+/** Use GPR_TLS_DECL to declare tls static variables outside a class */
+#define GPR_TLS_DECL(name) \
+ static __declspec(thread) struct gpr_msvc_thread_local name = {0}
+
+/** Use GPR_TLS_CLASS_DECL to declare tls static variable members of a class.
+ * GPR_TLS_CLASS_DEF needs to be called to define this member. */
+#define GPR_TLS_CLASS_DECL(name) \
+ static __declspec(thread) struct gpr_msvc_thread_local name
+
+#define GPR_TLS_CLASS_DEF(name) \
+ __declspec(thread) struct gpr_msvc_thread_local name = {0}
+
+#define gpr_tls_init(tls) \
+ do { \
+ } while (0)
+#define gpr_tls_destroy(tls) \
+ do { \
+ } while (0)
+#define gpr_tls_set(tls, new_value) (((tls)->value) = (new_value))
+#define gpr_tls_get(tls) ((tls)->value)
+
+#endif /* GRPC_CORE_LIB_GPR_TLS_MSVC_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.cc b/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.cc
index 2e5b306909b..6bdd659579a 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_PTHREAD_TLS
-
-#include "src/core/lib/gpr/tls.h"
-
-intptr_t gpr_tls_set(struct gpr_pthread_thread_local* tls, intptr_t value) {
- GPR_ASSERT(0 == pthread_setspecific(tls->key, (void*)value));
- return value;
-}
-
-#endif /* GPR_PTHREAD_TLS */
+/*
+ *
+ * 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_PTHREAD_TLS
+
+#include "src/core/lib/gpr/tls.h"
+
+intptr_t gpr_tls_set(struct gpr_pthread_thread_local* tls, intptr_t value) {
+ GPR_ASSERT(0 == pthread_setspecific(tls->key, (void*)value));
+ return value;
+}
+
+#endif /* GPR_PTHREAD_TLS */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.h b/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.h
index a15f2f33897..b95c6bf0554 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/tls_pthread.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_GPR_TLS_PTHREAD_H
-#define GRPC_CORE_LIB_GPR_TLS_PTHREAD_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/log.h> /* for GPR_ASSERT */
-#include <pthread.h>
-
-/** Thread local storage based on pthread library calls.
- #include tls.h to use this - and see that file for documentation */
-
-struct gpr_pthread_thread_local {
- pthread_key_t key;
-};
-
-/** Use GPR_TLS_DECL to declare tls static variables outside a class */
-#define GPR_TLS_DECL(name) static struct gpr_pthread_thread_local name = {0}
-
-/** Use GPR_TLS_CLASS_DECL to declare tls static variable members of a class.
- * GPR_TLS_CLASS_DEF needs to be called to define this member. */
-#define GPR_TLS_CLASS_DECL(name) static struct gpr_pthread_thread_local name
-
-/** Use GPR_TLS_CLASS_DEF to declare tls static variable members of a class.
- * GPR_TLS_CLASS_DEF needs to be called to define this member. */
-#define GPR_TLS_CLASS_DEF(name) struct gpr_pthread_thread_local name = {0}
-
-#define gpr_tls_init(tls) GPR_ASSERT(0 == pthread_key_create(&(tls)->key, NULL))
-#define gpr_tls_destroy(tls) pthread_key_delete((tls)->key)
-#define gpr_tls_get(tls) ((intptr_t)pthread_getspecific((tls)->key))
-#ifdef __cplusplus
-extern "C" {
-#endif
-intptr_t gpr_tls_set(struct gpr_pthread_thread_local* tls, intptr_t value);
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* GRPC_CORE_LIB_GPR_TLS_PTHREAD_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_GPR_TLS_PTHREAD_H
+#define GRPC_CORE_LIB_GPR_TLS_PTHREAD_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/log.h> /* for GPR_ASSERT */
+#include <pthread.h>
+
+/** Thread local storage based on pthread library calls.
+ #include tls.h to use this - and see that file for documentation */
+
+struct gpr_pthread_thread_local {
+ pthread_key_t key;
+};
+
+/** Use GPR_TLS_DECL to declare tls static variables outside a class */
+#define GPR_TLS_DECL(name) static struct gpr_pthread_thread_local name = {0}
+
+/** Use GPR_TLS_CLASS_DECL to declare tls static variable members of a class.
+ * GPR_TLS_CLASS_DEF needs to be called to define this member. */
+#define GPR_TLS_CLASS_DECL(name) static struct gpr_pthread_thread_local name
+
+/** Use GPR_TLS_CLASS_DEF to declare tls static variable members of a class.
+ * GPR_TLS_CLASS_DEF needs to be called to define this member. */
+#define GPR_TLS_CLASS_DEF(name) struct gpr_pthread_thread_local name = {0}
+
+#define gpr_tls_init(tls) GPR_ASSERT(0 == pthread_key_create(&(tls)->key, NULL))
+#define gpr_tls_destroy(tls) pthread_key_delete((tls)->key)
+#define gpr_tls_get(tls) ((intptr_t)pthread_getspecific((tls)->key))
+#ifdef __cplusplus
+extern "C" {
+#endif
+intptr_t gpr_tls_set(struct gpr_pthread_thread_local* tls, intptr_t value);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GRPC_CORE_LIB_GPR_TLS_PTHREAD_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tmpfile.h b/contrib/libs/grpc/src/core/lib/gpr/tmpfile.h
index 3ce3ff5e5d2..b486e255206 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tmpfile.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/tmpfile.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_CORE_LIB_GPR_TMPFILE_H
-#define GRPC_CORE_LIB_GPR_TMPFILE_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdio.h>
-
-/* Creates a temporary file from a prefix.
- If tmp_filename is not NULL, *tmp_filename is assigned the name of the
- created file and it is the responsibility of the caller to gpr_free it
- unless an error occurs in which case it will be set to NULL. */
-FILE* gpr_tmpfile(const char* prefix, char** tmp_filename);
-
-#endif /* GRPC_CORE_LIB_GPR_TMPFILE_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_GPR_TMPFILE_H
+#define GRPC_CORE_LIB_GPR_TMPFILE_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdio.h>
+
+/* Creates a temporary file from a prefix.
+ If tmp_filename is not NULL, *tmp_filename is assigned the name of the
+ created file and it is the responsibility of the caller to gpr_free it
+ unless an error occurs in which case it will be set to NULL. */
+FILE* gpr_tmpfile(const char* prefix, char** tmp_filename);
+
+#endif /* GRPC_CORE_LIB_GPR_TMPFILE_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tmpfile_msys.cc b/contrib/libs/grpc/src/core/lib/gpr/tmpfile_msys.cc
index 76cd886f3a0..4c2103c6952 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tmpfile_msys.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/tmpfile_msys.cc
@@ -1,58 +1,58 @@
-/*
- *
- * 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_MSYS_TMPFILE
-
-#include <io.h>
-#include <stdio.h>
-#include <string.h>
-#include <tchar.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string_windows.h"
-#include "src/core/lib/gpr/tmpfile.h"
-
-FILE* gpr_tmpfile(const char* prefix, char** tmp_filename_out) {
- FILE* result = NULL;
- char tmp_filename[MAX_PATH];
- UINT success;
-
- if (tmp_filename_out != NULL) *tmp_filename_out = NULL;
-
- /* Generate a unique filename with our template + temporary path. */
- success = GetTempFileNameA(".", prefix, 0, tmp_filename);
- fprintf(stderr, "success = %d\n", success);
-
- if (success) {
- /* Open a file there. */
- result = fopen(tmp_filename, "wb+");
- fprintf(stderr, "result = %p\n", result);
- }
- if (result != NULL && tmp_filename_out) {
- *tmp_filename_out = gpr_strdup(tmp_filename);
- }
-
- return result;
-}
-
-#endif /* GPR_MSYS_TMPFILE */
+/*
+ *
+ * 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_MSYS_TMPFILE
+
+#include <io.h>
+#include <stdio.h>
+#include <string.h>
+#include <tchar.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string_windows.h"
+#include "src/core/lib/gpr/tmpfile.h"
+
+FILE* gpr_tmpfile(const char* prefix, char** tmp_filename_out) {
+ FILE* result = NULL;
+ char tmp_filename[MAX_PATH];
+ UINT success;
+
+ if (tmp_filename_out != NULL) *tmp_filename_out = NULL;
+
+ /* Generate a unique filename with our template + temporary path. */
+ success = GetTempFileNameA(".", prefix, 0, tmp_filename);
+ fprintf(stderr, "success = %d\n", success);
+
+ if (success) {
+ /* Open a file there. */
+ result = fopen(tmp_filename, "wb+");
+ fprintf(stderr, "result = %p\n", result);
+ }
+ if (result != NULL && tmp_filename_out) {
+ *tmp_filename_out = gpr_strdup(tmp_filename);
+ }
+
+ return result;
+}
+
+#endif /* GPR_MSYS_TMPFILE */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tmpfile_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/tmpfile_posix.cc
index ffdad335d67..b1e7c5e959f 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tmpfile_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/tmpfile_posix.cc
@@ -1,70 +1,70 @@
-/*
- *
- * 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_TMPFILE
-
-#include "src/core/lib/gpr/tmpfile.h"
-
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string.h"
-
-FILE* gpr_tmpfile(const char* prefix, char** tmp_filename) {
- FILE* result = nullptr;
- char* filename_template;
- int fd;
-
- if (tmp_filename != nullptr) *tmp_filename = nullptr;
-
- gpr_asprintf(&filename_template, "/tmp/%s_XXXXXX", prefix);
- GPR_ASSERT(filename_template != nullptr);
-
- fd = mkstemp(filename_template);
- if (fd == -1) {
- gpr_log(GPR_ERROR, "mkstemp failed for filename_template %s with error %s.",
- filename_template, strerror(errno));
- goto end;
- }
- result = fdopen(fd, "w+");
- if (result == nullptr) {
- gpr_log(GPR_ERROR, "Could not open file %s from fd %d (error = %s).",
- filename_template, fd, strerror(errno));
- unlink(filename_template);
- close(fd);
- goto end;
- }
-
-end:
- if (result != nullptr && tmp_filename != nullptr) {
- *tmp_filename = filename_template;
- } else {
- gpr_free(filename_template);
- }
- return result;
-}
-
-#endif /* GPR_POSIX_TMPFILE */
+/*
+ *
+ * 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_TMPFILE
+
+#include "src/core/lib/gpr/tmpfile.h"
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string.h"
+
+FILE* gpr_tmpfile(const char* prefix, char** tmp_filename) {
+ FILE* result = nullptr;
+ char* filename_template;
+ int fd;
+
+ if (tmp_filename != nullptr) *tmp_filename = nullptr;
+
+ gpr_asprintf(&filename_template, "/tmp/%s_XXXXXX", prefix);
+ GPR_ASSERT(filename_template != nullptr);
+
+ fd = mkstemp(filename_template);
+ if (fd == -1) {
+ gpr_log(GPR_ERROR, "mkstemp failed for filename_template %s with error %s.",
+ filename_template, strerror(errno));
+ goto end;
+ }
+ result = fdopen(fd, "w+");
+ if (result == nullptr) {
+ gpr_log(GPR_ERROR, "Could not open file %s from fd %d (error = %s).",
+ filename_template, fd, strerror(errno));
+ unlink(filename_template);
+ close(fd);
+ goto end;
+ }
+
+end:
+ if (result != nullptr && tmp_filename != nullptr) {
+ *tmp_filename = filename_template;
+ } else {
+ gpr_free(filename_template);
+ }
+ return result;
+}
+
+#endif /* GPR_POSIX_TMPFILE */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/tmpfile_windows.cc b/contrib/libs/grpc/src/core/lib/gpr/tmpfile_windows.cc
index d4868084189..e195439add3 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/tmpfile_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/tmpfile_windows.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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS_TMPFILE
-
-#include <io.h>
-#include <stdio.h>
-#include <string.h>
-#include <tchar.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/string_windows.h"
-#include "src/core/lib/gpr/tmpfile.h"
-
-FILE* gpr_tmpfile(const char* prefix, char** tmp_filename_out) {
- FILE* result = NULL;
- LPTSTR template_string = NULL;
- TCHAR tmp_path[MAX_PATH];
- TCHAR tmp_filename[MAX_PATH];
- DWORD status;
- UINT success;
-
- if (tmp_filename_out != NULL) *tmp_filename_out = NULL;
-
- /* Convert our prefix to TCHAR. */
- template_string = gpr_char_to_tchar(prefix);
- GPR_ASSERT(template_string);
-
- /* Get the path to the best temporary folder available. */
- status = GetTempPath(MAX_PATH, tmp_path);
- if (status == 0 || status > MAX_PATH) goto end;
-
- /* Generate a unique filename with our template + temporary path. */
- success = GetTempFileName(tmp_path, template_string, 0, tmp_filename);
- if (!success) goto end;
-
- /* Open a file there. */
- if (_tfopen_s(&result, tmp_filename, TEXT("wb+")) != 0) goto end;
-
-end:
- if (result && tmp_filename_out) {
- *tmp_filename_out = gpr_tchar_to_char(tmp_filename);
- }
-
- gpr_free(template_string);
- return result;
-}
-
-#endif /* GPR_WINDOWS_TMPFILE */
+/*
+ *
+ * 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_WINDOWS_TMPFILE
+
+#include <io.h>
+#include <stdio.h>
+#include <string.h>
+#include <tchar.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/string_windows.h"
+#include "src/core/lib/gpr/tmpfile.h"
+
+FILE* gpr_tmpfile(const char* prefix, char** tmp_filename_out) {
+ FILE* result = NULL;
+ LPTSTR template_string = NULL;
+ TCHAR tmp_path[MAX_PATH];
+ TCHAR tmp_filename[MAX_PATH];
+ DWORD status;
+ UINT success;
+
+ if (tmp_filename_out != NULL) *tmp_filename_out = NULL;
+
+ /* Convert our prefix to TCHAR. */
+ template_string = gpr_char_to_tchar(prefix);
+ GPR_ASSERT(template_string);
+
+ /* Get the path to the best temporary folder available. */
+ status = GetTempPath(MAX_PATH, tmp_path);
+ if (status == 0 || status > MAX_PATH) goto end;
+
+ /* Generate a unique filename with our template + temporary path. */
+ success = GetTempFileName(tmp_path, template_string, 0, tmp_filename);
+ if (!success) goto end;
+
+ /* Open a file there. */
+ if (_tfopen_s(&result, tmp_filename, TEXT("wb+")) != 0) goto end;
+
+end:
+ if (result && tmp_filename_out) {
+ *tmp_filename_out = gpr_tchar_to_char(tmp_filename);
+ }
+
+ gpr_free(template_string);
+ return result;
+}
+
+#endif /* GPR_WINDOWS_TMPFILE */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/useful.h b/contrib/libs/grpc/src/core/lib/gpr/useful.h
index a4e73b9a613..af52c9408be 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/useful.h
+++ b/contrib/libs/grpc/src/core/lib/gpr/useful.h
@@ -1,65 +1,65 @@
-/*
- *
- * 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_GPR_USEFUL_H
-#define GRPC_CORE_LIB_GPR_USEFUL_H
-
-/** useful macros that don't belong anywhere else */
-
-#define GPR_MIN(a, b) ((a) < (b) ? (a) : (b))
-#define GPR_MAX(a, b) ((a) > (b) ? (a) : (b))
-#define GPR_CLAMP(a, min, max) ((a) < (min) ? (min) : (a) > (max) ? (max) : (a))
-/** rotl, rotr assume x is unsigned */
-#define GPR_ROTL(x, n) (((x) << (n)) | ((x) >> (sizeof(x) * 8 - (n))))
-#define GPR_ROTR(x, n) (((x) >> (n)) | ((x) << (sizeof(x) * 8 - (n))))
-
-#define GPR_ARRAY_SIZE(array) (sizeof(array) / sizeof(*(array)))
-
-#define GPR_SWAP(type, a, b) \
- do { \
- type x = a; \
- a = b; \
- b = x; \
- } while (0)
-
-/** Set the \a n-th bit of \a i (a mutable pointer). */
-#define GPR_BITSET(i, n) ((*(i)) |= (1u << (n)))
-
-/** Clear the \a n-th bit of \a i (a mutable pointer). */
-#define GPR_BITCLEAR(i, n) ((*(i)) &= ~(1u << (n)))
-
-/** Get the \a n-th bit of \a i */
-#define GPR_BITGET(i, n) (((i) & (1u << (n))) != 0)
-
-#define GPR_INTERNAL_HEXDIGIT_BITCOUNT(x) \
- ((x) - (((x) >> 1) & 0x77777777) - (((x) >> 2) & 0x33333333) - \
- (((x) >> 3) & 0x11111111))
-
-/** Returns number of bits set in bitset \a i */
-#define GPR_BITCOUNT(i) \
- (((GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) + \
- (GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) >> 4)) & \
- 0x0f0f0f0f) % \
- 255)
-
-#define GPR_ICMP(a, b) ((a) < (b) ? -1 : ((a) > (b) ? 1 : 0))
-
-#define GPR_HASH_POINTER(x, range) \
- ((((size_t)x) >> 4) ^ (((size_t)x) >> 9) ^ (((size_t)x) >> 14)) % (range)
-
-#endif /* GRPC_CORE_LIB_GPR_USEFUL_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_GPR_USEFUL_H
+#define GRPC_CORE_LIB_GPR_USEFUL_H
+
+/** useful macros that don't belong anywhere else */
+
+#define GPR_MIN(a, b) ((a) < (b) ? (a) : (b))
+#define GPR_MAX(a, b) ((a) > (b) ? (a) : (b))
+#define GPR_CLAMP(a, min, max) ((a) < (min) ? (min) : (a) > (max) ? (max) : (a))
+/** rotl, rotr assume x is unsigned */
+#define GPR_ROTL(x, n) (((x) << (n)) | ((x) >> (sizeof(x) * 8 - (n))))
+#define GPR_ROTR(x, n) (((x) >> (n)) | ((x) << (sizeof(x) * 8 - (n))))
+
+#define GPR_ARRAY_SIZE(array) (sizeof(array) / sizeof(*(array)))
+
+#define GPR_SWAP(type, a, b) \
+ do { \
+ type x = a; \
+ a = b; \
+ b = x; \
+ } while (0)
+
+/** Set the \a n-th bit of \a i (a mutable pointer). */
+#define GPR_BITSET(i, n) ((*(i)) |= (1u << (n)))
+
+/** Clear the \a n-th bit of \a i (a mutable pointer). */
+#define GPR_BITCLEAR(i, n) ((*(i)) &= ~(1u << (n)))
+
+/** Get the \a n-th bit of \a i */
+#define GPR_BITGET(i, n) (((i) & (1u << (n))) != 0)
+
+#define GPR_INTERNAL_HEXDIGIT_BITCOUNT(x) \
+ ((x) - (((x) >> 1) & 0x77777777) - (((x) >> 2) & 0x33333333) - \
+ (((x) >> 3) & 0x11111111))
+
+/** Returns number of bits set in bitset \a i */
+#define GPR_BITCOUNT(i) \
+ (((GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) + \
+ (GPR_INTERNAL_HEXDIGIT_BITCOUNT(i) >> 4)) & \
+ 0x0f0f0f0f) % \
+ 255)
+
+#define GPR_ICMP(a, b) ((a) < (b) ? -1 : ((a) > (b) ? 1 : 0))
+
+#define GPR_HASH_POINTER(x, range) \
+ ((((size_t)x) >> 4) ^ (((size_t)x) >> 9) ^ (((size_t)x) >> 14)) % (range)
+
+#endif /* GRPC_CORE_LIB_GPR_USEFUL_H */
diff --git a/contrib/libs/grpc/src/core/lib/gpr/wrap_memcpy.cc b/contrib/libs/grpc/src/core/lib/gpr/wrap_memcpy.cc
index 9b8608e056c..480ce5fffde 100644
--- a/contrib/libs/grpc/src/core/lib/gpr/wrap_memcpy.cc
+++ b/contrib/libs/grpc/src/core/lib/gpr/wrap_memcpy.cc
@@ -1,42 +1,42 @@
-/*
- *
- * 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 <string.h>
-
-/* Provide a wrapped memcpy for targets that need to be backwards
- * compatible with older libc's.
- *
- * Enable by setting LDFLAGS=-Wl,-wrap,memcpy when linking.
- */
-
-extern "C" {
-#ifdef __linux__
-#if defined(__x86_64__) && !defined(GPR_MUSL_LIBC_COMPAT)
-__asm__(".symver memcpy,memcpy@GLIBC_2.2.5");
-void* __wrap_memcpy(void* destination, const void* source, size_t num) {
- return memcpy(destination, source, num);
-}
-#else /* !__x86_64__ */
-void* __wrap_memcpy(void* destination, const void* source, size_t num) {
- return memmove(destination, source, num);
-}
-#endif
-#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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <string.h>
+
+/* Provide a wrapped memcpy for targets that need to be backwards
+ * compatible with older libc's.
+ *
+ * Enable by setting LDFLAGS=-Wl,-wrap,memcpy when linking.
+ */
+
+extern "C" {
+#ifdef __linux__
+#if defined(__x86_64__) && !defined(GPR_MUSL_LIBC_COMPAT)
+__asm__(".symver memcpy,memcpy@GLIBC_2.2.5");
+void* __wrap_memcpy(void* destination, const void* source, size_t num) {
+ return memcpy(destination, source, num);
+}
+#else /* !__x86_64__ */
+void* __wrap_memcpy(void* destination, const void* source, size_t num) {
+ return memmove(destination, source, num);
+}
+#endif
+#endif
+}
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/README.md b/contrib/libs/grpc/src/core/lib/gprpp/README.md
index f541d22bbcd..5d5785fa7a1 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/README.md
+++ b/contrib/libs/grpc/src/core/lib/gprpp/README.md
@@ -1,12 +1,12 @@
-# GPR++ - Google Portable Runtime for C++
-
-The files in this directory contain various utility code for C++ code.
-None of this code is gRPC-specific; anything here may also be useful
-for other open source projects written in C++.
-
-Note that this is one of the few places in src/core where we allow
-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::`
+# GPR++ - Google Portable Runtime for C++
+
+The files in this directory contain various utility code for C++ code.
+None of this code is gRPC-specific; anything here may also be useful
+for other open source projects written in C++.
+
+Note that this is one of the few places in src/core where we allow
+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).
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/atomic.h b/contrib/libs/grpc/src/core/lib/gprpp/atomic.h
index 4a53d2cfa55..f5fd423dc1d 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/atomic.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/atomic.h
@@ -1,39 +1,39 @@
-/*
- *
- * 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_ATOMIC_H
-#define GRPC_CORE_LIB_GPRPP_ATOMIC_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_ATOMIC_H
+#define GRPC_CORE_LIB_GPRPP_ATOMIC_H
+
+#include <grpc/support/port_platform.h>
+
#include <atomic>
-
+
#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)
+ 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>
@@ -101,4 +101,4 @@ class Atomic {
} // namespace grpc_core
-#endif /* GRPC_CORE_LIB_GPRPP_ATOMIC_H */
+#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 a96e06e2350..78d6595fe86 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/debug_location.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/debug_location.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_DEBUG_LOCATION_H
-#define GRPC_CORE_LIB_GPRPP_DEBUG_LOCATION_H
-
-namespace grpc_core {
-
-// Used for tracking file and line where a call is made for debug builds.
-// No-op for non-debug builds.
-// Callers can use the DEBUG_LOCATION macro in either case.
-#ifndef NDEBUG
+/*
+ *
+ * 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_DEBUG_LOCATION_H
+#define GRPC_CORE_LIB_GPRPP_DEBUG_LOCATION_H
+
+namespace grpc_core {
+
+// Used for tracking file and line where a call is made for debug builds.
+// 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,
// similarly to how y_absl::SourceLocation::current() works, so that
// callers don't need to explicitly pass DEBUG_LOCATION anywhere.
-class DebugLocation {
- public:
- DebugLocation(const char* file, int line) : file_(file), line_(line) {}
- const char* file() const { return file_; }
- int line() const { return line_; }
-
- private:
- const char* file_;
- const int line_;
-};
-#define DEBUG_LOCATION ::grpc_core::DebugLocation(__FILE__, __LINE__)
-#else
-class DebugLocation {
- public:
- const char* file() const { return nullptr; }
- int line() const { return -1; }
-};
-#define DEBUG_LOCATION ::grpc_core::DebugLocation()
-#endif
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_DEBUG_LOCATION_H */
+class DebugLocation {
+ public:
+ DebugLocation(const char* file, int line) : file_(file), line_(line) {}
+ const char* file() const { return file_; }
+ int line() const { return line_; }
+
+ private:
+ const char* file_;
+ const int line_;
+};
+#define DEBUG_LOCATION ::grpc_core::DebugLocation(__FILE__, __LINE__)
+#else
+class DebugLocation {
+ public:
+ const char* file() const { return nullptr; }
+ int line() const { return -1; }
+};
+#define DEBUG_LOCATION ::grpc_core::DebugLocation()
+#endif
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_DEBUG_LOCATION_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/manual_constructor.h b/contrib/libs/grpc/src/core/lib/gprpp/manual_constructor.h
index 7f827ca8b76..041ffb9d458 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/manual_constructor.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/manual_constructor.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_GPRPP_MANUAL_CONSTRUCTOR_H
-#define GRPC_CORE_LIB_GPRPP_MANUAL_CONSTRUCTOR_H
-
-// manually construct a region of memory with some type
-
-#include <grpc/support/port_platform.h>
-
-#include <stddef.h>
-#include <stdlib.h>
-#include <new>
-#include <type_traits>
-#include <utility>
-
-#include <grpc/support/log.h>
-
-namespace grpc_core {
-
-// this contains templated helpers needed to implement the ManualConstructors
-// in this file.
-namespace manual_ctor_impl {
-
-// is_one_of returns true it a class, Member, is present in a variadic list of
-// classes, List.
-template <class Member, class... List>
-class is_one_of;
-
-template <class Member, class... List>
-class is_one_of<Member, Member, List...> {
- public:
- static constexpr const bool value = true;
-};
-
-template <class Member, class A, class... List>
-class is_one_of<Member, A, List...> {
- public:
- static constexpr const bool value = is_one_of<Member, List...>::value;
-};
-
-template <class Member>
-class is_one_of<Member> {
- public:
- static constexpr const bool value = false;
-};
-
-// max_size_of returns sizeof(Type) for the largest type in the variadic list
-// of classes, Types.
-template <class... Types>
-class max_size_of;
-
-template <class A>
-class max_size_of<A> {
- public:
- static constexpr const size_t value = sizeof(A);
-};
-
-template <class A, class... B>
-class max_size_of<A, B...> {
- public:
- static constexpr const size_t value = sizeof(A) > max_size_of<B...>::value
- ? sizeof(A)
- : max_size_of<B...>::value;
-};
-
-// max_size_of returns alignof(Type) for the largest type in the variadic list
-// of classes, Types.
-template <class... Types>
-class max_align_of;
-
-template <class A>
-class max_align_of<A> {
- public:
- static constexpr const size_t value = alignof(A);
-};
-
-template <class A, class... B>
-class max_align_of<A, B...> {
- public:
- static constexpr const size_t value = alignof(A) > max_align_of<B...>::value
- ? alignof(A)
- : max_align_of<B...>::value;
-};
-
-} // namespace manual_ctor_impl
-
-template <class BaseType, class... DerivedTypes>
-class PolymorphicManualConstructor {
- public:
- // No constructor or destructor because one of the most useful uses of
- // this class is as part of a union, and members of a union could not have
- // constructors or destructors till C++11. And, anyway, the whole point of
- // this class is to bypass constructor and destructor.
-
- BaseType* get() { return reinterpret_cast<BaseType*>(&space_); }
- const BaseType* get() const {
- return reinterpret_cast<const BaseType*>(&space_);
- }
-
- BaseType* operator->() { return get(); }
- const BaseType* operator->() const { return get(); }
-
- BaseType& operator*() { return *get(); }
- const BaseType& operator*() const { return *get(); }
-
- template <class DerivedType>
- void Init() {
- FinishInit(new (&space_) DerivedType);
- }
-
- // Init() constructs the Type instance using the given arguments
- // (which are forwarded to Type's constructor).
- //
- // Note that Init() with no arguments performs default-initialization,
- // not zero-initialization (i.e it behaves the same as "new Type;", not
- // "new Type();"), so it will leave non-class types uninitialized.
- template <class DerivedType, typename... Ts>
- void Init(Ts&&... args) {
- FinishInit(new (&space_) DerivedType(std::forward<Ts>(args)...));
- }
-
- // Init() that is equivalent to copy and move construction.
- // Enables usage like this:
- // ManualConstructor<std::vector<int>> v;
- // v.Init({1, 2, 3});
- template <class DerivedType>
- void Init(const DerivedType& x) {
- FinishInit(new (&space_) DerivedType(x));
- }
- template <class DerivedType>
- void Init(DerivedType&& x) {
- FinishInit(new (&space_) DerivedType(std::move(x)));
- }
-
- void Destroy() { get()->~BaseType(); }
-
- private:
- template <class DerivedType>
- void FinishInit(DerivedType* p) {
- static_assert(
- manual_ctor_impl::is_one_of<DerivedType, DerivedTypes...>::value,
- "DerivedType must be one of the predeclared DerivedTypes");
- GPR_ASSERT(static_cast<BaseType*>(p) == p);
- }
-
- typename std::aligned_storage<
- grpc_core::manual_ctor_impl::max_size_of<DerivedTypes...>::value,
- grpc_core::manual_ctor_impl::max_align_of<DerivedTypes...>::value>::type
- space_;
-};
-
-template <typename Type>
-class ManualConstructor {
- public:
- // No constructor or destructor because one of the most useful uses of
- // this class is as part of a union, and members of a union could not have
- // constructors or destructors till C++11. And, anyway, the whole point of
- // this class is to bypass constructor and destructor.
-
- Type* get() { return reinterpret_cast<Type*>(&space_); }
- const Type* get() const { return reinterpret_cast<const Type*>(&space_); }
-
- Type* operator->() { return get(); }
- const Type* operator->() const { return get(); }
-
- Type& operator*() { return *get(); }
- const Type& operator*() const { return *get(); }
-
- void Init() { new (&space_) Type; }
-
- // Init() constructs the Type instance using the given arguments
- // (which are forwarded to Type's constructor).
- //
- // Note that Init() with no arguments performs default-initialization,
- // not zero-initialization (i.e it behaves the same as "new Type;", not
- // "new Type();"), so it will leave non-class types uninitialized.
- template <typename... Ts>
- void Init(Ts&&... args) {
- new (&space_) Type(std::forward<Ts>(args)...);
- }
-
- // Init() that is equivalent to copy and move construction.
- // Enables usage like this:
- // ManualConstructor<std::vector<int>> v;
- // v.Init({1, 2, 3});
- void Init(const Type& x) { new (&space_) Type(x); }
- void Init(Type&& x) { new (&space_) Type(std::move(x)); }
-
- void Destroy() { get()->~Type(); }
-
- private:
- typename std::aligned_storage<sizeof(Type), alignof(Type)>::type space_;
-};
-
-} // 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_CORE_LIB_GPRPP_MANUAL_CONSTRUCTOR_H
+#define GRPC_CORE_LIB_GPRPP_MANUAL_CONSTRUCTOR_H
+
+// manually construct a region of memory with some type
+
+#include <grpc/support/port_platform.h>
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <new>
+#include <type_traits>
+#include <utility>
+
+#include <grpc/support/log.h>
+
+namespace grpc_core {
+
+// this contains templated helpers needed to implement the ManualConstructors
+// in this file.
+namespace manual_ctor_impl {
+
+// is_one_of returns true it a class, Member, is present in a variadic list of
+// classes, List.
+template <class Member, class... List>
+class is_one_of;
+
+template <class Member, class... List>
+class is_one_of<Member, Member, List...> {
+ public:
+ static constexpr const bool value = true;
+};
+
+template <class Member, class A, class... List>
+class is_one_of<Member, A, List...> {
+ public:
+ static constexpr const bool value = is_one_of<Member, List...>::value;
+};
+
+template <class Member>
+class is_one_of<Member> {
+ public:
+ static constexpr const bool value = false;
+};
+
+// max_size_of returns sizeof(Type) for the largest type in the variadic list
+// of classes, Types.
+template <class... Types>
+class max_size_of;
+
+template <class A>
+class max_size_of<A> {
+ public:
+ static constexpr const size_t value = sizeof(A);
+};
+
+template <class A, class... B>
+class max_size_of<A, B...> {
+ public:
+ static constexpr const size_t value = sizeof(A) > max_size_of<B...>::value
+ ? sizeof(A)
+ : max_size_of<B...>::value;
+};
+
+// max_size_of returns alignof(Type) for the largest type in the variadic list
+// of classes, Types.
+template <class... Types>
+class max_align_of;
+
+template <class A>
+class max_align_of<A> {
+ public:
+ static constexpr const size_t value = alignof(A);
+};
+
+template <class A, class... B>
+class max_align_of<A, B...> {
+ public:
+ static constexpr const size_t value = alignof(A) > max_align_of<B...>::value
+ ? alignof(A)
+ : max_align_of<B...>::value;
+};
+
+} // namespace manual_ctor_impl
+
+template <class BaseType, class... DerivedTypes>
+class PolymorphicManualConstructor {
+ public:
+ // No constructor or destructor because one of the most useful uses of
+ // this class is as part of a union, and members of a union could not have
+ // constructors or destructors till C++11. And, anyway, the whole point of
+ // this class is to bypass constructor and destructor.
+
+ BaseType* get() { return reinterpret_cast<BaseType*>(&space_); }
+ const BaseType* get() const {
+ return reinterpret_cast<const BaseType*>(&space_);
+ }
+
+ BaseType* operator->() { return get(); }
+ const BaseType* operator->() const { return get(); }
+
+ BaseType& operator*() { return *get(); }
+ const BaseType& operator*() const { return *get(); }
+
+ template <class DerivedType>
+ void Init() {
+ FinishInit(new (&space_) DerivedType);
+ }
+
+ // Init() constructs the Type instance using the given arguments
+ // (which are forwarded to Type's constructor).
+ //
+ // Note that Init() with no arguments performs default-initialization,
+ // not zero-initialization (i.e it behaves the same as "new Type;", not
+ // "new Type();"), so it will leave non-class types uninitialized.
+ template <class DerivedType, typename... Ts>
+ void Init(Ts&&... args) {
+ FinishInit(new (&space_) DerivedType(std::forward<Ts>(args)...));
+ }
+
+ // Init() that is equivalent to copy and move construction.
+ // Enables usage like this:
+ // ManualConstructor<std::vector<int>> v;
+ // v.Init({1, 2, 3});
+ template <class DerivedType>
+ void Init(const DerivedType& x) {
+ FinishInit(new (&space_) DerivedType(x));
+ }
+ template <class DerivedType>
+ void Init(DerivedType&& x) {
+ FinishInit(new (&space_) DerivedType(std::move(x)));
+ }
+
+ void Destroy() { get()->~BaseType(); }
+
+ private:
+ template <class DerivedType>
+ void FinishInit(DerivedType* p) {
+ static_assert(
+ manual_ctor_impl::is_one_of<DerivedType, DerivedTypes...>::value,
+ "DerivedType must be one of the predeclared DerivedTypes");
+ GPR_ASSERT(static_cast<BaseType*>(p) == p);
+ }
+
+ typename std::aligned_storage<
+ grpc_core::manual_ctor_impl::max_size_of<DerivedTypes...>::value,
+ grpc_core::manual_ctor_impl::max_align_of<DerivedTypes...>::value>::type
+ space_;
+};
+
+template <typename Type>
+class ManualConstructor {
+ public:
+ // No constructor or destructor because one of the most useful uses of
+ // this class is as part of a union, and members of a union could not have
+ // constructors or destructors till C++11. And, anyway, the whole point of
+ // this class is to bypass constructor and destructor.
+
+ Type* get() { return reinterpret_cast<Type*>(&space_); }
+ const Type* get() const { return reinterpret_cast<const Type*>(&space_); }
+
+ Type* operator->() { return get(); }
+ const Type* operator->() const { return get(); }
+
+ Type& operator*() { return *get(); }
+ const Type& operator*() const { return *get(); }
+
+ void Init() { new (&space_) Type; }
+
+ // Init() constructs the Type instance using the given arguments
+ // (which are forwarded to Type's constructor).
+ //
+ // Note that Init() with no arguments performs default-initialization,
+ // not zero-initialization (i.e it behaves the same as "new Type;", not
+ // "new Type();"), so it will leave non-class types uninitialized.
+ template <typename... Ts>
+ void Init(Ts&&... args) {
+ new (&space_) Type(std::forward<Ts>(args)...);
+ }
+
+ // Init() that is equivalent to copy and move construction.
+ // Enables usage like this:
+ // ManualConstructor<std::vector<int>> v;
+ // v.Init({1, 2, 3});
+ void Init(const Type& x) { new (&space_) Type(x); }
+ void Init(Type&& x) { new (&space_) Type(std::move(x)); }
+
+ void Destroy() { get()->~Type(); }
+
+ private:
+ typename std::aligned_storage<sizeof(Type), alignof(Type)>::type space_;
+};
+
+} // namespace grpc_core
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/memory.h b/contrib/libs/grpc/src/core/lib/gprpp/memory.h
index becf273510f..a86142e3b91 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/memory.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/memory.h
@@ -1,51 +1,51 @@
-/*
- *
- * 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_MEMORY_H
-#define GRPC_CORE_LIB_GPRPP_MEMORY_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/alloc.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_MEMORY_H
+#define GRPC_CORE_LIB_GPRPP_MEMORY_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-
-#include <limits>
-#include <memory>
-#include <utility>
-
+
+#include <limits>
+#include <memory>
+#include <utility>
+
#include "y_absl/memory/memory.h"
-namespace grpc_core {
-
+namespace grpc_core {
+
class DefaultDeleteChar {
- public:
+ public:
void operator()(char* p) {
if (p == nullptr) return;
gpr_free(p);
}
-};
-
+};
+
// 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>;
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_MEMORY_H */
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_MEMORY_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h b/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h
index 79542de6dd1..f2d45426c84 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h
@@ -1,90 +1,90 @@
-/*
- *
- * 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_ORPHANABLE_H
-#define GRPC_CORE_LIB_GPRPP_ORPHANABLE_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include <cinttypes>
-#include <memory>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/debug_location.h"
-#include "src/core/lib/gprpp/memory.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_ORPHANABLE_H
+#define GRPC_CORE_LIB_GPRPP_ORPHANABLE_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include <cinttypes>
+#include <memory>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gprpp/debug_location.h"
+#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
-
-namespace grpc_core {
-
-// A base class for orphanable objects, which have one external owner
-// but are not necessarily destroyed immediately when the external owner
-// gives up ownership. Instead, the owner calls the object's Orphan()
-// method, and the object then takes responsibility for its own cleanup
-// and destruction.
-class Orphanable {
- public:
- // Gives up ownership of the object. The implementation must arrange
- // to eventually destroy the object without further interaction from the
- // caller.
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
+
+namespace grpc_core {
+
+// A base class for orphanable objects, which have one external owner
+// but are not necessarily destroyed immediately when the external owner
+// gives up ownership. Instead, the owner calls the object's Orphan()
+// method, and the object then takes responsibility for its own cleanup
+// and destruction.
+class Orphanable {
+ public:
+ // 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;
-
- // Not copyable or movable.
- Orphanable(const Orphanable&) = delete;
- Orphanable& operator=(const Orphanable&) = delete;
-
- protected:
- Orphanable() {}
- virtual ~Orphanable() {}
-};
-
-class OrphanableDelete {
- public:
+
+ // Not copyable or movable.
+ Orphanable(const Orphanable&) = delete;
+ Orphanable& operator=(const Orphanable&) = delete;
+
+ protected:
+ Orphanable() {}
+ virtual ~Orphanable() {}
+};
+
+class OrphanableDelete {
+ public:
template <typename T>
void operator()(T* p) {
p->Orphan();
}
-};
-
+};
+
template <typename T, typename Deleter = OrphanableDelete>
-using OrphanablePtr = std::unique_ptr<T, Deleter>;
-
-template <typename T, typename... Args>
-inline OrphanablePtr<T> MakeOrphanable(Args&&... args) {
+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)...));
-}
-
-// A type of Orphanable with internal ref-counting.
-template <typename Child>
-class InternallyRefCounted : public Orphanable {
- public:
- // Not copyable nor movable.
- InternallyRefCounted(const InternallyRefCounted&) = delete;
- InternallyRefCounted& operator=(const InternallyRefCounted&) = delete;
-
- protected:
- // Allow RefCountedPtr<> to access Unref() and IncrementRefCount().
- template <typename T>
+}
+
+// A type of Orphanable with internal ref-counting.
+template <typename Child>
+class InternallyRefCounted : public Orphanable {
+ public:
+ // Not copyable nor movable.
+ InternallyRefCounted(const InternallyRefCounted&) = delete;
+ InternallyRefCounted& operator=(const InternallyRefCounted&) = delete;
+
+ protected:
+ // Allow RefCountedPtr<> to access Unref() and IncrementRefCount().
+ template <typename T>
friend class RefCountedPtr;
-
+
// TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag.
// Note: RefCount tracing is only enabled on debug builds, even when a
// TraceFlag is used.
@@ -93,37 +93,37 @@ class InternallyRefCounted : public Orphanable {
intptr_t initial_refcount = 1)
: refs_(initial_refcount, trace_flag) {}
virtual ~InternallyRefCounted() = default;
-
- RefCountedPtr<Child> Ref() GRPC_MUST_USE_RESULT {
- IncrementRefCount();
- return RefCountedPtr<Child>(static_cast<Child*>(this));
- }
- RefCountedPtr<Child> Ref(const DebugLocation& location,
- const char* reason) GRPC_MUST_USE_RESULT {
+
+ RefCountedPtr<Child> Ref() GRPC_MUST_USE_RESULT {
+ IncrementRefCount();
+ return RefCountedPtr<Child>(static_cast<Child*>(this));
+ }
+ RefCountedPtr<Child> Ref(const DebugLocation& location,
+ const char* reason) GRPC_MUST_USE_RESULT {
IncrementRefCount(location, reason);
return RefCountedPtr<Child>(static_cast<Child*>(this));
- }
-
- void Unref() {
+ }
+
+ void Unref() {
if (GPR_UNLIKELY(refs_.Unref())) {
delete this;
- }
- }
- void Unref(const DebugLocation& location, const char* reason) {
+ }
+ }
+ void Unref(const DebugLocation& location, const char* reason) {
if (GPR_UNLIKELY(refs_.Unref(location, reason))) {
delete this;
- }
- }
-
- private:
+ }
+ }
+
+ private:
void IncrementRefCount() { refs_.Ref(); }
void IncrementRefCount(const DebugLocation& location, const char* reason) {
refs_.Ref(location, reason);
}
-
+
grpc_core::RefCount refs_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_ORPHANABLE_H */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_ORPHANABLE_H */
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 d05ff6e44c4..2a1c3859f10 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h
@@ -1,42 +1,42 @@
-/*
- *
- * 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_REF_COUNTED_H
-#define GRPC_CORE_LIB_GPRPP_REF_COUNTED_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_REF_COUNTED_H
+#define GRPC_CORE_LIB_GPRPP_REF_COUNTED_H
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
#include <atomic>
#include <cassert>
-#include <cinttypes>
-
-#include "src/core/lib/debug/trace.h"
+#include <cinttypes>
+
+#include "src/core/lib/debug/trace.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"
-
-namespace grpc_core {
-
+#include "src/core/lib/gprpp/debug_location.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
+
+namespace grpc_core {
+
// RefCount is a simple atomic ref-count.
//
// This is a C++ implementation of gpr_refcount, with inline functions. Due to
@@ -48,7 +48,7 @@ namespace grpc_core {
class RefCount {
public:
using Value = intptr_t;
-
+
// `init` is the initial refcount stored in this object.
//
// TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag.
@@ -195,15 +195,15 @@ class RefCount {
return prior == 1;
}
- private:
+ private:
Value get() const { return value_.Load(MemoryOrder::RELAXED); }
-
+
#ifndef NDEBUG
TraceFlag* trace_flag_;
#endif
Atomic<Value> value_;
-};
-
+};
+
// PolymorphicRefCount enforces polymorphic destruction of RefCounted.
class PolymorphicRefCount {
public:
@@ -269,36 +269,36 @@ class Delete<T, false> {
template <typename Child, typename Impl = PolymorphicRefCount,
bool DeleteUponUnref = true>
class RefCounted : public Impl {
- public:
+ public:
// 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));
- }
-
- RefCountedPtr<Child> Ref(const DebugLocation& location,
- const char* reason) GRPC_MUST_USE_RESULT {
+ RefCountedPtr<Child> Ref() GRPC_MUST_USE_RESULT {
+ IncrementRefCount();
+ return RefCountedPtr<Child>(static_cast<Child*>(this));
+ }
+
+ RefCountedPtr<Child> Ref(const DebugLocation& location,
+ const char* reason) GRPC_MUST_USE_RESULT {
IncrementRefCount(location, reason);
return RefCountedPtr<Child>(static_cast<Child*>(this));
- }
-
- // TODO(roth): Once all of our code is converted to C++ and can use
+ }
+
+ // TODO(roth): Once all of our code is converted to C++ and can use
// RefCountedPtr<> instead of manual ref-counting, make this method
// private, since it will only be used by RefCountedPtr<>, which is a
- // friend of this class.
- void Unref() {
+ // friend of this class.
+ void Unref() {
if (GPR_UNLIKELY(refs_.Unref())) {
internal::Delete<Child, DeleteUponUnref>(static_cast<Child*>(this));
- }
- }
- void Unref(const DebugLocation& location, const char* reason) {
+ }
+ }
+ void Unref(const DebugLocation& location, const char* reason) {
if (GPR_UNLIKELY(refs_.Unref(location, reason))) {
internal::Delete<Child, DeleteUponUnref>(static_cast<Child*>(this));
- }
- }
-
+ }
+ }
+
RefCountedPtr<Child> RefIfNonZero() GRPC_MUST_USE_RESULT {
return RefCountedPtr<Child>(refs_.RefIfNonZero() ? static_cast<Child*>(this)
: nullptr);
@@ -310,11 +310,11 @@ class RefCounted : public Impl {
: nullptr);
}
- // Not copyable nor movable.
+ // Not copyable nor movable.
RefCounted(const RefCounted&) = delete;
RefCounted& operator=(const RefCounted&) = delete;
-
- protected:
+
+ protected:
// TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag.
// Note: RefCount tracing is only enabled on debug builds, even when a
// TraceFlag is used.
@@ -322,20 +322,20 @@ class RefCounted : public Impl {
explicit RefCounted(TraceFlagT* trace_flag = nullptr,
intptr_t initial_refcount = 1)
: refs_(initial_refcount, trace_flag) {}
-
- private:
- // Allow RefCountedPtr<> to access IncrementRefCount().
+
+ private:
+ // Allow RefCountedPtr<> to access IncrementRefCount().
template <typename T>
friend class RefCountedPtr;
-
+
void IncrementRefCount() { refs_.Ref(); }
void IncrementRefCount(const DebugLocation& location, const char* reason) {
refs_.Ref(location, reason);
}
-
+
RefCount refs_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_REF_COUNTED_H */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_REF_COUNTED_H */
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 c28e7625323..b70504fb03e 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
@@ -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_REF_COUNTED_PTR_H
-#define GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H
-
-#include <grpc/support/port_platform.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H
+#define GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H
+
+#include <grpc/support/port_platform.h>
+
#include <type_traits>
-#include <utility>
-
+#include <utility>
+
#include "src/core/lib/gprpp/debug_location.h"
-#include "src/core/lib/gprpp/memory.h"
-
-namespace grpc_core {
-
-// A smart pointer class for objects that provide IncrementRefCount() and
-// Unref() methods, such as those provided by the RefCounted base class.
-template <typename T>
-class RefCountedPtr {
- public:
- RefCountedPtr() {}
- RefCountedPtr(std::nullptr_t) {}
-
- // If value is non-null, we take ownership of a ref to it.
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+
+// A smart pointer class for objects that provide IncrementRefCount() and
+// Unref() methods, such as those provided by the RefCounted base class.
+template <typename T>
+class RefCountedPtr {
+ public:
+ RefCountedPtr() {}
+ RefCountedPtr(std::nullptr_t) {}
+
+ // If value is non-null, we take ownership of a ref to it.
template <typename Y>
explicit RefCountedPtr(Y* value) {
value_ = value;
}
-
+
// Move ctors.
- RefCountedPtr(RefCountedPtr&& other) {
- value_ = other.value_;
- other.value_ = nullptr;
- }
+ RefCountedPtr(RefCountedPtr&& other) {
+ value_ = other.value_;
+ other.value_ = nullptr;
+ }
template <typename Y>
RefCountedPtr(RefCountedPtr<Y>&& other) {
value_ = static_cast<T*>(other.value_);
@@ -55,23 +55,23 @@ class RefCountedPtr {
}
// Move assignment.
- RefCountedPtr& operator=(RefCountedPtr&& other) {
+ RefCountedPtr& operator=(RefCountedPtr&& other) {
reset(other.value_);
- other.value_ = nullptr;
- return *this;
- }
+ other.value_ = nullptr;
+ return *this;
+ }
template <typename Y>
RefCountedPtr& operator=(RefCountedPtr<Y>&& other) {
reset(other.value_);
other.value_ = nullptr;
return *this;
}
-
+
// Copy ctors.
- RefCountedPtr(const RefCountedPtr& other) {
- if (other.value_ != nullptr) other.value_->IncrementRefCount();
- value_ = other.value_;
- }
+ RefCountedPtr(const RefCountedPtr& other) {
+ if (other.value_ != nullptr) other.value_->IncrementRefCount();
+ value_ = other.value_;
+ }
template <typename Y>
RefCountedPtr(const RefCountedPtr<Y>& other) {
static_assert(std::has_virtual_destructor<T>::value,
@@ -81,13 +81,13 @@ class RefCountedPtr {
}
// Copy assignment.
- RefCountedPtr& operator=(const RefCountedPtr& other) {
- // Note: Order of reffing and unreffing is important here in case value_
- // and other.value_ are the same object.
- if (other.value_ != nullptr) other.value_->IncrementRefCount();
+ RefCountedPtr& operator=(const RefCountedPtr& other) {
+ // Note: Order of reffing and unreffing is important here in case value_
+ // and other.value_ are the same object.
+ if (other.value_ != nullptr) other.value_->IncrementRefCount();
reset(other.value_);
- return *this;
- }
+ return *this;
+ }
template <typename Y>
RefCountedPtr& operator=(const RefCountedPtr<Y>& other) {
static_assert(std::has_virtual_destructor<T>::value,
@@ -98,18 +98,18 @@ class RefCountedPtr {
reset(other.value_);
return *this;
}
-
- ~RefCountedPtr() {
- if (value_ != nullptr) value_->Unref();
- }
-
+
+ ~RefCountedPtr() {
+ if (value_ != nullptr) value_->Unref();
+ }
+
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();
- value_ = value;
- }
+ // If value is non-null, we take ownership of a ref to it.
+ void reset(T* value = nullptr) {
+ if (value_ != nullptr) value_->Unref();
+ value_ = value;
+ }
void reset(const DebugLocation& location, const char* reason,
T* value = nullptr) {
if (value_ != nullptr) value_->Unref(location, reason);
@@ -130,26 +130,26 @@ class RefCountedPtr {
if (value_ != nullptr) value_->Unref(location, reason);
value_ = static_cast<T*>(value);
}
-
- // TODO(roth): This method exists solely as a transition mechanism to allow
- // us to pass a ref to idiomatic C code that does not use RefCountedPtr<>.
- // Once all of our code has been converted to idiomatic C++, this
- // method should go away.
- T* release() {
- T* value = value_;
- value_ = nullptr;
- return value;
- }
-
- T* get() const { return value_; }
-
- T& operator*() const { return *value_; }
- T* operator->() const { return value_; }
-
+
+ // TODO(roth): This method exists solely as a transition mechanism to allow
+ // us to pass a ref to idiomatic C code that does not use RefCountedPtr<>.
+ // Once all of our code has been converted to idiomatic C++, this
+ // method should go away.
+ T* release() {
+ T* value = value_;
+ value_ = nullptr;
+ return value;
+ }
+
+ T* get() const { return value_; }
+
+ T& operator*() const { return *value_; }
+ T* operator->() const { return value_; }
+
template <typename Y>
bool operator==(const RefCountedPtr<Y>& other) const {
- return value_ == other.value_;
- }
+ return value_ == other.value_;
+ }
template <typename Y>
bool operator==(const Y* other) const {
@@ -160,9 +160,9 @@ class RefCountedPtr {
template <typename Y>
bool operator!=(const RefCountedPtr<Y>& other) const {
- return value_ != other.value_;
- }
-
+ return value_ != other.value_;
+ }
+
template <typename Y>
bool operator!=(const Y* other) const {
return value_ != other;
@@ -170,13 +170,13 @@ class RefCountedPtr {
bool operator!=(std::nullptr_t) const { return value_ != nullptr; }
- private:
+ private:
template <typename Y>
friend class RefCountedPtr;
- T* value_ = nullptr;
-};
-
+ T* value_ = nullptr;
+};
+
// A smart pointer class for objects that provide IncrementWeakRefCount() and
// WeakUnref() methods, such as those provided by the DualRefCounted base class.
template <typename T>
@@ -325,11 +325,11 @@ class WeakRefCountedPtr {
T* value_ = nullptr;
};
-template <typename T, typename... Args>
-inline RefCountedPtr<T> MakeRefCounted(Args&&... args) {
+template <typename T, typename... Args>
+inline RefCountedPtr<T> MakeRefCounted(Args&&... args) {
return RefCountedPtr<T>(new T(std::forward<Args>(args)...));
-}
-
+}
+
template <typename T>
bool operator<(const RefCountedPtr<T>& p1, const RefCountedPtr<T>& p2) {
return p1.get() < p2.get();
@@ -340,6 +340,6 @@ bool operator<(const WeakRefCountedPtr<T>& p1, const WeakRefCountedPtr<T>& p2) {
return p1.get() < p2.get();
}
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H */
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_REF_COUNTED_PTR_H */
diff --git a/contrib/libs/grpc/src/core/lib/gprpp/thd.h b/contrib/libs/grpc/src/core/lib/gprpp/thd.h
index 8e50f545e25..7a3fff5dc81 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/thd.h
+++ b/contrib/libs/grpc/src/core/lib/gprpp/thd.h
@@ -1,50 +1,50 @@
-/*
- *
- * 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_THD_H
-#define GRPC_CORE_LIB_GPRPP_THD_H
-
-/** Internal thread interface. */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/thd_id.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/gprpp/memory.h"
-
-namespace grpc_core {
-namespace internal {
-
-/// Base class for platform-specific thread-state
-class ThreadInternalsInterface {
- public:
- virtual ~ThreadInternalsInterface() {}
+/*
+ *
+ * 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_THD_H
+#define GRPC_CORE_LIB_GPRPP_THD_H
+
+/** Internal thread interface. */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/thd_id.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+namespace internal {
+
+/// Base class for platform-specific thread-state
+class ThreadInternalsInterface {
+ public:
+ virtual ~ThreadInternalsInterface() {}
virtual void Start() = 0;
virtual void Join() = 0;
-};
-
-} // namespace internal
-
-class Thread {
- public:
+};
+
+} // namespace internal
+
+class Thread {
+ public:
class Options {
public:
Options() : joinable_(true), tracked_(true), stack_size_(0) {}
@@ -75,100 +75,100 @@ class Thread {
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_
- Thread() : state_(FAKE), impl_(nullptr) {}
-
- /// Normal constructor to create a thread with name \a thd_name,
- /// which will execute a thread based on function \a thd_body
- /// with argument \a arg once it is started.
- /// The optional \a success argument indicates whether the thread
- /// is successfully created.
+ /// 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_
+ Thread() : state_(FAKE), impl_(nullptr) {}
+
+ /// Normal constructor to create a thread with name \a thd_name,
+ /// which will execute a thread based on function \a thd_body
+ /// 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.
- Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
+ Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
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
+
+ /// 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_) {
- other.state_ = MOVED;
- other.impl_ = nullptr;
+ other.state_ = MOVED;
+ other.impl_ = nullptr;
other.options_ = Options();
- }
-
- /// Move assignment operator for thread. After this is called, the other
- /// thread no longer represents a living thread object. Not allowed if this
- /// thread actually exists
- Thread& operator=(Thread&& other) {
- if (this != &other) {
- // TODO(vjpai): if we can be sure that all Thread's are actually
- // constructed, then we should assert GPR_ASSERT(impl_ == nullptr) here.
- // However, as long as threads come in structures that are
- // allocated via gpr_malloc, this will not be the case, so we cannot
- // assert it for the time being.
- state_ = other.state_;
- impl_ = other.impl_;
+ }
+
+ /// Move assignment operator for thread. After this is called, the other
+ /// thread no longer represents a living thread object. Not allowed if this
+ /// thread actually exists
+ Thread& operator=(Thread&& other) {
+ if (this != &other) {
+ // TODO(vjpai): if we can be sure that all Thread's are actually
+ // constructed, then we should assert GPR_ASSERT(impl_ == nullptr) here.
+ // However, as long as threads come in structures that are
+ // allocated via gpr_malloc, this will not be the case, so we cannot
+ // assert it for the time being.
+ state_ = other.state_;
+ impl_ = other.impl_;
options_ = other.options_;
- other.state_ = MOVED;
- other.impl_ = nullptr;
+ other.state_ = MOVED;
+ other.impl_ = nullptr;
other.options_ = Options();
- }
- return *this;
- }
-
- /// The destructor is strictly optional; either the thread never came to life
+ }
+ 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); }
-
- void Start() {
- if (impl_ != nullptr) {
- GPR_ASSERT(state_ == ALIVE);
- state_ = STARTED;
- impl_->Start();
+
+ 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.
- } else {
- GPR_ASSERT(state_ == FAILED);
- }
+ } else {
+ GPR_ASSERT(state_ == FAILED);
+ }
}
-
+
// It is only legal to call Join if the Thread is created as joinable.
- void Join() {
- if (impl_ != nullptr) {
- impl_->Join();
+ void Join() {
+ if (impl_ != nullptr) {
+ impl_->Join();
delete impl_;
- state_ = DONE;
- impl_ = nullptr;
- } else {
- GPR_ASSERT(state_ == FAILED);
- }
+ state_ = DONE;
+ impl_ = nullptr;
+ } else {
+ GPR_ASSERT(state_ == FAILED);
+ }
}
-
- private:
- Thread(const Thread&) = delete;
- Thread& operator=(const Thread&) = delete;
-
- /// The thread states are as follows:
- /// FAKE -- just a dummy placeholder Thread created by the default constructor
- /// ALIVE -- an actual thread of control exists associated with this thread
- /// STARTED -- the thread of control has been started
- /// DONE -- the thread of control has completed and been joined
- /// FAILED -- the thread of control never came alive
- /// MOVED -- contents were moved out and we're no longer tracking them
- enum ThreadState { FAKE, ALIVE, STARTED, DONE, FAILED, MOVED };
- ThreadState state_;
- internal::ThreadInternalsInterface* impl_;
+
+ private:
+ Thread(const Thread&) = delete;
+ Thread& operator=(const Thread&) = delete;
+
+ /// The thread states are as follows:
+ /// FAKE -- just a dummy placeholder Thread created by the default constructor
+ /// ALIVE -- an actual thread of control exists associated with this thread
+ /// STARTED -- the thread of control has been started
+ /// DONE -- the thread of control has completed and been joined
+ /// FAILED -- the thread of control never came alive
+ /// MOVED -- contents were moved out and we're no longer tracking them
+ enum ThreadState { FAKE, ALIVE, STARTED, DONE, FAILED, MOVED };
+ ThreadState state_;
+ internal::ThreadInternalsInterface* impl_;
Options options_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_GPRPP_THD_H */
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_GPRPP_THD_H */
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 f6f6af9c26b..9f8b6766ba4 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.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.
- *
- */
-
-/* Posix implementation for gpr threads. */
-
-#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.
+ *
+ */
+
+/* Posix implementation for gpr threads. */
+
+#include <grpc/support/port_platform.h>
#include <util/system/thread.h>
-
-#ifdef GPR_POSIX_SYNC
-
-#include "src/core/lib/gprpp/thd.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/thd_id.h>
-#include <pthread.h>
-#include <stdlib.h>
-#include <string.h>
+
+#ifdef GPR_POSIX_SYNC
+
+#include "src/core/lib/gprpp/thd.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/thd_id.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
#include <unistd.h>
-
-#include "src/core/lib/gpr/useful.h"
+
+#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/fork.h"
-#include "src/core/lib/gprpp/memory.h"
-
-namespace grpc_core {
-namespace {
-class ThreadInternalsPosix;
-struct thd_arg {
- ThreadInternalsPosix* thread;
- void (*body)(void* arg); /* body of a thread */
- void* arg; /* argument to a thread */
- const char* name; /* name of thread. Can be nullptr. */
+#include "src/core/lib/gprpp/memory.h"
+
+namespace grpc_core {
+namespace {
+class ThreadInternalsPosix;
+struct thd_arg {
+ ThreadInternalsPosix* thread;
+ 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;
-};
-
+};
+
size_t RoundUpToPageSize(size_t size) {
// TODO(yunjiaw): Change this variable (page_size) to a function-level static
// when possible
@@ -71,28 +71,28 @@ size_t MinValidStackSize(size_t request_size) {
}
class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
- public:
- ThreadInternalsPosix(const char* thd_name, void (*thd_body)(void* arg),
+ public:
+ ThreadInternalsPosix(const char* thd_name, void (*thd_body)(void* arg),
void* arg, bool* success, const Thread::Options& options)
- : started_(false) {
- gpr_mu_init(&mu_);
- gpr_cv_init(&ready_);
- pthread_attr_t attr;
- /* don't use gpr_malloc as we may cause an infinite recursion with
- * the profiling code */
- thd_arg* info = static_cast<thd_arg*>(malloc(sizeof(*info)));
- GPR_ASSERT(info != nullptr);
- info->thread = this;
- info->body = thd_body;
- info->arg = arg;
- info->name = thd_name;
+ : started_(false) {
+ gpr_mu_init(&mu_);
+ gpr_cv_init(&ready_);
+ pthread_attr_t attr;
+ /* don't use gpr_malloc as we may cause an infinite recursion with
+ * the profiling code */
+ thd_arg* info = static_cast<thd_arg*>(malloc(sizeof(*info)));
+ GPR_ASSERT(info != nullptr);
+ info->thread = this;
+ info->body = thd_body;
+ info->arg = arg;
+ info->name = thd_name;
info->joinable = options.joinable();
info->tracked = options.tracked();
if (options.tracked()) {
Fork::IncThreadCount();
}
-
- GPR_ASSERT(pthread_attr_init(&attr) == 0);
+
+ GPR_ASSERT(pthread_attr_init(&attr) == 0);
if (options.joinable()) {
GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) ==
0);
@@ -100,94 +100,94 @@ class ThreadInternalsPosix : public internal::ThreadInternalsInterface {
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* {
- thd_arg arg = *static_cast<thd_arg*>(v);
- free(v);
- if (arg.name != nullptr) {
+ *success =
+ (pthread_create(&pthread_id_, &attr,
+ [](void* v) -> void* {
+ thd_arg arg = *static_cast<thd_arg*>(v);
+ free(v);
+ if (arg.name != nullptr) {
TThread::SetCurrentThreadName(arg.name);
- }
-
- gpr_mu_lock(&arg.thread->mu_);
- while (!arg.thread->started_) {
- gpr_cv_wait(&arg.thread->ready_, &arg.thread->mu_,
- gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
- gpr_mu_unlock(&arg.thread->mu_);
-
+ }
+
+ gpr_mu_lock(&arg.thread->mu_);
+ while (!arg.thread->started_) {
+ gpr_cv_wait(&arg.thread->ready_, &arg.thread->mu_,
+ gpr_inf_future(GPR_CLOCK_MONOTONIC));
+ }
+ gpr_mu_unlock(&arg.thread->mu_);
+
if (!arg.joinable) {
delete arg.thread;
}
- (*arg.body)(arg.arg);
+ (*arg.body)(arg.arg);
if (arg.tracked) {
Fork::DecThreadCount();
}
- return nullptr;
- },
- info) == 0);
-
- GPR_ASSERT(pthread_attr_destroy(&attr) == 0);
-
+ return nullptr;
+ },
+ info) == 0);
+
+ GPR_ASSERT(pthread_attr_destroy(&attr) == 0);
+
if (!(*success)) {
- /* don't use gpr_free, as this was allocated using malloc (see above) */
- free(info);
+ /* don't use gpr_free, as this was allocated using malloc (see above) */
+ free(info);
if (options.tracked()) {
Fork::DecThreadCount();
}
- }
- }
-
- ~ThreadInternalsPosix() override {
- gpr_mu_destroy(&mu_);
- gpr_cv_destroy(&ready_);
- }
-
- void Start() override {
- gpr_mu_lock(&mu_);
- started_ = true;
- gpr_cv_signal(&ready_);
- gpr_mu_unlock(&mu_);
+ }
}
-
- void Join() override { pthread_join(pthread_id_, nullptr); }
-
- private:
- gpr_mu mu_;
- gpr_cv ready_;
- bool started_;
- pthread_t pthread_id_;
-};
-
-} // namespace
-
-Thread::Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
+
+ ~ThreadInternalsPosix() override {
+ gpr_mu_destroy(&mu_);
+ gpr_cv_destroy(&ready_);
+ }
+
+ void Start() override {
+ gpr_mu_lock(&mu_);
+ started_ = true;
+ gpr_cv_signal(&ready_);
+ gpr_mu_unlock(&mu_);
+ }
+
+ void Join() override { pthread_join(pthread_id_, nullptr); }
+
+ private:
+ gpr_mu mu_;
+ gpr_cv ready_;
+ bool started_;
+ pthread_t pthread_id_;
+};
+
+} // namespace
+
+Thread::Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
bool* success, const Options& options)
: options_(options) {
- bool outcome = false;
+ bool outcome = false;
impl_ = new ThreadInternalsPosix(thd_name, thd_body, arg, &outcome, options);
- if (outcome) {
- state_ = ALIVE;
- } else {
- state_ = FAILED;
+ if (outcome) {
+ state_ = ALIVE;
+ } else {
+ state_ = FAILED;
delete impl_;
- impl_ = nullptr;
- }
-
- if (success != nullptr) {
- *success = outcome;
- }
-}
-} // namespace grpc_core
-
-// The following is in the external namespace as it is exposed as C89 API
-gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); }
-
-#endif /* GPR_POSIX_SYNC */
+ impl_ = nullptr;
+ }
+
+ if (success != nullptr) {
+ *success = outcome;
+ }
+}
+} // namespace grpc_core
+
+// The following is in the external namespace as it is exposed as C89 API
+gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); }
+
+#endif /* GPR_POSIX_SYNC */
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 bd3b7a36ebb..6de129f3aed 100644
--- a/contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/gprpp/thd_windows.cc
@@ -1,70 +1,70 @@
-/*
- *
- * 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.
- *
- */
-
-/* Windows implementation for gpr threads. */
-
-#include <grpc/support/port_platform.h>
-
-#ifdef GPR_WINDOWS
-
-#include "src/core/lib/gprpp/thd.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/thd_id.h>
-#include <string.h>
-
-#include "src/core/lib/gprpp/memory.h"
-
-#if defined(_MSC_VER)
-#define thread_local __declspec(thread)
-#elif defined(__GNUC__)
-#define thread_local __thread
-#else
-#error "Unknown compiler - please file a bug report"
-#endif
-
-namespace {
-class ThreadInternalsWindows;
-struct thd_info {
- ThreadInternalsWindows* thread;
- void (*body)(void* arg); /* body of a thread */
- void* arg; /* argument to a thread */
- HANDLE join_event; /* the join event */
+/*
+ *
+ * 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.
+ *
+ */
+
+/* Windows implementation for gpr threads. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WINDOWS
+
+#include "src/core/lib/gprpp/thd.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/thd_id.h>
+#include <string.h>
+
+#include "src/core/lib/gprpp/memory.h"
+
+#if defined(_MSC_VER)
+#define thread_local __declspec(thread)
+#elif defined(__GNUC__)
+#define thread_local __thread
+#else
+#error "Unknown compiler - please file a bug report"
+#endif
+
+namespace {
+class ThreadInternalsWindows;
+struct thd_info {
+ ThreadInternalsWindows* thread;
+ 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 */
-};
-
-thread_local struct thd_info* g_thd_info;
-
-class ThreadInternalsWindows
- : public grpc_core::internal::ThreadInternalsInterface {
- public:
+};
+
+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)
- : started_(false) {
- gpr_mu_init(&mu_);
- gpr_cv_init(&ready_);
-
- HANDLE handle;
- info_ = (struct thd_info*)gpr_malloc(sizeof(*info_));
- info_->thread = this;
- info_->body = thd_body;
- info_->arg = arg;
+ : started_(false) {
+ gpr_mu_init(&mu_);
+ gpr_cv_init(&ready_);
+
+ HANDLE handle;
+ info_ = (struct thd_info*)gpr_malloc(sizeof(*info_));
+ info_->thread = this;
+ info_->body = thd_body;
+ info_->arg = arg;
info_->join_event = nullptr;
info_->joinable = options.joinable();
if (info_->joinable) {
@@ -75,7 +75,7 @@ class ThreadInternalsWindows
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_,
@@ -86,32 +86,32 @@ class ThreadInternalsWindows
if (handle == nullptr) {
destroy_thread();
- *success = false;
- } else {
+ *success = false;
+ } else {
CloseHandle(handle);
*success = true;
- }
- }
-
- ~ThreadInternalsWindows() override {
- gpr_mu_destroy(&mu_);
- gpr_cv_destroy(&ready_);
- }
-
- void Start() override {
- gpr_mu_lock(&mu_);
- started_ = true;
- gpr_cv_signal(&ready_);
- gpr_mu_unlock(&mu_);
- }
-
- void Join() override {
- DWORD ret = WaitForSingleObject(info_->join_event, INFINITE);
- GPR_ASSERT(ret == WAIT_OBJECT_0);
- destroy_thread();
- }
-
- private:
+ }
+ }
+
+ ~ThreadInternalsWindows() override {
+ gpr_mu_destroy(&mu_);
+ gpr_cv_destroy(&ready_);
+ }
+
+ void Start() override {
+ gpr_mu_lock(&mu_);
+ started_ = true;
+ gpr_cv_signal(&ready_);
+ gpr_mu_unlock(&mu_);
+ }
+
+ void Join() override {
+ DWORD ret = WaitForSingleObject(info_->join_event, INFINITE);
+ GPR_ASSERT(ret == WAIT_OBJECT_0);
+ destroy_thread();
+ }
+
+ private:
static DWORD WINAPI thread_body(void* v) {
g_thd_info = static_cast<thd_info*>(v);
gpr_mu_lock(&g_thd_info->thread->mu_);
@@ -134,43 +134,43 @@ class ThreadInternalsWindows
return 0;
}
- void destroy_thread() {
+ void destroy_thread() {
if (info_ != nullptr && info_->joinable) {
CloseHandle(info_->join_event);
}
- gpr_free(info_);
- }
-
- gpr_mu mu_;
- gpr_cv ready_;
- bool started_;
- thd_info* info_;
-};
-
-} // namespace
-
-namespace grpc_core {
-
-Thread::Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
+ gpr_free(info_);
+ }
+
+ gpr_mu mu_;
+ gpr_cv ready_;
+ bool started_;
+ thd_info* info_;
+};
+
+} // namespace
+
+namespace grpc_core {
+
+Thread::Thread(const char* thd_name, void (*thd_body)(void* arg), void* arg,
bool* success, const Options& options)
: options_(options) {
- bool outcome = false;
+ bool outcome = false;
impl_ = new ThreadInternalsWindows(thd_body, arg, &outcome, options);
- if (outcome) {
- state_ = ALIVE;
- } else {
- state_ = FAILED;
+ if (outcome) {
+ state_ = ALIVE;
+ } else {
+ state_ = FAILED;
delete impl_;
- impl_ = nullptr;
- }
-
- if (success != nullptr) {
- *success = outcome;
- }
-}
-
-} // namespace grpc_core
-
-gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)g_thd_info; }
-
-#endif /* GPR_WINDOWS */
+ impl_ = nullptr;
+ }
+
+ if (success != nullptr) {
+ *success = outcome;
+ }
+}
+
+} // namespace grpc_core
+
+gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)g_thd_info; }
+
+#endif /* GPR_WINDOWS */
diff --git a/contrib/libs/grpc/src/core/lib/http/format_request.cc b/contrib/libs/grpc/src/core/lib/http/format_request.cc
index d9294324bd0..d5b7f8791f9 100644
--- a/contrib/libs/grpc/src/core/lib/http/format_request.cc
+++ b/contrib/libs/grpc/src/core/lib/http/format_request.cc
@@ -1,103 +1,103 @@
-/*
- *
- * 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/http/format_request.h"
-
-#include <stdarg.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/lib/http/format_request.h"
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
#include <vector>
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/slice.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-#include "src/core/lib/gpr/string.h"
-
-static void fill_common_header(const grpc_httpcli_request* request,
+#include <grpc/slice.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/gpr/string.h"
+
+static void fill_common_header(const grpc_httpcli_request* request,
bool connection_close,
std::vector<TString>* buf) {
buf->push_back(request->http.path);
buf->push_back(" HTTP/1.0\r\n");
- /* just in case some crazy server really expects HTTP/1.1 */
+ /* just in case some crazy server really expects HTTP/1.1 */
buf->push_back("Host: ");
buf->push_back(request->host);
buf->push_back("\r\n");
if (connection_close) buf->push_back("Connection: close\r\n");
buf->push_back("User-Agent: " GRPC_HTTPCLI_USER_AGENT "\r\n");
- /* user supplied headers */
+ /* user supplied headers */
for (size_t i = 0; i < request->http.hdr_count; i++) {
buf->push_back(request->http.hdrs[i].key);
buf->push_back(": ");
buf->push_back(request->http.hdrs[i].value);
buf->push_back("\r\n");
- }
-}
-
-grpc_slice grpc_httpcli_format_get_request(
- const grpc_httpcli_request* request) {
+ }
+}
+
+grpc_slice grpc_httpcli_format_get_request(
+ const grpc_httpcli_request* request) {
std::vector<TString> out;
out.push_back("GET ");
fill_common_header(request, true, &out);
out.push_back("\r\n");
TString req = y_absl::StrJoin(out, "");
return grpc_slice_from_copied_buffer(req.data(), req.size());
-}
-
-grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request* request,
- const char* body_bytes,
- size_t body_size) {
+}
+
+grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request* request,
+ const char* body_bytes,
+ size_t body_size) {
std::vector<TString> out;
out.push_back("POST ");
fill_common_header(request, true, &out);
if (body_bytes != nullptr) {
bool has_content_type = false;
for (size_t i = 0; i < request->http.hdr_count; i++) {
- if (strcmp(request->http.hdrs[i].key, "Content-Type") == 0) {
+ if (strcmp(request->http.hdrs[i].key, "Content-Type") == 0) {
has_content_type = true;
- break;
- }
- }
- if (!has_content_type) {
+ break;
+ }
+ }
+ if (!has_content_type) {
out.push_back("Content-Type: text/plain\r\n");
- }
+ }
out.push_back(y_absl::StrFormat("Content-Length: %lu\r\n",
static_cast<unsigned long>(body_size)));
- }
+ }
out.push_back("\r\n");
TString req = y_absl::StrJoin(out, "");
if (body_bytes != nullptr) {
y_absl::StrAppend(&req, y_absl::string_view(body_bytes, body_size));
- }
+ }
return grpc_slice_from_copied_buffer(req.data(), req.size());
-}
-
-grpc_slice grpc_httpcli_format_connect_request(
- const grpc_httpcli_request* request) {
+}
+
+grpc_slice grpc_httpcli_format_connect_request(
+ const grpc_httpcli_request* request) {
std::vector<TString> out;
out.push_back("CONNECT ");
fill_common_header(request, false, &out);
out.push_back("\r\n");
TString req = y_absl::StrJoin(out, "");
return grpc_slice_from_copied_buffer(req.data(), req.size());
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/http/format_request.h b/contrib/libs/grpc/src/core/lib/http/format_request.h
index bcc332fe6e7..987661b0f18 100644
--- a/contrib/libs/grpc/src/core/lib/http/format_request.h
+++ b/contrib/libs/grpc/src/core/lib/http/format_request.h
@@ -1,34 +1,34 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_HTTP_FORMAT_REQUEST_H
#define GRPC_CORE_LIB_HTTP_FORMAT_REQUEST_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include "src/core/lib/http/httpcli.h"
-grpc_slice grpc_httpcli_format_get_request(const grpc_httpcli_request* request);
-grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request* request,
- const char* body_bytes,
+grpc_slice grpc_httpcli_format_get_request(const grpc_httpcli_request* request);
+grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request* request,
+ const char* body_bytes,
size_t body_size);
grpc_slice grpc_httpcli_format_connect_request(
- const grpc_httpcli_request* request);
+ const grpc_httpcli_request* request);
#endif /* GRPC_CORE_LIB_HTTP_FORMAT_REQUEST_H */
diff --git a/contrib/libs/grpc/src/core/lib/http/httpcli.cc b/contrib/libs/grpc/src/core/lib/http/httpcli.cc
index c196a8faac7..1487bdbb295 100644
--- a/contrib/libs/grpc/src/core/lib/http/httpcli.cc
+++ b/contrib/libs/grpc/src/core/lib/http/httpcli.cc
@@ -1,306 +1,306 @@
-/*
- *
- * 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/http/httpcli.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/lib/http/httpcli.h"
+
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_format.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/gpr/string.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/gpr/string.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"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/slice/slice_internal.h"
-
+#include "src/core/lib/http/format_request.h"
+#include "src/core/lib/http/parser.h"
+#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/slice/slice_internal.h"
+
struct internal_request {
- grpc_slice request_text;
- grpc_http_parser parser;
- grpc_resolved_addresses* addresses;
- size_t next_address;
- grpc_endpoint* ep;
- char* host;
- char* ssl_host_override;
- grpc_millis deadline;
- int have_read_byte;
- const grpc_httpcli_handshaker* handshaker;
- grpc_closure* on_done;
- grpc_httpcli_context* context;
- grpc_polling_entity* pollent;
- grpc_iomgr_object iomgr_obj;
- grpc_slice_buffer incoming;
- grpc_slice_buffer outgoing;
- grpc_closure on_read;
- grpc_closure done_write;
- grpc_closure connected;
- grpc_error* overall_error;
- grpc_resource_quota* resource_quota;
+ grpc_slice request_text;
+ grpc_http_parser parser;
+ grpc_resolved_addresses* addresses;
+ size_t next_address;
+ grpc_endpoint* ep;
+ char* host;
+ char* ssl_host_override;
+ grpc_millis deadline;
+ int have_read_byte;
+ const grpc_httpcli_handshaker* handshaker;
+ grpc_closure* on_done;
+ grpc_httpcli_context* context;
+ grpc_polling_entity* pollent;
+ grpc_iomgr_object iomgr_obj;
+ grpc_slice_buffer incoming;
+ grpc_slice_buffer outgoing;
+ grpc_closure on_read;
+ grpc_closure done_write;
+ grpc_closure connected;
+ grpc_error* overall_error;
+ grpc_resource_quota* resource_quota;
};
-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,
+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*/,
- void (*on_done)(void* arg,
- grpc_endpoint* endpoint)) {
- on_done(arg, endpoint);
-}
-
-const grpc_httpcli_handshaker grpc_httpcli_plaintext = {"http",
- plaintext_handshake};
-
-void grpc_httpcli_context_init(grpc_httpcli_context* context) {
- context->pollset_set = grpc_pollset_set_create();
-}
-
-void grpc_httpcli_context_destroy(grpc_httpcli_context* context) {
- grpc_pollset_set_destroy(context->pollset_set);
-}
-
-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);
+ void (*on_done)(void* arg,
+ grpc_endpoint* endpoint)) {
+ on_done(arg, endpoint);
+}
+
+const grpc_httpcli_handshaker grpc_httpcli_plaintext = {"http",
+ plaintext_handshake};
+
+void grpc_httpcli_context_init(grpc_httpcli_context* context) {
+ context->pollset_set = grpc_pollset_set_create();
+}
+
+void grpc_httpcli_context_destroy(grpc_httpcli_context* context) {
+ grpc_pollset_set_destroy(context->pollset_set);
+}
+
+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_http_parser_destroy(&req->parser);
- if (req->addresses != nullptr) {
- grpc_resolved_addresses_destroy(req->addresses);
- }
- if (req->ep != nullptr) {
- grpc_endpoint_destroy(req->ep);
- }
- grpc_slice_unref_internal(req->request_text);
- gpr_free(req->host);
- gpr_free(req->ssl_host_override);
- grpc_iomgr_unregister_object(&req->iomgr_obj);
- grpc_slice_buffer_destroy_internal(&req->incoming);
- grpc_slice_buffer_destroy_internal(&req->outgoing);
- GRPC_ERROR_UNREF(req->overall_error);
- grpc_resource_quota_unref_internal(req->resource_quota);
- gpr_free(req);
-}
-
-static void append_error(internal_request* req, grpc_error* error) {
- if (req->overall_error == GRPC_ERROR_NONE) {
- req->overall_error =
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed HTTP/1 client request");
- }
- grpc_resolved_address* addr = &req->addresses->addrs[req->next_address - 1];
+ grpc_http_parser_destroy(&req->parser);
+ if (req->addresses != nullptr) {
+ grpc_resolved_addresses_destroy(req->addresses);
+ }
+ if (req->ep != nullptr) {
+ grpc_endpoint_destroy(req->ep);
+ }
+ grpc_slice_unref_internal(req->request_text);
+ gpr_free(req->host);
+ gpr_free(req->ssl_host_override);
+ grpc_iomgr_unregister_object(&req->iomgr_obj);
+ grpc_slice_buffer_destroy_internal(&req->incoming);
+ grpc_slice_buffer_destroy_internal(&req->outgoing);
+ GRPC_ERROR_UNREF(req->overall_error);
+ grpc_resource_quota_unref_internal(req->resource_quota);
+ gpr_free(req);
+}
+
+static void append_error(internal_request* req, grpc_error* error) {
+ if (req->overall_error == GRPC_ERROR_NONE) {
+ req->overall_error =
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed HTTP/1 client request");
+ }
+ grpc_resolved_address* addr = &req->addresses->addrs[req->next_address - 1];
TString addr_text = grpc_sockaddr_to_uri(addr);
- req->overall_error = grpc_error_add_child(
- req->overall_error,
- grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,
+ req->overall_error = grpc_error_add_child(
+ req->overall_error,
+ grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_cpp_string(std::move(addr_text))));
-}
-
-static void do_read(internal_request* req) {
+}
+
+static void do_read(internal_request* req) {
grpc_endpoint_read(req->ep, &req->incoming, &req->on_read, /*urgent=*/true);
-}
-
-static void on_read(void* user_data, grpc_error* error) {
- internal_request* req = static_cast<internal_request*>(user_data);
- size_t i;
-
- for (i = 0; i < req->incoming.count; i++) {
- if (GRPC_SLICE_LENGTH(req->incoming.slices[i])) {
- req->have_read_byte = 1;
- grpc_error* err = grpc_http_parser_parse(
- &req->parser, req->incoming.slices[i], nullptr);
- if (err != GRPC_ERROR_NONE) {
- finish(req, err);
- return;
- }
- }
- }
-
- if (error == GRPC_ERROR_NONE) {
- do_read(req);
- } else if (!req->have_read_byte) {
- next_address(req, GRPC_ERROR_REF(error));
- } else {
- finish(req, grpc_http_parser_eof(&req->parser));
- }
-}
-
-static void on_written(internal_request* req) { do_read(req); }
-
-static void done_write(void* arg, grpc_error* error) {
- internal_request* req = static_cast<internal_request*>(arg);
- if (error == GRPC_ERROR_NONE) {
- on_written(req);
- } else {
- next_address(req, GRPC_ERROR_REF(error));
- }
-}
-
-static void start_write(internal_request* req) {
- grpc_slice_ref_internal(req->request_text);
- grpc_slice_buffer_add(&req->outgoing, req->request_text);
+}
+
+static void on_read(void* user_data, grpc_error* error) {
+ internal_request* req = static_cast<internal_request*>(user_data);
+ size_t i;
+
+ for (i = 0; i < req->incoming.count; i++) {
+ if (GRPC_SLICE_LENGTH(req->incoming.slices[i])) {
+ req->have_read_byte = 1;
+ grpc_error* err = grpc_http_parser_parse(
+ &req->parser, req->incoming.slices[i], nullptr);
+ if (err != GRPC_ERROR_NONE) {
+ finish(req, err);
+ return;
+ }
+ }
+ }
+
+ if (error == GRPC_ERROR_NONE) {
+ do_read(req);
+ } else if (!req->have_read_byte) {
+ next_address(req, GRPC_ERROR_REF(error));
+ } else {
+ finish(req, grpc_http_parser_eof(&req->parser));
+ }
+}
+
+static void on_written(internal_request* req) { do_read(req); }
+
+static void done_write(void* arg, grpc_error* error) {
+ internal_request* req = static_cast<internal_request*>(arg);
+ if (error == GRPC_ERROR_NONE) {
+ on_written(req);
+ } else {
+ next_address(req, GRPC_ERROR_REF(error));
+ }
+}
+
+static void start_write(internal_request* req) {
+ grpc_slice_ref_internal(req->request_text);
+ grpc_slice_buffer_add(&req->outgoing, req->request_text);
grpc_endpoint_write(req->ep, &req->outgoing, &req->done_write, nullptr);
-}
-
-static void on_handshake_done(void* arg, grpc_endpoint* ep) {
- internal_request* req = static_cast<internal_request*>(arg);
-
- if (!ep) {
- next_address(req, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Unexplained handshake failure"));
- return;
- }
-
- req->ep = ep;
- start_write(req);
-}
-
-static void on_connected(void* arg, grpc_error* error) {
- internal_request* req = static_cast<internal_request*>(arg);
-
- if (!req->ep) {
- next_address(req, GRPC_ERROR_REF(error));
- return;
- }
- req->handshaker->handshake(
- req, req->ep, req->ssl_host_override ? req->ssl_host_override : req->host,
- req->deadline, on_handshake_done);
-}
-
-static void next_address(internal_request* req, grpc_error* error) {
- grpc_resolved_address* addr;
- if (error != GRPC_ERROR_NONE) {
- append_error(req, error);
- }
- if (req->next_address == req->addresses->naddrs) {
- finish(req,
- GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Failed HTTP requests to all targets", &req->overall_error, 1));
- return;
- }
- addr = &req->addresses->addrs[req->next_address++];
- GRPC_CLOSURE_INIT(&req->connected, on_connected, req,
- grpc_schedule_on_exec_ctx);
- grpc_arg arg = grpc_channel_arg_pointer_create(
- (char*)GRPC_ARG_RESOURCE_QUOTA, req->resource_quota,
- grpc_resource_quota_arg_vtable());
- grpc_channel_args args = {1, &arg};
- grpc_tcp_client_connect(&req->connected, &req->ep, req->context->pollset_set,
- &args, addr, req->deadline);
-}
-
-static void on_resolved(void* arg, grpc_error* error) {
- internal_request* req = static_cast<internal_request*>(arg);
- if (error != GRPC_ERROR_NONE) {
- finish(req, GRPC_ERROR_REF(error));
- return;
- }
- req->next_address = 0;
- next_address(req, GRPC_ERROR_NONE);
-}
-
-static void internal_request_begin(grpc_httpcli_context* context,
- grpc_polling_entity* pollent,
- grpc_resource_quota* resource_quota,
- const grpc_httpcli_request* request,
- grpc_millis deadline, grpc_closure* on_done,
- grpc_httpcli_response* response,
+}
+
+static void on_handshake_done(void* arg, grpc_endpoint* ep) {
+ internal_request* req = static_cast<internal_request*>(arg);
+
+ if (!ep) {
+ next_address(req, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Unexplained handshake failure"));
+ return;
+ }
+
+ req->ep = ep;
+ start_write(req);
+}
+
+static void on_connected(void* arg, grpc_error* error) {
+ internal_request* req = static_cast<internal_request*>(arg);
+
+ if (!req->ep) {
+ next_address(req, GRPC_ERROR_REF(error));
+ return;
+ }
+ req->handshaker->handshake(
+ req, req->ep, req->ssl_host_override ? req->ssl_host_override : req->host,
+ req->deadline, on_handshake_done);
+}
+
+static void next_address(internal_request* req, grpc_error* error) {
+ grpc_resolved_address* addr;
+ if (error != GRPC_ERROR_NONE) {
+ append_error(req, error);
+ }
+ if (req->next_address == req->addresses->naddrs) {
+ finish(req,
+ GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Failed HTTP requests to all targets", &req->overall_error, 1));
+ return;
+ }
+ addr = &req->addresses->addrs[req->next_address++];
+ GRPC_CLOSURE_INIT(&req->connected, on_connected, req,
+ grpc_schedule_on_exec_ctx);
+ grpc_arg arg = grpc_channel_arg_pointer_create(
+ (char*)GRPC_ARG_RESOURCE_QUOTA, req->resource_quota,
+ grpc_resource_quota_arg_vtable());
+ grpc_channel_args args = {1, &arg};
+ grpc_tcp_client_connect(&req->connected, &req->ep, req->context->pollset_set,
+ &args, addr, req->deadline);
+}
+
+static void on_resolved(void* arg, grpc_error* error) {
+ internal_request* req = static_cast<internal_request*>(arg);
+ if (error != GRPC_ERROR_NONE) {
+ finish(req, GRPC_ERROR_REF(error));
+ return;
+ }
+ req->next_address = 0;
+ next_address(req, GRPC_ERROR_NONE);
+}
+
+static void internal_request_begin(grpc_httpcli_context* context,
+ grpc_polling_entity* pollent,
+ grpc_resource_quota* resource_quota,
+ const grpc_httpcli_request* request,
+ grpc_millis deadline, grpc_closure* on_done,
+ grpc_httpcli_response* response,
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));
- req->request_text = request_text;
- grpc_http_parser_init(&req->parser, GRPC_HTTP_RESPONSE, response);
- req->on_done = on_done;
- req->deadline = deadline;
- req->handshaker =
- request->handshaker ? request->handshaker : &grpc_httpcli_plaintext;
- req->context = context;
- req->pollent = pollent;
- req->overall_error = GRPC_ERROR_NONE;
- req->resource_quota = grpc_resource_quota_ref_internal(resource_quota);
- GRPC_CLOSURE_INIT(&req->on_read, on_read, req, grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&req->done_write, done_write, req,
- grpc_schedule_on_exec_ctx);
- grpc_slice_buffer_init(&req->incoming);
- grpc_slice_buffer_init(&req->outgoing);
- grpc_iomgr_register_object(&req->iomgr_obj, name);
- req->host = gpr_strdup(request->host);
- req->ssl_host_override = gpr_strdup(request->ssl_host_override);
-
- GPR_ASSERT(pollent);
- grpc_polling_entity_add_to_pollset_set(req->pollent,
- req->context->pollset_set);
- grpc_resolve_address(
- request->host, req->handshaker->default_port, req->context->pollset_set,
- GRPC_CLOSURE_CREATE(on_resolved, req, grpc_schedule_on_exec_ctx),
- &req->addresses);
-}
-
-void grpc_httpcli_get(grpc_httpcli_context* context,
- grpc_polling_entity* pollent,
- grpc_resource_quota* resource_quota,
- const grpc_httpcli_request* request, grpc_millis deadline,
- grpc_closure* on_done, grpc_httpcli_response* response) {
- if (g_get_override && g_get_override(request, deadline, on_done, response)) {
- return;
- }
+ internal_request* req =
+ static_cast<internal_request*>(gpr_malloc(sizeof(internal_request)));
+ memset(req, 0, sizeof(*req));
+ req->request_text = request_text;
+ grpc_http_parser_init(&req->parser, GRPC_HTTP_RESPONSE, response);
+ req->on_done = on_done;
+ req->deadline = deadline;
+ req->handshaker =
+ request->handshaker ? request->handshaker : &grpc_httpcli_plaintext;
+ req->context = context;
+ req->pollent = pollent;
+ req->overall_error = GRPC_ERROR_NONE;
+ req->resource_quota = grpc_resource_quota_ref_internal(resource_quota);
+ GRPC_CLOSURE_INIT(&req->on_read, on_read, req, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&req->done_write, done_write, req,
+ grpc_schedule_on_exec_ctx);
+ grpc_slice_buffer_init(&req->incoming);
+ grpc_slice_buffer_init(&req->outgoing);
+ grpc_iomgr_register_object(&req->iomgr_obj, name);
+ req->host = gpr_strdup(request->host);
+ req->ssl_host_override = gpr_strdup(request->ssl_host_override);
+
+ GPR_ASSERT(pollent);
+ grpc_polling_entity_add_to_pollset_set(req->pollent,
+ req->context->pollset_set);
+ grpc_resolve_address(
+ request->host, req->handshaker->default_port, req->context->pollset_set,
+ GRPC_CLOSURE_CREATE(on_resolved, req, grpc_schedule_on_exec_ctx),
+ &req->addresses);
+}
+
+void grpc_httpcli_get(grpc_httpcli_context* context,
+ grpc_polling_entity* pollent,
+ grpc_resource_quota* resource_quota,
+ const grpc_httpcli_request* request, grpc_millis deadline,
+ grpc_closure* on_done, grpc_httpcli_response* response) {
+ if (g_get_override && g_get_override(request, deadline, on_done, response)) {
+ return;
+ }
TString name =
y_absl::StrFormat("HTTP:GET:%s:%s", request->host, request->http.path);
- internal_request_begin(context, pollent, resource_quota, request, deadline,
+ internal_request_begin(context, pollent, resource_quota, request, deadline,
on_done, response, name.c_str(),
- grpc_httpcli_format_get_request(request));
-}
-
-void grpc_httpcli_post(grpc_httpcli_context* context,
- grpc_polling_entity* pollent,
- grpc_resource_quota* resource_quota,
- const grpc_httpcli_request* request,
- const char* body_bytes, size_t body_size,
- grpc_millis deadline, grpc_closure* on_done,
- grpc_httpcli_response* response) {
- if (g_post_override && g_post_override(request, body_bytes, body_size,
- deadline, on_done, response)) {
- return;
- }
+ grpc_httpcli_format_get_request(request));
+}
+
+void grpc_httpcli_post(grpc_httpcli_context* context,
+ grpc_polling_entity* pollent,
+ grpc_resource_quota* resource_quota,
+ const grpc_httpcli_request* request,
+ const char* body_bytes, size_t body_size,
+ grpc_millis deadline, grpc_closure* on_done,
+ grpc_httpcli_response* response) {
+ if (g_post_override && g_post_override(request, body_bytes, body_size,
+ deadline, on_done, response)) {
+ return;
+ }
TString name =
y_absl::StrFormat("HTTP:POST:%s:%s", request->host, request->http.path);
- internal_request_begin(
- context, pollent, resource_quota, request, deadline, on_done, response,
+ internal_request_begin(
+ context, pollent, resource_quota, request, deadline, on_done, response,
name.c_str(),
grpc_httpcli_format_post_request(request, body_bytes, body_size));
-}
-
-void grpc_httpcli_set_override(grpc_httpcli_get_override get,
- grpc_httpcli_post_override post) {
- g_get_override = get;
- g_post_override = post;
-}
+}
+
+void grpc_httpcli_set_override(grpc_httpcli_get_override get,
+ grpc_httpcli_post_override post) {
+ g_get_override = get;
+ g_post_override = post;
+}
diff --git a/contrib/libs/grpc/src/core/lib/http/httpcli.h b/contrib/libs/grpc/src/core/lib/http/httpcli.h
index 16a160cc965..69851e921ca 100644
--- a/contrib/libs/grpc/src/core/lib/http/httpcli.h
+++ b/contrib/libs/grpc/src/core/lib/http/httpcli.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_HTTP_HTTPCLI_H
#define GRPC_CORE_LIB_HTTP_HTTPCLI_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stddef.h>
#include <grpc/support/time.h>
@@ -38,14 +38,14 @@
TODO(ctiller): allow caching and capturing multiple requests for the
same content and combining them */
typedef struct grpc_httpcli_context {
- grpc_pollset_set* pollset_set;
+ grpc_pollset_set* pollset_set;
} grpc_httpcli_context;
struct grpc_httpcli_handshaker {
- const char* default_port;
- void (*handshake)(void* arg, grpc_endpoint* endpoint, const char* host,
- grpc_millis deadline,
- void (*on_done)(void* arg, grpc_endpoint* endpoint));
+ const char* default_port;
+ void (*handshake)(void* arg, grpc_endpoint* endpoint, const char* host,
+ grpc_millis deadline,
+ void (*on_done)(void* arg, grpc_endpoint* endpoint));
};
extern const grpc_httpcli_handshaker grpc_httpcli_plaintext;
extern const grpc_httpcli_handshaker grpc_httpcli_ssl;
@@ -53,22 +53,22 @@ extern const grpc_httpcli_handshaker grpc_httpcli_ssl;
/* A request */
typedef struct grpc_httpcli_request {
/* The host name to connect to */
- char* host;
+ char* host;
/* The host to verify in the SSL handshake (or NULL) */
- char* ssl_host_override;
+ char* ssl_host_override;
/* The main part of the request
The following headers are supplied automatically and MUST NOT be set here:
Host, Connection, User-Agent */
grpc_http_request http;
/* handshaker to use ssl for the request */
- const grpc_httpcli_handshaker* handshaker;
+ const grpc_httpcli_handshaker* handshaker;
} grpc_httpcli_request;
/* Expose the parser response type as a httpcli response too */
typedef struct grpc_http_response grpc_httpcli_response;
-void grpc_httpcli_context_init(grpc_httpcli_context* context);
-void grpc_httpcli_context_destroy(grpc_httpcli_context* context);
+void grpc_httpcli_context_init(grpc_httpcli_context* context);
+void grpc_httpcli_context_destroy(grpc_httpcli_context* context);
/* Asynchronously perform a HTTP GET.
'context' specifies the http context under which to do the get
@@ -79,12 +79,12 @@ void grpc_httpcli_context_destroy(grpc_httpcli_context* context);
destroyed once the call returns
'deadline' contains a deadline for the request (or gpr_inf_future)
'on_response' is a callback to report results to */
-void grpc_httpcli_get(grpc_httpcli_context* context,
- grpc_polling_entity* pollent,
- grpc_resource_quota* resource_quota,
- const grpc_httpcli_request* request, grpc_millis deadline,
- grpc_closure* on_complete,
- grpc_httpcli_response* response);
+void grpc_httpcli_get(grpc_httpcli_context* context,
+ grpc_polling_entity* pollent,
+ grpc_resource_quota* resource_quota,
+ const grpc_httpcli_request* request, grpc_millis deadline,
+ grpc_closure* on_complete,
+ grpc_httpcli_response* response);
/* Asynchronously perform a HTTP POST.
'context' specifies the http context under which to do the post
@@ -100,25 +100,25 @@ void grpc_httpcli_get(grpc_httpcli_context* context,
lifetime of the request
'on_response' is a callback to report results to
Does not support ?var1=val1&var2=val2 in the path. */
-void grpc_httpcli_post(grpc_httpcli_context* context,
- grpc_polling_entity* pollent,
- grpc_resource_quota* resource_quota,
- const grpc_httpcli_request* request,
- const char* body_bytes, size_t body_size,
- grpc_millis deadline, grpc_closure* on_complete,
- grpc_httpcli_response* response);
+void grpc_httpcli_post(grpc_httpcli_context* context,
+ grpc_polling_entity* pollent,
+ grpc_resource_quota* resource_quota,
+ const grpc_httpcli_request* request,
+ const char* body_bytes, size_t body_size,
+ grpc_millis deadline, grpc_closure* on_complete,
+ grpc_httpcli_response* response);
/* override functions return 1 if they handled the request, 0 otherwise */
-typedef int (*grpc_httpcli_get_override)(const grpc_httpcli_request* request,
- grpc_millis deadline,
- grpc_closure* on_complete,
- grpc_httpcli_response* response);
-typedef int (*grpc_httpcli_post_override)(const grpc_httpcli_request* request,
- const char* body_bytes,
- size_t body_size,
- grpc_millis deadline,
- grpc_closure* on_complete,
- grpc_httpcli_response* response);
+typedef int (*grpc_httpcli_get_override)(const grpc_httpcli_request* request,
+ grpc_millis deadline,
+ grpc_closure* on_complete,
+ grpc_httpcli_response* response);
+typedef int (*grpc_httpcli_post_override)(const grpc_httpcli_request* request,
+ const char* body_bytes,
+ size_t body_size,
+ grpc_millis deadline,
+ grpc_closure* on_complete,
+ grpc_httpcli_response* response);
void grpc_httpcli_set_override(grpc_httpcli_get_override get,
grpc_httpcli_post_override post);
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 62643186ad0..9bc7c3e7d3d 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/http/httpcli.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/lib/http/httpcli.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/string_view.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/channel/handshaker_registry.h"
-#include "src/core/lib/gpr/string.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/channel/handshaker_registry.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/security_connector/ssl_utils.h"
-#include "src/core/lib/security/transport/security_handshaker.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/tsi/ssl_transport_security.h"
-
+#include "src/core/lib/security/transport/security_handshaker.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/tsi/ssl_transport_security.h"
+
class grpc_httpcli_ssl_channel_security_connector final
: public grpc_channel_security_connector {
public:
@@ -49,7 +49,7 @@ class grpc_httpcli_ssl_channel_security_connector final
/*channel_creds=*/nullptr,
/*request_metadata_creds=*/nullptr),
secure_peer_name_(secure_peer_name) {}
-
+
~grpc_httpcli_ssl_channel_security_connector() override {
if (handshaker_factory_ != nullptr) {
tsi_ssl_client_handshaker_factory_unref(handshaker_factory_);
@@ -57,8 +57,8 @@ class grpc_httpcli_ssl_channel_security_connector final
if (secure_peer_name_ != nullptr) {
gpr_free(secure_peer_name_);
}
- }
-
+ }
+
tsi_result InitHandshakerFactory(const char* pem_root_certs,
const tsi_ssl_root_certs_store* root_store) {
tsi_ssl_client_handshaker_options options;
@@ -79,15 +79,15 @@ class grpc_httpcli_ssl_channel_security_connector final
gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.",
tsi_result_to_string(result));
}
- }
+ }
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*/,
grpc_core::RefCountedPtr<grpc_auth_context>* /*auth_context*/,
grpc_closure* on_peer_checked) override {
@@ -103,15 +103,15 @@ class grpc_httpcli_ssl_channel_security_connector final
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
tsi_peer_destruct(&peer);
- }
-
+ }
+
int cmp(const grpc_security_connector* other_sc) const override {
auto* other =
reinterpret_cast<const grpc_httpcli_ssl_channel_security_connector*>(
other_sc);
return strcmp(secure_peer_name_, other->secure_peer_name_);
}
-
+
bool check_call_host(y_absl::string_view /*host*/,
grpc_auth_context* /*auth_context*/,
grpc_closure* /*on_call_host_checked*/,
@@ -119,7 +119,7 @@ class grpc_httpcli_ssl_channel_security_connector final
*error = GRPC_ERROR_NONE;
return true;
}
-
+
void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/,
grpc_error* error) override {
GRPC_ERROR_UNREF(error);
@@ -134,65 +134,65 @@ 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* pem_root_certs, const tsi_ssl_root_certs_store* root_store,
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.");
+ if (secure_peer_name != nullptr && pem_root_certs == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Cannot assert a secure peer name without a trust root.");
return nullptr;
- }
+ }
grpc_core::RefCountedPtr<grpc_httpcli_ssl_channel_security_connector> c =
grpc_core::MakeRefCounted<grpc_httpcli_ssl_channel_security_connector>(
secure_peer_name == nullptr ? nullptr : gpr_strdup(secure_peer_name));
tsi_result result = c->InitHandshakerFactory(pem_root_certs, root_store);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
- tsi_result_to_string(result));
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
+ tsi_result_to_string(result));
return nullptr;
- }
+ }
return c;
-}
-
-/* handshaker */
-
+}
+
+/* handshaker */
+
struct on_done_closure {
- void (*func)(void* arg, grpc_endpoint* endpoint);
- void* arg;
+ void (*func)(void* arg, grpc_endpoint* endpoint);
+ void* arg;
grpc_core::RefCountedPtr<grpc_core::HandshakeManager> handshake_mgr;
};
-static void on_handshake_done(void* arg, grpc_error* error) {
+static void on_handshake_done(void* arg, grpc_error* error) {
auto* args = static_cast<grpc_core::HandshakerArgs*>(arg);
- on_done_closure* c = static_cast<on_done_closure*>(args->user_data);
- if (error != GRPC_ERROR_NONE) {
- const char* msg = grpc_error_string(error);
- gpr_log(GPR_ERROR, "Secure transport setup failed: %s", msg);
-
- c->func(c->arg, nullptr);
- } else {
- grpc_channel_args_destroy(args->args);
- grpc_slice_buffer_destroy_internal(args->read_buffer);
- gpr_free(args->read_buffer);
- c->func(c->arg, args->endpoint);
- }
+ on_done_closure* c = static_cast<on_done_closure*>(args->user_data);
+ if (error != GRPC_ERROR_NONE) {
+ const char* msg = grpc_error_string(error);
+ gpr_log(GPR_ERROR, "Secure transport setup failed: %s", msg);
+
+ c->func(c->arg, nullptr);
+ } else {
+ grpc_channel_args_destroy(args->args);
+ grpc_slice_buffer_destroy_internal(args->read_buffer);
+ gpr_free(args->read_buffer);
+ c->func(c->arg, args->endpoint);
+ }
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)) {
+}
+
+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();
- const char* pem_root_certs =
- grpc_core::DefaultSslRootStore::GetPemRootCerts();
- const tsi_ssl_root_certs_store* root_store =
- grpc_core::DefaultSslRootStore::GetRootStore();
- if (root_store == nullptr) {
- gpr_log(GPR_ERROR, "Could not get default pem root certs.");
- on_done(arg, nullptr);
- gpr_free(c);
- return;
- }
- c->func = on_done;
- c->arg = arg;
+ const char* pem_root_certs =
+ grpc_core::DefaultSslRootStore::GetPemRootCerts();
+ const tsi_ssl_root_certs_store* root_store =
+ grpc_core::DefaultSslRootStore::GetRootStore();
+ if (root_store == nullptr) {
+ gpr_log(GPR_ERROR, "Could not get default pem root certs.");
+ on_done(arg, nullptr);
+ gpr_free(c);
+ return;
+ }
+ 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,
@@ -200,7 +200,7 @@ static void ssl_handshake(void* arg, grpc_endpoint* tcp, const char* host,
GPR_ASSERT(sc != nullptr);
grpc_arg channel_arg = grpc_security_connector_to_arg(sc.get());
- grpc_channel_args args = {1, &channel_arg};
+ grpc_channel_args args = {1, &channel_arg};
c->handshake_mgr = grpc_core::MakeRefCounted<grpc_core::HandshakeManager>();
grpc_core::HandshakerRegistry::AddHandshakers(
grpc_core::HANDSHAKER_CLIENT, &args, /*interested_parties=*/nullptr,
@@ -209,6 +209,6 @@ static void ssl_handshake(void* arg, grpc_endpoint* tcp, const char* host,
/*acceptor=*/nullptr, on_handshake_done,
/*user_data=*/c);
sc.reset(DEBUG_LOCATION, "httpcli");
-}
-
-const grpc_httpcli_handshaker grpc_httpcli_ssl = {"https", ssl_handshake};
+}
+
+const grpc_httpcli_handshaker grpc_httpcli_ssl = {"https", ssl_handshake};
diff --git a/contrib/libs/grpc/src/core/lib/http/parser.cc b/contrib/libs/grpc/src/core/lib/http/parser.cc
index 022ef9a2e7b..e50d791a1cc 100644
--- a/contrib/libs/grpc/src/core/lib/http/parser.cc
+++ b/contrib/libs/grpc/src/core/lib/http/parser.cc
@@ -1,372 +1,372 @@
-/*
- *
- * 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/http/parser.h"
-
-#include <stdbool.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-grpc_core::TraceFlag grpc_http1_trace(false, "http1");
-
-static char* buf2str(void* buffer, size_t length) {
- char* out = static_cast<char*>(gpr_malloc(length + 1));
- memcpy(out, buffer, length);
- out[length] = 0;
- return out;
-}
-
-static grpc_error* handle_response_line(grpc_http_parser* parser) {
- uint8_t* beg = parser->cur_line;
- uint8_t* cur = beg;
- uint8_t* end = beg + parser->cur_line_length;
-
- if (cur == end || *cur++ != 'H')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'H'");
- if (cur == end || *cur++ != 'T')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
- if (cur == end || *cur++ != 'T')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
- if (cur == end || *cur++ != 'P')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'P'");
- if (cur == end || *cur++ != '/')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '/'");
- if (cur == end || *cur++ != '1')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '1'");
- if (cur == end || *cur++ != '.')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '.'");
- if (cur == end || *cur < '0' || *cur++ > '1') {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Expected HTTP/1.0 or HTTP/1.1");
- }
- if (cur == end || *cur++ != ' ')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected ' '");
- if (cur == end || *cur < '1' || *cur++ > '9')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected status code");
- if (cur == end || *cur < '0' || *cur++ > '9')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected status code");
- if (cur == end || *cur < '0' || *cur++ > '9')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected status code");
- parser->http.response->status =
- (cur[-3] - '0') * 100 + (cur[-2] - '0') * 10 + (cur[-1] - '0');
- if (cur == end || *cur++ != ' ')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected ' '");
-
- /* we don't really care about the status code message */
-
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* handle_request_line(grpc_http_parser* parser) {
- uint8_t* beg = parser->cur_line;
- uint8_t* cur = beg;
- uint8_t* end = beg + parser->cur_line_length;
- uint8_t vers_major = 0;
- uint8_t vers_minor = 0;
-
- while (cur != end && *cur++ != ' ')
- ;
- if (cur == end)
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "No method on HTTP request line");
- parser->http.request->method =
- buf2str(beg, static_cast<size_t>(cur - beg - 1));
-
- beg = cur;
- while (cur != end && *cur++ != ' ')
- ;
- if (cur == end)
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("No path on HTTP request line");
- parser->http.request->path = buf2str(beg, static_cast<size_t>(cur - beg - 1));
-
- if (cur == end || *cur++ != 'H')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'H'");
- if (cur == end || *cur++ != 'T')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
- if (cur == end || *cur++ != 'T')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
- if (cur == end || *cur++ != 'P')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'P'");
- if (cur == end || *cur++ != '/')
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '/'");
- vers_major = static_cast<uint8_t>(*cur++ - '1' + 1);
- ++cur;
- if (cur == end)
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "End of line in HTTP version string");
- vers_minor = static_cast<uint8_t>(*cur++ - '1' + 1);
-
- if (vers_major == 1) {
- if (vers_minor == 0) {
- parser->http.request->version = GRPC_HTTP_HTTP10;
- } else if (vers_minor == 1) {
- parser->http.request->version = GRPC_HTTP_HTTP11;
- } else {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Expected one of HTTP/1.0, HTTP/1.1, or HTTP/2.0");
- }
- } else if (vers_major == 2) {
- if (vers_minor == 0) {
- parser->http.request->version = GRPC_HTTP_HTTP20;
- } else {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Expected one of HTTP/1.0, HTTP/1.1, or HTTP/2.0");
- }
- } else {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Expected one of HTTP/1.0, HTTP/1.1, or HTTP/2.0");
- }
-
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* handle_first_line(grpc_http_parser* parser) {
- switch (parser->type) {
- case GRPC_HTTP_REQUEST:
- return handle_request_line(parser);
- case GRPC_HTTP_RESPONSE:
- return handle_response_line(parser);
- }
- GPR_UNREACHABLE_CODE(
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here"));
-}
-
-static grpc_error* add_header(grpc_http_parser* parser) {
- uint8_t* beg = parser->cur_line;
- uint8_t* cur = beg;
- uint8_t* end = beg + parser->cur_line_length;
- size_t* hdr_count = nullptr;
- grpc_http_header** hdrs = nullptr;
- grpc_http_header hdr = {nullptr, nullptr};
- grpc_error* error = GRPC_ERROR_NONE;
-
- GPR_ASSERT(cur != end);
-
- if (*cur == ' ' || *cur == '\t') {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Continued header lines not supported yet");
- goto done;
- }
-
- while (cur != end && *cur != ':') {
- cur++;
- }
- if (cur == end) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Didn't find ':' in header string");
- goto done;
- }
- GPR_ASSERT(cur >= beg);
- hdr.key = buf2str(beg, static_cast<size_t>(cur - beg));
- cur++; /* skip : */
-
- while (cur != end && (*cur == ' ' || *cur == '\t')) {
- cur++;
- }
- GPR_ASSERT((size_t)(end - cur) >= parser->cur_line_end_length);
- hdr.value = buf2str(
- cur, static_cast<size_t>(end - cur) - parser->cur_line_end_length);
-
- switch (parser->type) {
- case GRPC_HTTP_RESPONSE:
- hdr_count = &parser->http.response->hdr_count;
- hdrs = &parser->http.response->hdrs;
- break;
- case GRPC_HTTP_REQUEST:
- hdr_count = &parser->http.request->hdr_count;
- hdrs = &parser->http.request->hdrs;
- break;
- }
-
- if (*hdr_count == parser->hdr_capacity) {
- parser->hdr_capacity =
- GPR_MAX(parser->hdr_capacity + 1, parser->hdr_capacity * 3 / 2);
- *hdrs = static_cast<grpc_http_header*>(
- gpr_realloc(*hdrs, parser->hdr_capacity * sizeof(**hdrs)));
- }
- (*hdrs)[(*hdr_count)++] = hdr;
-
-done:
- if (error != GRPC_ERROR_NONE) {
- gpr_free(hdr.key);
- gpr_free(hdr.value);
- }
- return error;
-}
-
-static grpc_error* finish_line(grpc_http_parser* parser,
- bool* found_body_start) {
- grpc_error* err;
- switch (parser->state) {
- case GRPC_HTTP_FIRST_LINE:
- err = handle_first_line(parser);
- if (err != GRPC_ERROR_NONE) return err;
- parser->state = GRPC_HTTP_HEADERS;
- break;
- case GRPC_HTTP_HEADERS:
- if (parser->cur_line_length == parser->cur_line_end_length) {
- parser->state = GRPC_HTTP_BODY;
- *found_body_start = true;
- break;
- }
- err = add_header(parser);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- break;
- case GRPC_HTTP_BODY:
- GPR_UNREACHABLE_CODE(return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Should never reach here"));
- }
-
- parser->cur_line_length = 0;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* addbyte_body(grpc_http_parser* parser, uint8_t byte) {
- size_t* body_length = nullptr;
- char** body = nullptr;
-
- if (parser->type == GRPC_HTTP_RESPONSE) {
- body_length = &parser->http.response->body_length;
- body = &parser->http.response->body;
- } else if (parser->type == GRPC_HTTP_REQUEST) {
- body_length = &parser->http.request->body_length;
- body = &parser->http.request->body;
- } else {
- GPR_UNREACHABLE_CODE(
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here"));
- }
-
- if (*body_length == parser->body_capacity) {
- parser->body_capacity = GPR_MAX(8, parser->body_capacity * 3 / 2);
- *body =
- static_cast<char*>(gpr_realloc((void*)*body, parser->body_capacity));
- }
- (*body)[*body_length] = static_cast<char>(byte);
- (*body_length)++;
-
- return GRPC_ERROR_NONE;
-}
-
-static bool check_line(grpc_http_parser* parser) {
- if (parser->cur_line_length >= 2 &&
- parser->cur_line[parser->cur_line_length - 2] == '\r' &&
- parser->cur_line[parser->cur_line_length - 1] == '\n') {
- return true;
- }
-
- // HTTP request with \n\r line termiantors.
- else if (parser->cur_line_length >= 2 &&
- parser->cur_line[parser->cur_line_length - 2] == '\n' &&
- parser->cur_line[parser->cur_line_length - 1] == '\r') {
- return true;
- }
-
- // HTTP request with only \n line terminators.
- else if (parser->cur_line_length >= 1 &&
- parser->cur_line[parser->cur_line_length - 1] == '\n') {
- parser->cur_line_end_length = 1;
- return true;
- }
-
- return false;
-}
-
-static grpc_error* addbyte(grpc_http_parser* parser, uint8_t byte,
- bool* found_body_start) {
- switch (parser->state) {
- case GRPC_HTTP_FIRST_LINE:
- case GRPC_HTTP_HEADERS:
- if (parser->cur_line_length >= GRPC_HTTP_PARSER_MAX_HEADER_LENGTH) {
+/*
+ *
+ * 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/http/parser.h"
+
+#include <stdbool.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+grpc_core::TraceFlag grpc_http1_trace(false, "http1");
+
+static char* buf2str(void* buffer, size_t length) {
+ char* out = static_cast<char*>(gpr_malloc(length + 1));
+ memcpy(out, buffer, length);
+ out[length] = 0;
+ return out;
+}
+
+static grpc_error* handle_response_line(grpc_http_parser* parser) {
+ uint8_t* beg = parser->cur_line;
+ uint8_t* cur = beg;
+ uint8_t* end = beg + parser->cur_line_length;
+
+ if (cur == end || *cur++ != 'H')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'H'");
+ if (cur == end || *cur++ != 'T')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
+ if (cur == end || *cur++ != 'T')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
+ if (cur == end || *cur++ != 'P')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'P'");
+ if (cur == end || *cur++ != '/')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '/'");
+ if (cur == end || *cur++ != '1')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '1'");
+ if (cur == end || *cur++ != '.')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '.'");
+ if (cur == end || *cur < '0' || *cur++ > '1') {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Expected HTTP/1.0 or HTTP/1.1");
+ }
+ if (cur == end || *cur++ != ' ')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected ' '");
+ if (cur == end || *cur < '1' || *cur++ > '9')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected status code");
+ if (cur == end || *cur < '0' || *cur++ > '9')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected status code");
+ if (cur == end || *cur < '0' || *cur++ > '9')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected status code");
+ parser->http.response->status =
+ (cur[-3] - '0') * 100 + (cur[-2] - '0') * 10 + (cur[-1] - '0');
+ if (cur == end || *cur++ != ' ')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected ' '");
+
+ /* we don't really care about the status code message */
+
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* handle_request_line(grpc_http_parser* parser) {
+ uint8_t* beg = parser->cur_line;
+ uint8_t* cur = beg;
+ uint8_t* end = beg + parser->cur_line_length;
+ uint8_t vers_major = 0;
+ uint8_t vers_minor = 0;
+
+ while (cur != end && *cur++ != ' ')
+ ;
+ if (cur == end)
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "No method on HTTP request line");
+ parser->http.request->method =
+ buf2str(beg, static_cast<size_t>(cur - beg - 1));
+
+ beg = cur;
+ while (cur != end && *cur++ != ' ')
+ ;
+ if (cur == end)
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("No path on HTTP request line");
+ parser->http.request->path = buf2str(beg, static_cast<size_t>(cur - beg - 1));
+
+ if (cur == end || *cur++ != 'H')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'H'");
+ if (cur == end || *cur++ != 'T')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
+ if (cur == end || *cur++ != 'T')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'T'");
+ if (cur == end || *cur++ != 'P')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'P'");
+ if (cur == end || *cur++ != '/')
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected '/'");
+ vers_major = static_cast<uint8_t>(*cur++ - '1' + 1);
+ ++cur;
+ if (cur == end)
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "End of line in HTTP version string");
+ vers_minor = static_cast<uint8_t>(*cur++ - '1' + 1);
+
+ if (vers_major == 1) {
+ if (vers_minor == 0) {
+ parser->http.request->version = GRPC_HTTP_HTTP10;
+ } else if (vers_minor == 1) {
+ parser->http.request->version = GRPC_HTTP_HTTP11;
+ } else {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Expected one of HTTP/1.0, HTTP/1.1, or HTTP/2.0");
+ }
+ } else if (vers_major == 2) {
+ if (vers_minor == 0) {
+ parser->http.request->version = GRPC_HTTP_HTTP20;
+ } else {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Expected one of HTTP/1.0, HTTP/1.1, or HTTP/2.0");
+ }
+ } else {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Expected one of HTTP/1.0, HTTP/1.1, or HTTP/2.0");
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* handle_first_line(grpc_http_parser* parser) {
+ switch (parser->type) {
+ case GRPC_HTTP_REQUEST:
+ return handle_request_line(parser);
+ case GRPC_HTTP_RESPONSE:
+ return handle_response_line(parser);
+ }
+ GPR_UNREACHABLE_CODE(
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here"));
+}
+
+static grpc_error* add_header(grpc_http_parser* parser) {
+ uint8_t* beg = parser->cur_line;
+ uint8_t* cur = beg;
+ uint8_t* end = beg + parser->cur_line_length;
+ size_t* hdr_count = nullptr;
+ grpc_http_header** hdrs = nullptr;
+ grpc_http_header hdr = {nullptr, nullptr};
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ GPR_ASSERT(cur != end);
+
+ if (*cur == ' ' || *cur == '\t') {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Continued header lines not supported yet");
+ goto done;
+ }
+
+ while (cur != end && *cur != ':') {
+ cur++;
+ }
+ if (cur == end) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Didn't find ':' in header string");
+ goto done;
+ }
+ GPR_ASSERT(cur >= beg);
+ hdr.key = buf2str(beg, static_cast<size_t>(cur - beg));
+ cur++; /* skip : */
+
+ while (cur != end && (*cur == ' ' || *cur == '\t')) {
+ cur++;
+ }
+ GPR_ASSERT((size_t)(end - cur) >= parser->cur_line_end_length);
+ hdr.value = buf2str(
+ cur, static_cast<size_t>(end - cur) - parser->cur_line_end_length);
+
+ switch (parser->type) {
+ case GRPC_HTTP_RESPONSE:
+ hdr_count = &parser->http.response->hdr_count;
+ hdrs = &parser->http.response->hdrs;
+ break;
+ case GRPC_HTTP_REQUEST:
+ hdr_count = &parser->http.request->hdr_count;
+ hdrs = &parser->http.request->hdrs;
+ break;
+ }
+
+ if (*hdr_count == parser->hdr_capacity) {
+ parser->hdr_capacity =
+ GPR_MAX(parser->hdr_capacity + 1, parser->hdr_capacity * 3 / 2);
+ *hdrs = static_cast<grpc_http_header*>(
+ gpr_realloc(*hdrs, parser->hdr_capacity * sizeof(**hdrs)));
+ }
+ (*hdrs)[(*hdr_count)++] = hdr;
+
+done:
+ if (error != GRPC_ERROR_NONE) {
+ gpr_free(hdr.key);
+ gpr_free(hdr.value);
+ }
+ return error;
+}
+
+static grpc_error* finish_line(grpc_http_parser* parser,
+ bool* found_body_start) {
+ grpc_error* err;
+ switch (parser->state) {
+ case GRPC_HTTP_FIRST_LINE:
+ err = handle_first_line(parser);
+ if (err != GRPC_ERROR_NONE) return err;
+ parser->state = GRPC_HTTP_HEADERS;
+ break;
+ case GRPC_HTTP_HEADERS:
+ if (parser->cur_line_length == parser->cur_line_end_length) {
+ parser->state = GRPC_HTTP_BODY;
+ *found_body_start = true;
+ break;
+ }
+ err = add_header(parser);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ break;
+ case GRPC_HTTP_BODY:
+ GPR_UNREACHABLE_CODE(return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Should never reach here"));
+ }
+
+ parser->cur_line_length = 0;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* addbyte_body(grpc_http_parser* parser, uint8_t byte) {
+ size_t* body_length = nullptr;
+ char** body = nullptr;
+
+ if (parser->type == GRPC_HTTP_RESPONSE) {
+ body_length = &parser->http.response->body_length;
+ body = &parser->http.response->body;
+ } else if (parser->type == GRPC_HTTP_REQUEST) {
+ body_length = &parser->http.request->body_length;
+ body = &parser->http.request->body;
+ } else {
+ GPR_UNREACHABLE_CODE(
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here"));
+ }
+
+ if (*body_length == parser->body_capacity) {
+ parser->body_capacity = GPR_MAX(8, parser->body_capacity * 3 / 2);
+ *body =
+ static_cast<char*>(gpr_realloc((void*)*body, parser->body_capacity));
+ }
+ (*body)[*body_length] = static_cast<char>(byte);
+ (*body_length)++;
+
+ return GRPC_ERROR_NONE;
+}
+
+static bool check_line(grpc_http_parser* parser) {
+ if (parser->cur_line_length >= 2 &&
+ parser->cur_line[parser->cur_line_length - 2] == '\r' &&
+ parser->cur_line[parser->cur_line_length - 1] == '\n') {
+ return true;
+ }
+
+ // HTTP request with \n\r line termiantors.
+ else if (parser->cur_line_length >= 2 &&
+ parser->cur_line[parser->cur_line_length - 2] == '\n' &&
+ parser->cur_line[parser->cur_line_length - 1] == '\r') {
+ return true;
+ }
+
+ // HTTP request with only \n line terminators.
+ else if (parser->cur_line_length >= 1 &&
+ parser->cur_line[parser->cur_line_length - 1] == '\n') {
+ parser->cur_line_end_length = 1;
+ return true;
+ }
+
+ return false;
+}
+
+static grpc_error* addbyte(grpc_http_parser* parser, uint8_t byte,
+ bool* found_body_start) {
+ switch (parser->state) {
+ 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))
- gpr_log(GPR_ERROR, "HTTP header max line length (%d) exceeded",
- GRPC_HTTP_PARSER_MAX_HEADER_LENGTH);
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "HTTP header max line length exceeded");
- }
- parser->cur_line[parser->cur_line_length] = byte;
- parser->cur_line_length++;
- if (check_line(parser)) {
- return finish_line(parser, found_body_start);
- }
- return GRPC_ERROR_NONE;
- case GRPC_HTTP_BODY:
- return addbyte_body(parser, byte);
- }
- GPR_UNREACHABLE_CODE(return GRPC_ERROR_NONE);
-}
-
-void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type,
- void* request_or_response) {
- memset(parser, 0, sizeof(*parser));
- parser->state = GRPC_HTTP_FIRST_LINE;
- parser->type = type;
- parser->http.request_or_response = request_or_response;
- parser->cur_line_end_length = 2;
-}
-
+ gpr_log(GPR_ERROR, "HTTP header max line length (%d) exceeded",
+ GRPC_HTTP_PARSER_MAX_HEADER_LENGTH);
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "HTTP header max line length exceeded");
+ }
+ parser->cur_line[parser->cur_line_length] = byte;
+ parser->cur_line_length++;
+ if (check_line(parser)) {
+ return finish_line(parser, found_body_start);
+ }
+ return GRPC_ERROR_NONE;
+ case GRPC_HTTP_BODY:
+ return addbyte_body(parser, byte);
+ }
+ GPR_UNREACHABLE_CODE(return GRPC_ERROR_NONE);
+}
+
+void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type,
+ void* request_or_response) {
+ memset(parser, 0, sizeof(*parser));
+ parser->state = GRPC_HTTP_FIRST_LINE;
+ parser->type = type;
+ parser->http.request_or_response = request_or_response;
+ parser->cur_line_end_length = 2;
+}
+
void grpc_http_parser_destroy(grpc_http_parser* /*parser*/) {}
-
-void grpc_http_request_destroy(grpc_http_request* request) {
- size_t i;
- gpr_free(request->body);
- for (i = 0; i < request->hdr_count; i++) {
- gpr_free(request->hdrs[i].key);
- gpr_free(request->hdrs[i].value);
- }
- gpr_free(request->hdrs);
- gpr_free(request->method);
- gpr_free(request->path);
-}
-
-void grpc_http_response_destroy(grpc_http_response* response) {
- size_t i;
- gpr_free(response->body);
- for (i = 0; i < response->hdr_count; i++) {
- gpr_free(response->hdrs[i].key);
- gpr_free(response->hdrs[i].value);
- }
- gpr_free(response->hdrs);
-}
-
+
+void grpc_http_request_destroy(grpc_http_request* request) {
+ size_t i;
+ gpr_free(request->body);
+ for (i = 0; i < request->hdr_count; i++) {
+ gpr_free(request->hdrs[i].key);
+ gpr_free(request->hdrs[i].value);
+ }
+ gpr_free(request->hdrs);
+ gpr_free(request->method);
+ gpr_free(request->path);
+}
+
+void grpc_http_response_destroy(grpc_http_response* response) {
+ size_t i;
+ gpr_free(response->body);
+ for (i = 0; i < response->hdr_count; i++) {
+ gpr_free(response->hdrs[i].key);
+ gpr_free(response->hdrs[i].value);
+ }
+ gpr_free(response->hdrs);
+}
+
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;
- grpc_error* err =
- addbyte(parser, GRPC_SLICE_START_PTR(slice)[i], &found_body_start);
- if (err != GRPC_ERROR_NONE) return err;
- if (found_body_start && start_of_body != nullptr) *start_of_body = i + 1;
- }
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_http_parser_eof(grpc_http_parser* parser) {
- if (parser->state != GRPC_HTTP_BODY) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Did not finish headers");
- }
- return GRPC_ERROR_NONE;
-}
+ size_t* start_of_body) {
+ for (size_t i = 0; i < GRPC_SLICE_LENGTH(slice); i++) {
+ bool found_body_start = false;
+ grpc_error* err =
+ addbyte(parser, GRPC_SLICE_START_PTR(slice)[i], &found_body_start);
+ if (err != GRPC_ERROR_NONE) return err;
+ if (found_body_start && start_of_body != nullptr) *start_of_body = i + 1;
+ }
+ return GRPC_ERROR_NONE;
+}
+
+grpc_error* grpc_http_parser_eof(grpc_http_parser* parser) {
+ if (parser->state != GRPC_HTTP_BODY) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Did not finish headers");
+ }
+ return GRPC_ERROR_NONE;
+}
diff --git a/contrib/libs/grpc/src/core/lib/http/parser.h b/contrib/libs/grpc/src/core/lib/http/parser.h
index 2da21903e63..28b4f974fa1 100644
--- a/contrib/libs/grpc/src/core/lib/http/parser.h
+++ b/contrib/libs/grpc/src/core/lib/http/parser.h
@@ -1,28 +1,28 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_HTTP_PARSER_H
#define GRPC_CORE_LIB_HTTP_PARSER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/error.h"
/* Maximum length of a header string of the form 'Key: Value\r\n' */
@@ -30,8 +30,8 @@
/* A single header to be passed in a request */
typedef struct grpc_http_header {
- char* key;
- char* value;
+ char* key;
+ char* value;
} grpc_http_header;
typedef enum {
@@ -54,17 +54,17 @@ typedef enum {
/* A request */
typedef struct grpc_http_request {
/* Method of the request (e.g. GET, POST) */
- char* method;
+ char* method;
/* The path of the resource to fetch */
- char* path;
+ char* path;
/* HTTP version to use */
grpc_http_version version;
/* Headers attached to the request */
size_t hdr_count;
- grpc_http_header* hdrs;
+ grpc_http_header* hdrs;
/* Body: length and contents; contents are NOT null-terminated */
size_t body_length;
- char* body;
+ char* body;
} grpc_http_request;
/* A response */
@@ -84,9 +84,9 @@ struct grpc_http_parser {
grpc_http_type type;
union {
- grpc_http_response* response;
- grpc_http_request* request;
- void* request_or_response;
+ grpc_http_response* response;
+ grpc_http_request* request;
+ void* request_or_response;
} http;
size_t body_capacity;
size_t hdr_capacity;
@@ -95,19 +95,19 @@ struct grpc_http_parser {
size_t cur_line_length;
size_t cur_line_end_length;
};
-void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type,
- void* request_or_response);
-void grpc_http_parser_destroy(grpc_http_parser* parser);
+void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type,
+ void* request_or_response);
+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,
- size_t* start_of_body);
-grpc_error* grpc_http_parser_eof(grpc_http_parser* parser);
+ size_t* start_of_body);
+grpc_error* grpc_http_parser_eof(grpc_http_parser* parser);
-void grpc_http_request_destroy(grpc_http_request* request);
-void grpc_http_response_destroy(grpc_http_response* response);
+void grpc_http_request_destroy(grpc_http_request* request);
+void grpc_http_response_destroy(grpc_http_response* response);
-extern grpc_core::TraceFlag grpc_http1_trace;
+extern grpc_core::TraceFlag grpc_http1_trace;
#endif /* GRPC_CORE_LIB_HTTP_PARSER_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/block_annotate.h b/contrib/libs/grpc/src/core/lib/iomgr/block_annotate.h
index a57873aabb2..b99423b7f24 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/block_annotate.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/block_annotate.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_BLOCK_ANNOTATE_H
-#define GRPC_CORE_LIB_IOMGR_BLOCK_ANNOTATE_H
-
-void gpr_thd_start_blocking_region();
-void gpr_thd_end_blocking_region();
-
-/* These annotations identify the beginning and end of regions where
- the code may block for reasons other than synchronization functions.
- These include poll, epoll, and getaddrinfo. */
-
-#ifdef GRPC_SCHEDULING_MARK_BLOCKING_REGION
-#define GRPC_SCHEDULING_START_BLOCKING_REGION \
- do { \
- gpr_thd_start_blocking_region(); \
- } while (0)
-#define GRPC_SCHEDULING_END_BLOCKING_REGION \
- do { \
- gpr_thd_end_blocking_region(); \
- grpc_core::ExecCtx::Get()->InvalidateNow(); \
- } while (0)
-#define GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX \
- do { \
- gpr_thd_end_blocking_region(); \
- } while (0)
-
-#else
-#define GRPC_SCHEDULING_START_BLOCKING_REGION \
- do { \
- } while (0)
-#define GRPC_SCHEDULING_END_BLOCKING_REGION \
- do { \
- grpc_core::ExecCtx::Get()->InvalidateNow(); \
- } while (0)
-#define GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX \
- do { \
- } while (0)
-#endif
-
-#endif /* GRPC_CORE_LIB_IOMGR_BLOCK_ANNOTATE_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_IOMGR_BLOCK_ANNOTATE_H
+#define GRPC_CORE_LIB_IOMGR_BLOCK_ANNOTATE_H
+
+void gpr_thd_start_blocking_region();
+void gpr_thd_end_blocking_region();
+
+/* These annotations identify the beginning and end of regions where
+ the code may block for reasons other than synchronization functions.
+ These include poll, epoll, and getaddrinfo. */
+
+#ifdef GRPC_SCHEDULING_MARK_BLOCKING_REGION
+#define GRPC_SCHEDULING_START_BLOCKING_REGION \
+ do { \
+ gpr_thd_start_blocking_region(); \
+ } while (0)
+#define GRPC_SCHEDULING_END_BLOCKING_REGION \
+ do { \
+ gpr_thd_end_blocking_region(); \
+ grpc_core::ExecCtx::Get()->InvalidateNow(); \
+ } while (0)
+#define GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX \
+ do { \
+ gpr_thd_end_blocking_region(); \
+ } while (0)
+
+#else
+#define GRPC_SCHEDULING_START_BLOCKING_REGION \
+ do { \
+ } while (0)
+#define GRPC_SCHEDULING_END_BLOCKING_REGION \
+ do { \
+ grpc_core::ExecCtx::Get()->InvalidateNow(); \
+ } while (0)
+#define GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX \
+ do { \
+ } while (0)
+#endif
+
+#endif /* GRPC_CORE_LIB_IOMGR_BLOCK_ANNOTATE_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 ed0ae174887..6f61f8734e2 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc
@@ -1,48 +1,48 @@
-/*
- *
- * 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/iomgr/call_combiner.h"
-
-#include <inttypes.h>
-
-#include <grpc/support/log.h>
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/profiling/timers.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/call_combiner.h"
+
+#include <inttypes.h>
+
+#include <grpc/support/log.h>
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/profiling/timers.h"
+
namespace grpc_core {
-
+
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;
-}
-
+ if (cancel_state & 1) {
+ return (grpc_error*)(cancel_state & ~static_cast<gpr_atm>(1));
+ }
+ return GRPC_ERROR_NONE;
+}
+
gpr_atm EncodeCancelStateError(grpc_error* error) {
- return static_cast<gpr_atm>(1) | (gpr_atm)error;
-}
-
+ return static_cast<gpr_atm>(1) | (gpr_atm)error;
+}
+
} // namespace
CallCombiner::CallCombiner() {
@@ -99,158 +99,158 @@ void CallCombiner::ScheduleClosure(grpc_closure* closure, grpc_error* error) {
#endif
}
-#ifndef NDEBUG
+#ifndef NDEBUG
#define DEBUG_ARGS const char *file, int line,
-#define DEBUG_FMT_STR "%s:%d: "
-#define DEBUG_FMT_ARGS , file, line
-#else
-#define DEBUG_ARGS
-#define DEBUG_FMT_STR
-#define DEBUG_FMT_ARGS
-#endif
-
+#define DEBUG_FMT_STR "%s:%d: "
+#define DEBUG_FMT_ARGS , file, line
+#else
+#define DEBUG_ARGS
+#define DEBUG_FMT_STR
+#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)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"==> CallCombiner::Start() [%p] closure=%p [" DEBUG_FMT_STR
- "%s] error=%s",
+ "%s] error=%s",
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)) {
- gpr_log(GPR_INFO, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size,
- prev_size + 1);
- }
- GRPC_STATS_INC_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS();
- if (prev_size == 0) {
- GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED();
- GPR_TIMER_MARK("call_combiner_initiate", 0);
+ gpr_log(GPR_INFO, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size,
+ prev_size + 1);
+ }
+ GRPC_STATS_INC_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS();
+ 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)) {
- gpr_log(GPR_INFO, " EXECUTING IMMEDIATELY");
- }
- // Queue was empty, so execute this closure immediately.
+ gpr_log(GPR_INFO, " EXECUTING IMMEDIATELY");
+ }
+ // Queue was empty, so execute this closure immediately.
ScheduleClosure(closure, error);
- } else {
+ } else {
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;
+ 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));
- }
-}
-
+ }
+}
+
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)) {
- gpr_log(GPR_INFO, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size,
- prev_size - 1);
- }
- GPR_ASSERT(prev_size >= 1);
- if (prev_size > 1) {
- while (true) {
+ 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)) {
- gpr_log(GPR_INFO, " checking queue");
- }
- bool empty;
+ gpr_log(GPR_INFO, " checking queue");
+ }
+ bool 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
+ 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)) {
- gpr_log(GPR_INFO, " queue returned no result; checking again");
- }
- continue;
- }
+ gpr_log(GPR_INFO, " queue returned no result; checking again");
+ }
+ continue;
+ }
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));
- }
+ 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);
- break;
- }
+ break;
+ }
} else if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
- gpr_log(GPR_INFO, " queue empty");
- }
-}
-
+ gpr_log(GPR_INFO, " queue empty");
+ }
+}
+
void CallCombiner::SetNotifyOnCancel(grpc_closure* closure) {
- GRPC_STATS_INC_CALL_COMBINER_SET_NOTIFY_ON_CANCEL();
- while (true) {
- // Decode original state.
+ 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);
- // If error is set, invoke the cancellation closure immediately.
- // Otherwise, store the new closure.
- if (original_error != GRPC_ERROR_NONE) {
+ // 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)) {
- gpr_log(GPR_INFO,
- "call_combiner=%p: scheduling notify_on_cancel callback=%p "
- "for pre-existing cancellation",
+ gpr_log(GPR_INFO,
+ "call_combiner=%p: scheduling notify_on_cancel callback=%p "
+ "for pre-existing cancellation",
this, closure);
- }
+ }
ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(original_error));
- break;
- } else {
+ break;
+ } else {
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",
+ gpr_log(GPR_INFO, "call_combiner=%p: setting notify_on_cancel=%p",
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 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)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"call_combiner=%p: scheduling old cancel callback=%p", this,
closure);
- }
+ }
ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
- }
- break;
- }
- }
- // cas failed, try again.
- }
-}
-
+ }
+ break;
+ }
+ }
+ // cas failed, try again.
+ }
+}
+
void CallCombiner::Cancel(grpc_error* error) {
- GRPC_STATS_INC_CALL_COMBINER_CANCELLED();
- while (true) {
+ 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);
- if (original_error != GRPC_ERROR_NONE) {
- GRPC_ERROR_UNREF(error);
- break;
- }
+ if (original_error != GRPC_ERROR_NONE) {
+ GRPC_ERROR_UNREF(error);
+ break;
+ }
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 (original_state != 0) {
+ grpc_closure* notify_on_cancel = (grpc_closure*)original_state;
if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) {
- gpr_log(GPR_INFO,
- "call_combiner=%p: scheduling notify_on_cancel callback=%p",
+ gpr_log(GPR_INFO,
+ "call_combiner=%p: scheduling notify_on_cancel callback=%p",
this, notify_on_cancel);
- }
+ }
ExecCtx::Run(DEBUG_LOCATION, notify_on_cancel, GRPC_ERROR_REF(error));
- }
- break;
- }
- // cas failed, try again.
- }
-}
+ }
+ break;
+ }
+ // cas failed, try again.
+ }
+}
} // 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 aed847c9728..6299b364514 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h
@@ -1,50 +1,50 @@
-/*
- *
- * 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_IOMGR_CALL_COMBINER_H
-#define GRPC_CORE_LIB_IOMGR_CALL_COMBINER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stddef.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_CALL_COMBINER_H
+#define GRPC_CORE_LIB_IOMGR_CALL_COMBINER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stddef.h>
+
#include "y_absl/container/inlined_vector.h"
-#include <grpc/support/atm.h>
-
+#include <grpc/support/atm.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/closure.h"
#include "src/core/lib/iomgr/dynamic_annotations.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.
-//
-// It requires the callback (or, in the common case where the callback
-// actually kicks off a chain of callbacks, the last callback in that
-// chain) to explicitly indicate (by calling GRPC_CALL_COMBINER_STOP())
-// when it is done with the action that was kicked off by the original
-// callback.
-
+
+// A simple, lock-free mechanism for serializing activity related to a
+// single call. This is similar to a combiner but is more lightweight.
+//
+// It requires the callback (or, in the common case where the callback
+// actually kicks off a chain of callbacks, the last callback in that
+// chain) to explicitly indicate (by calling GRPC_CALL_COMBINER_STOP())
+// 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 {
@@ -111,9 +111,9 @@ class CallCombiner {
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).
+ // 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;
#ifdef GRPC_TSAN_ENABLED
// A fake ref-counted lock that is kept alive after the destruction of
@@ -214,4 +214,4 @@ class CallCombinerClosureList {
} // namespace grpc_core
-#endif /* GRPC_CORE_LIB_IOMGR_CALL_COMBINER_H */
+#endif /* GRPC_CORE_LIB_IOMGR_CALL_COMBINER_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/closure.h b/contrib/libs/grpc/src/core/lib/iomgr/closure.h
index 6bb65340d1a..2cdbff32974 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/closure.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/closure.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,43 +21,43 @@
#include <grpc/support/port_platform.h>
-#include <assert.h>
+#include <assert.h>
#include <stdbool.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.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/iomgr/error.h"
-#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/profiling/timers.h"
struct grpc_closure;
typedef struct grpc_closure grpc_closure;
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_closure;
-
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_closure;
+
typedef struct grpc_closure_list {
- grpc_closure* head;
- grpc_closure* tail;
+ grpc_closure* head;
+ grpc_closure* tail;
} grpc_closure_list;
/** gRPC Callback definition.
*
* \param arg Arbitrary input.
* \param error GRPC_ERROR_NONE if no error occurred, otherwise some grpc_error
- * describing what went wrong.
- * Error contract: it is not the cb's job to unref this error;
- * the closure scheduler will do that after the cb returns */
-typedef void (*grpc_iomgr_cb_func)(void* arg, grpc_error* error);
+ * describing what went wrong.
+ * Error contract: it is not the cb's job to unref this error;
+ * the closure scheduler will do that after the cb returns */
+typedef void (*grpc_iomgr_cb_func)(void* arg, grpc_error* error);
/** A closure over a grpc_iomgr_cb_func. */
struct grpc_closure {
/** Once queued, next indicates the next queued closure; before then, scratch
* space */
union {
- grpc_closure* next;
+ grpc_closure* next;
grpc_core::ManualConstructor<
grpc_core::MultiProducerSingleConsumerQueue::Node>
mpscq_node;
@@ -68,160 +68,160 @@ struct grpc_closure {
grpc_iomgr_cb_func cb;
/** Arguments to be passed to "cb". */
- void* cb_arg;
+ void* cb_arg;
/** Once queued, the result of the closure. Before then: scratch space */
union {
- grpc_error* error;
+ grpc_error* error;
uintptr_t scratch;
} error_data;
-
-// extra tracing and debugging for grpc_closure. This incurs a decent amount of
-// overhead per closure, so it must be enabled at compile time.
-#ifndef NDEBUG
- bool scheduled;
- bool run; // true = run, false = scheduled
- const char* file_created;
- int line_created;
- const char* file_initiated;
- int line_initiated;
-#endif
+
+// extra tracing and debugging for grpc_closure. This incurs a decent amount of
+// overhead per closure, so it must be enabled at compile time.
+#ifndef NDEBUG
+ bool scheduled;
+ bool run; // true = run, false = scheduled
+ const char* file_created;
+ int line_created;
+ const char* file_initiated;
+ int line_initiated;
+#endif
};
-#ifndef NDEBUG
-inline grpc_closure* grpc_closure_init(const char* file, int line,
- grpc_closure* 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) {
-#else
-inline grpc_closure* grpc_closure_init(grpc_closure* closure,
+#else
+inline grpc_closure* grpc_closure_init(grpc_closure* closure,
grpc_iomgr_cb_func cb, void* cb_arg) {
-#endif
- closure->cb = cb;
- closure->cb_arg = cb_arg;
+#endif
+ closure->cb = cb;
+ closure->cb_arg = cb_arg;
closure->error_data.error = GRPC_ERROR_NONE;
-#ifndef NDEBUG
- closure->scheduled = false;
- closure->file_initiated = nullptr;
- closure->line_initiated = 0;
- closure->run = false;
- closure->file_created = file;
- closure->line_created = line;
-#endif
- return closure;
-}
-
+#ifndef NDEBUG
+ closure->scheduled = false;
+ closure->file_initiated = nullptr;
+ closure->line_initiated = 0;
+ closure->run = false;
+ closure->file_created = file;
+ closure->line_created = line;
+#endif
+ return 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) \
+#ifndef NDEBUG
+#define GRPC_CLOSURE_INIT(closure, cb, cb_arg, scheduler) \
grpc_closure_init(__FILE__, __LINE__, closure, cb, cb_arg)
-#else
-#define GRPC_CLOSURE_INIT(closure, cb, cb_arg, scheduler) \
+#else
+#define GRPC_CLOSURE_INIT(closure, cb, cb_arg, scheduler) \
grpc_closure_init(closure, cb, cb_arg)
-#endif
-
-namespace closure_impl {
+#endif
+namespace closure_impl {
+
struct wrapped_closure {
- grpc_iomgr_cb_func cb;
- void* cb_arg;
- grpc_closure wrapper;
+ grpc_iomgr_cb_func cb;
+ void* cb_arg;
+ grpc_closure wrapper;
};
-inline void closure_wrapper(void* arg, grpc_error* error) {
- wrapped_closure* wc = static_cast<wrapped_closure*>(arg);
- grpc_iomgr_cb_func cb = wc->cb;
- void* cb_arg = wc->cb_arg;
- gpr_free(wc);
- cb(cb_arg, error);
-}
-
-} // namespace closure_impl
-
-#ifndef NDEBUG
-inline grpc_closure* grpc_closure_create(const char* file, int line,
+inline void closure_wrapper(void* arg, grpc_error* error) {
+ wrapped_closure* wc = static_cast<wrapped_closure*>(arg);
+ grpc_iomgr_cb_func cb = wc->cb;
+ void* cb_arg = wc->cb_arg;
+ gpr_free(wc);
+ cb(cb_arg, error);
+}
+
+} // namespace closure_impl
+
+#ifndef NDEBUG
+inline grpc_closure* grpc_closure_create(const char* file, int line,
grpc_iomgr_cb_func cb, void* cb_arg) {
-#else
+#else
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
+#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);
-#else
+#else
grpc_closure_init(&wc->wrapper, closure_impl::closure_wrapper, wc);
-#endif
- return &wc->wrapper;
-}
-
+#endif
+ return &wc->wrapper;
+}
+
/* Create a heap allocated closure: try to avoid except for very rare events */
-#ifndef NDEBUG
-#define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \
+#ifndef NDEBUG
+#define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \
grpc_closure_create(__FILE__, __LINE__, cb, cb_arg)
-#else
-#define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \
+#else
+#define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \
grpc_closure_create(cb, cb_arg)
-#endif
+#endif
#define GRPC_CLOSURE_LIST_INIT \
- { nullptr, nullptr }
+ { nullptr, nullptr }
-inline void grpc_closure_list_init(grpc_closure_list* closure_list) {
- closure_list->head = closure_list->tail = nullptr;
-}
+inline void grpc_closure_list_init(grpc_closure_list* closure_list) {
+ closure_list->head = closure_list->tail = nullptr;
+}
/** add \a closure to the end of \a list
- and set \a closure's result to \a error
- Returns true if \a list becomes non-empty */
-inline bool grpc_closure_list_append(grpc_closure_list* closure_list,
- grpc_closure* closure, grpc_error* error) {
- if (closure == nullptr) {
- GRPC_ERROR_UNREF(error);
- return false;
- }
- closure->error_data.error = error;
- closure->next_data.next = nullptr;
- bool was_empty = (closure_list->head == nullptr);
- if (was_empty) {
- closure_list->head = closure;
- } else {
- closure_list->tail->next_data.next = closure;
- }
- closure_list->tail = closure;
- return was_empty;
-}
+ and set \a closure's result to \a error
+ Returns true if \a list becomes non-empty */
+inline bool grpc_closure_list_append(grpc_closure_list* closure_list,
+ grpc_closure* closure, grpc_error* error) {
+ if (closure == nullptr) {
+ GRPC_ERROR_UNREF(error);
+ return false;
+ }
+ closure->error_data.error = error;
+ closure->next_data.next = nullptr;
+ bool was_empty = (closure_list->head == nullptr);
+ if (was_empty) {
+ closure_list->head = closure;
+ } else {
+ closure_list->tail->next_data.next = closure;
+ }
+ closure_list->tail = closure;
+ return was_empty;
+}
/** force all success bits in \a list to false */
-inline void grpc_closure_list_fail_all(grpc_closure_list* list,
- grpc_error* forced_failure) {
- for (grpc_closure* c = list->head; c != nullptr; c = c->next_data.next) {
- if (c->error_data.error == GRPC_ERROR_NONE) {
- c->error_data.error = GRPC_ERROR_REF(forced_failure);
- }
- }
- GRPC_ERROR_UNREF(forced_failure);
-}
+inline void grpc_closure_list_fail_all(grpc_closure_list* list,
+ grpc_error* forced_failure) {
+ for (grpc_closure* c = list->head; c != nullptr; c = c->next_data.next) {
+ if (c->error_data.error == GRPC_ERROR_NONE) {
+ c->error_data.error = GRPC_ERROR_REF(forced_failure);
+ }
+ }
+ GRPC_ERROR_UNREF(forced_failure);
+}
/** append all closures from \a src to \a dst and empty \a src. */
-inline void grpc_closure_list_move(grpc_closure_list* src,
- grpc_closure_list* dst) {
- if (src->head == nullptr) {
- return;
- }
- if (dst->head == nullptr) {
- *dst = *src;
- } else {
- dst->tail->next_data.next = src->head;
- dst->tail = src->tail;
- }
- src->head = src->tail = nullptr;
-}
+inline void grpc_closure_list_move(grpc_closure_list* src,
+ grpc_closure_list* dst) {
+ if (src->head == nullptr) {
+ return;
+ }
+ if (dst->head == nullptr) {
+ *dst = *src;
+ } else {
+ dst->tail->next_data.next = src->head;
+ dst->tail = src->tail;
+ }
+ src->head = src->tail = nullptr;
+}
/** return whether \a list is empty. */
-inline bool grpc_closure_list_empty(grpc_closure_list closure_list) {
- return closure_list.head == nullptr;
-}
+inline bool grpc_closure_list_empty(grpc_closure_list closure_list) {
+ return closure_list.head == nullptr;
+}
namespace grpc_core {
class Closure {
@@ -233,23 +233,23 @@ class Closure {
GRPC_ERROR_UNREF(error);
return;
}
-#ifndef NDEBUG
+#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);
-#endif
+#endif
closure->cb(closure->cb_arg, error);
-#ifndef NDEBUG
+#ifndef NDEBUG
if (grpc_trace_closure.enabled()) {
gpr_log(GPR_DEBUG, "closure %p finished", closure);
- }
-#endif
- GRPC_ERROR_UNREF(error);
- }
+ }
+#endif
+ GRPC_ERROR_UNREF(error);
+ }
};
} // 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 4b85766aef6..a63c9a4632a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc
@@ -1,339 +1,339 @@
-/*
- *
- * 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/combiner.h"
-
-#include <assert.h>
-#include <inttypes.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/debug/stats.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/combiner.h"
+
+#include <assert.h>
+#include <inttypes.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gprpp/mpscq.h"
-#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/profiling/timers.h"
-
+#include "src/core/lib/profiling/timers.h"
+
grpc_core::DebugOnlyTraceFlag grpc_combiner_trace(false, "combiner");
-
-#define GRPC_COMBINER_TRACE(fn) \
- do { \
- if (grpc_combiner_trace.enabled()) { \
- fn; \
- } \
- } while (0)
-
-#define STATE_UNORPHANED 1
-#define STATE_ELEM_COUNT_LOW_BIT 2
-
+
+#define GRPC_COMBINER_TRACE(fn) \
+ do { \
+ if (grpc_combiner_trace.enabled()) { \
+ fn; \
+ } \
+ } while (0)
+
+#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 offload(void* arg, 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();
- gpr_ref_init(&lock->refs, 1);
- gpr_atm_no_barrier_store(&lock->state, STATE_UNORPHANED);
- grpc_closure_list_init(&lock->final_list);
+ 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_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p create", lock));
- return lock;
-}
-
+ GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p create", lock));
+ return 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);
+ GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p really_destroy", lock));
+ GPR_ASSERT(gpr_atm_no_barrier_load(&lock->state) == 0);
delete 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));
- if (old_state == 1) {
- really_destroy(lock);
- }
-}
-
-#ifndef NDEBUG
-#define GRPC_COMBINER_DEBUG_SPAM(op, delta) \
- if (grpc_combiner_trace.enabled()) { \
- gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, \
- "C:%p %s %" PRIdPTR " --> %" PRIdPTR " %s", lock, (op), \
- gpr_atm_no_barrier_load(&lock->refs.count), \
- gpr_atm_no_barrier_load(&lock->refs.count) + (delta), reason); \
- }
-#else
-#define GRPC_COMBINER_DEBUG_SPAM(op, delta)
-#endif
-
+ 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));
+ if (old_state == 1) {
+ really_destroy(lock);
+ }
+}
+
+#ifndef NDEBUG
+#define GRPC_COMBINER_DEBUG_SPAM(op, delta) \
+ if (grpc_combiner_trace.enabled()) { \
+ gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, \
+ "C:%p %s %" PRIdPTR " --> %" PRIdPTR " %s", lock, (op), \
+ gpr_atm_no_barrier_load(&lock->refs.count), \
+ gpr_atm_no_barrier_load(&lock->refs.count) + (delta), reason); \
+ }
+#else
+#define GRPC_COMBINER_DEBUG_SPAM(op, delta)
+#endif
+
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_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_COMBINER_DEBUG_SPAM(" REF", 1);
- gpr_ref(&lock->refs);
- return lock;
-}
-
+ GRPC_COMBINER_DEBUG_SPAM(" REF", 1);
+ gpr_ref(&lock->refs);
+ return 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 =
- grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = lock;
- } else {
- grpc_core::ExecCtx::Get()
- ->combiner_data()
- ->last_combiner->next_combiner_on_this_exec_ctx = lock;
- grpc_core::ExecCtx::Get()->combiner_data()->last_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 =
+ grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = lock;
+ } else {
+ grpc_core::ExecCtx::Get()
+ ->combiner_data()
+ ->last_combiner->next_combiner_on_this_exec_ctx = lock;
+ grpc_core::ExecCtx::Get()->combiner_data()->last_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;
- if (lock->next_combiner_on_this_exec_ctx == nullptr) {
- grpc_core::ExecCtx::Get()->combiner_data()->last_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;
+ if (lock->next_combiner_on_this_exec_ctx == nullptr) {
+ grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = lock;
+ }
+}
+
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);
- GRPC_COMBINER_TRACE(gpr_log(GPR_INFO,
- "C:%p grpc_combiner_execute c=%p last=%" PRIdPTR,
- lock, cl, last));
- if (last == 1) {
- GRPC_STATS_INC_COMBINER_LOCKS_INITIATED();
- GPR_TIMER_MARK("combiner.initiated", 0);
- gpr_atm_no_barrier_store(&lock->initiating_exec_ctx_or_null,
- (gpr_atm)grpc_core::ExecCtx::Get());
- // first element on this list: add it to the list of combiner locks
- // executing within this exec_ctx
- push_last_on_exec_ctx(lock);
- } else {
- // there may be a race with setting here: if that happens, we may delay
- // offload for one or two actions, and that's fine
- gpr_atm initiator =
- gpr_atm_no_barrier_load(&lock->initiating_exec_ctx_or_null);
- if (initiator != 0 && initiator != (gpr_atm)grpc_core::ExecCtx::Get()) {
- gpr_atm_no_barrier_store(&lock->initiating_exec_ctx_or_null, 0);
- }
- }
- GPR_ASSERT(last & STATE_UNORPHANED); // ensure lock has not been destroyed
- assert(cl->cb);
- cl->error_data.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);
+ GRPC_COMBINER_TRACE(gpr_log(GPR_INFO,
+ "C:%p grpc_combiner_execute c=%p last=%" PRIdPTR,
+ lock, cl, last));
+ if (last == 1) {
+ GRPC_STATS_INC_COMBINER_LOCKS_INITIATED();
+ GPR_TIMER_MARK("combiner.initiated", 0);
+ gpr_atm_no_barrier_store(&lock->initiating_exec_ctx_or_null,
+ (gpr_atm)grpc_core::ExecCtx::Get());
+ // first element on this list: add it to the list of combiner locks
+ // executing within this exec_ctx
+ push_last_on_exec_ctx(lock);
+ } else {
+ // there may be a race with setting here: if that happens, we may delay
+ // offload for one or two actions, and that's fine
+ gpr_atm initiator =
+ gpr_atm_no_barrier_load(&lock->initiating_exec_ctx_or_null);
+ if (initiator != 0 && initiator != (gpr_atm)grpc_core::ExecCtx::Get()) {
+ gpr_atm_no_barrier_store(&lock->initiating_exec_ctx_or_null, 0);
+ }
+ }
+ 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());
-}
-
-static void move_next() {
- grpc_core::ExecCtx::Get()->combiner_data()->active_combiner =
- grpc_core::ExecCtx::Get()
- ->combiner_data()
- ->active_combiner->next_combiner_on_this_exec_ctx;
- if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner == nullptr) {
- grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = nullptr;
- }
-}
-
+}
+
+static void move_next() {
+ grpc_core::ExecCtx::Get()->combiner_data()->active_combiner =
+ grpc_core::ExecCtx::Get()
+ ->combiner_data()
+ ->active_combiner->next_combiner_on_this_exec_ctx;
+ if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner == nullptr) {
+ grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = nullptr;
+ }
+}
+
static void offload(void* arg, grpc_error* /*error*/) {
grpc_core::Combiner* lock = static_cast<grpc_core::Combiner*>(arg);
- push_last_on_exec_ctx(lock);
-}
-
+ push_last_on_exec_ctx(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_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);
-}
-
-bool grpc_combiner_continue_exec_ctx() {
- GPR_TIMER_SCOPE("combiner.continue_exec_ctx", 0);
+}
+
+bool grpc_combiner_continue_exec_ctx() {
+ GPR_TIMER_SCOPE("combiner.continue_exec_ctx", 0);
grpc_core::Combiner* lock =
- grpc_core::ExecCtx::Get()->combiner_data()->active_combiner;
- if (lock == nullptr) {
- return false;
- }
-
- bool contended =
- gpr_atm_no_barrier_load(&lock->initiating_exec_ctx_or_null) == 0;
-
- GRPC_COMBINER_TRACE(gpr_log(GPR_INFO,
- "C:%p grpc_combiner_continue_exec_ctx "
- "contended=%d "
- "exec_ctx_ready_to_finish=%d "
- "time_to_execute_final_list=%d",
- lock, contended,
- grpc_core::ExecCtx::Get()->IsReadyToFinish(),
- lock->time_to_execute_final_list));
-
+ grpc_core::ExecCtx::Get()->combiner_data()->active_combiner;
+ if (lock == nullptr) {
+ return false;
+ }
+
+ bool contended =
+ gpr_atm_no_barrier_load(&lock->initiating_exec_ctx_or_null) == 0;
+
+ GRPC_COMBINER_TRACE(gpr_log(GPR_INFO,
+ "C:%p grpc_combiner_continue_exec_ctx "
+ "contended=%d "
+ "exec_ctx_ready_to_finish=%d "
+ "time_to_execute_final_list=%d",
+ lock, contended,
+ grpc_core::ExecCtx::Get()->IsReadyToFinish(),
+ lock->time_to_execute_final_list));
+
// 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
- if (contended && grpc_core::ExecCtx::Get()->IsReadyToFinish() &&
+ if (contended && grpc_core::ExecCtx::Get()->IsReadyToFinish() &&
!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
- queue_offload(lock);
- return true;
- }
-
- if (!lock->time_to_execute_final_list ||
- // peek to see if something new has shown up, and execute that with
- // priority
- (gpr_atm_acq_load(&lock->state) >> 1) > 1) {
+ 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
+ queue_offload(lock);
+ return true;
+ }
+
+ if (!lock->time_to_execute_final_list ||
+ // 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_COMBINER_TRACE(
- gpr_log(GPR_INFO, "C:%p maybe_finish_one n=%p", lock, n));
- if (n == nullptr) {
- // queue is in an inconsistent state: use this as a cue that we should
- // go off and do something else for a while (and come back later)
- GPR_TIMER_MARK("delay_busy", 0);
- queue_offload(lock);
- return true;
- }
- GPR_TIMER_SCOPE("combiner.exec1", 0);
- grpc_closure* cl = reinterpret_cast<grpc_closure*>(n);
- grpc_error* cl_err = cl->error_data.error;
-#ifndef NDEBUG
- cl->scheduled = false;
-#endif
- cl->cb(cl->cb_arg, cl_err);
- GRPC_ERROR_UNREF(cl_err);
- } else {
- grpc_closure* c = lock->final_list.head;
- GPR_ASSERT(c != nullptr);
- grpc_closure_list_init(&lock->final_list);
- int loops = 0;
- while (c != nullptr) {
- GPR_TIMER_SCOPE("combiner.exec_1final", 0);
- GRPC_COMBINER_TRACE(
- gpr_log(GPR_INFO, "C:%p execute_final[%d] c=%p", lock, loops, c));
- grpc_closure* next = c->next_data.next;
- grpc_error* error = c->error_data.error;
-#ifndef NDEBUG
- c->scheduled = false;
-#endif
- c->cb(c->cb_arg, error);
- GRPC_ERROR_UNREF(error);
- c = next;
- }
- }
-
- GPR_TIMER_MARK("unref", 0);
- move_next();
- lock->time_to_execute_final_list = false;
- gpr_atm old_state =
- gpr_atm_full_fetch_add(&lock->state, -STATE_ELEM_COUNT_LOW_BIT);
- GRPC_COMBINER_TRACE(
- gpr_log(GPR_INFO, "C:%p finish old_state=%" PRIdPTR, lock, old_state));
-// Define a macro to ease readability of the following switch statement.
-#define OLD_STATE_WAS(orphaned, elem_count) \
- (((orphaned) ? 0 : STATE_UNORPHANED) | \
- ((elem_count)*STATE_ELEM_COUNT_LOW_BIT))
- // Depending on what the previous state was, we need to perform different
- // actions.
- switch (old_state) {
- default:
- // we have multiple queued work items: just continue executing them
- break;
- case OLD_STATE_WAS(false, 2):
- case OLD_STATE_WAS(true, 2):
- // we're down to one queued item: if it's the final list we should do that
- if (!grpc_closure_list_empty(lock->final_list)) {
- lock->time_to_execute_final_list = true;
- }
- break;
- case OLD_STATE_WAS(false, 1):
- // had one count, one unorphaned --> unlocked unorphaned
- return true;
- case OLD_STATE_WAS(true, 1):
- // and one count, one orphaned --> unlocked and orphaned
- really_destroy(lock);
- return true;
- case OLD_STATE_WAS(false, 0):
- case OLD_STATE_WAS(true, 0):
- // these values are illegal - representing an already unlocked or
- // deleted lock
- GPR_UNREACHABLE_CODE(return true);
- }
- push_first_on_exec_ctx(lock);
- return true;
-}
-
-static void enqueue_finally(void* closure, grpc_error* error);
-
+ GRPC_COMBINER_TRACE(
+ gpr_log(GPR_INFO, "C:%p maybe_finish_one n=%p", lock, n));
+ if (n == nullptr) {
+ // queue is in an inconsistent state: use this as a cue that we should
+ // go off and do something else for a while (and come back later)
+ GPR_TIMER_MARK("delay_busy", 0);
+ queue_offload(lock);
+ return true;
+ }
+ GPR_TIMER_SCOPE("combiner.exec1", 0);
+ grpc_closure* cl = reinterpret_cast<grpc_closure*>(n);
+ grpc_error* cl_err = cl->error_data.error;
+#ifndef NDEBUG
+ cl->scheduled = false;
+#endif
+ cl->cb(cl->cb_arg, cl_err);
+ GRPC_ERROR_UNREF(cl_err);
+ } else {
+ grpc_closure* c = lock->final_list.head;
+ GPR_ASSERT(c != nullptr);
+ grpc_closure_list_init(&lock->final_list);
+ int loops = 0;
+ while (c != nullptr) {
+ GPR_TIMER_SCOPE("combiner.exec_1final", 0);
+ GRPC_COMBINER_TRACE(
+ gpr_log(GPR_INFO, "C:%p execute_final[%d] c=%p", lock, loops, c));
+ grpc_closure* next = c->next_data.next;
+ grpc_error* error = c->error_data.error;
+#ifndef NDEBUG
+ c->scheduled = false;
+#endif
+ c->cb(c->cb_arg, error);
+ GRPC_ERROR_UNREF(error);
+ c = next;
+ }
+ }
+
+ GPR_TIMER_MARK("unref", 0);
+ move_next();
+ lock->time_to_execute_final_list = false;
+ gpr_atm old_state =
+ gpr_atm_full_fetch_add(&lock->state, -STATE_ELEM_COUNT_LOW_BIT);
+ GRPC_COMBINER_TRACE(
+ gpr_log(GPR_INFO, "C:%p finish old_state=%" PRIdPTR, lock, old_state));
+// Define a macro to ease readability of the following switch statement.
+#define OLD_STATE_WAS(orphaned, elem_count) \
+ (((orphaned) ? 0 : STATE_UNORPHANED) | \
+ ((elem_count)*STATE_ELEM_COUNT_LOW_BIT))
+ // Depending on what the previous state was, we need to perform different
+ // actions.
+ switch (old_state) {
+ default:
+ // we have multiple queued work items: just continue executing them
+ break;
+ case OLD_STATE_WAS(false, 2):
+ case OLD_STATE_WAS(true, 2):
+ // we're down to one queued item: if it's the final list we should do that
+ if (!grpc_closure_list_empty(lock->final_list)) {
+ lock->time_to_execute_final_list = true;
+ }
+ break;
+ case OLD_STATE_WAS(false, 1):
+ // had one count, one unorphaned --> unlocked unorphaned
+ return true;
+ case OLD_STATE_WAS(true, 1):
+ // and one count, one orphaned --> unlocked and orphaned
+ really_destroy(lock);
+ return true;
+ case OLD_STATE_WAS(false, 0):
+ case OLD_STATE_WAS(true, 0):
+ // these values are illegal - representing an already unlocked or
+ // deleted lock
+ GPR_UNREACHABLE_CODE(return true);
+ }
+ push_first_on_exec_ctx(lock);
+ return true;
+}
+
+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);
- GPR_TIMER_SCOPE("combiner.execute_finally", 0);
- GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS();
- GRPC_COMBINER_TRACE(gpr_log(
- GPR_INFO, "C:%p grpc_combiner_execute_finally c=%p; ac=%p", lock, closure,
- grpc_core::ExecCtx::Get()->combiner_data()->active_combiner));
- if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner != lock) {
- GPR_TIMER_MARK("slowpath", 0);
+ GPR_TIMER_SCOPE("combiner.execute_finally", 0);
+ GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS();
+ GRPC_COMBINER_TRACE(gpr_log(
+ GPR_INFO, "C:%p grpc_combiner_execute_finally c=%p; ac=%p", lock, closure,
+ 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);
- return;
- }
-
- if (grpc_closure_list_empty(lock->final_list)) {
- gpr_atm_full_fetch_add(&lock->state, STATE_ELEM_COUNT_LOW_BIT);
- }
- grpc_closure_list_append(&lock->final_list, closure, error);
-}
-
-static void enqueue_finally(void* closure, grpc_error* error) {
+ return;
+ }
+
+ if (grpc_closure_list_empty(lock->final_list)) {
+ gpr_atm_full_fetch_add(&lock->state, STATE_ELEM_COUNT_LOW_BIT);
+ }
+ grpc_closure_list_append(&lock->final_list, closure, error);
+}
+
+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));
-}
-
+}
+
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);
-}
+}
} // 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 32712066bef..d5e03265b8a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/combiner.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/combiner.h
@@ -1,30 +1,30 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_COMBINER_H
#define GRPC_CORE_LIB_IOMGR_COMBINER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stddef.h>
#include <grpc/support/atm.h>
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/exec_ctx.h"
namespace grpc_core {
@@ -61,27 +61,27 @@ class Combiner {
// Initialize the lock, with an optional workqueue to shift load to when
// necessary
grpc_core::Combiner* grpc_combiner_create(void);
-
-#ifndef NDEBUG
-#define GRPC_COMBINER_DEBUG_ARGS \
- , const char *file, int line, const char *reason
-#define GRPC_COMBINER_REF(combiner, reason) \
- grpc_combiner_ref((combiner), __FILE__, __LINE__, (reason))
-#define GRPC_COMBINER_UNREF(combiner, reason) \
- grpc_combiner_unref((combiner), __FILE__, __LINE__, (reason))
-#else
-#define GRPC_COMBINER_DEBUG_ARGS
-#define GRPC_COMBINER_REF(combiner, reason) grpc_combiner_ref((combiner))
-#define GRPC_COMBINER_UNREF(combiner, reason) grpc_combiner_unref((combiner))
-#endif
-
-// Ref/unref the lock, for when we're sharing the lock ownership
-// Prefer to use the macros above
+
+#ifndef NDEBUG
+#define GRPC_COMBINER_DEBUG_ARGS \
+ , const char *file, int line, const char *reason
+#define GRPC_COMBINER_REF(combiner, reason) \
+ grpc_combiner_ref((combiner), __FILE__, __LINE__, (reason))
+#define GRPC_COMBINER_UNREF(combiner, reason) \
+ grpc_combiner_unref((combiner), __FILE__, __LINE__, (reason))
+#else
+#define GRPC_COMBINER_DEBUG_ARGS
+#define GRPC_COMBINER_REF(combiner, reason) grpc_combiner_ref((combiner))
+#define GRPC_COMBINER_UNREF(combiner, reason) grpc_combiner_unref((combiner))
+#endif
+
+// 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);
-bool grpc_combiner_continue_exec_ctx();
+bool grpc_combiner_continue_exec_ctx();
extern grpc_core::DebugOnlyTraceFlag grpc_combiner_trace;
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc
index 37e04001022..a92c3e8e350 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc
@@ -1,70 +1,70 @@
-/*
- *
- * 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/iomgr/endpoint.h"
-
-grpc_core::TraceFlag grpc_tcp_trace(false, "tcp");
-
-void grpc_endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
+/*
+ *
+ * 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/iomgr/endpoint.h"
+
+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);
-}
-
-void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
+}
+
+void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
grpc_closure* cb, void* arg) {
ep->vtable->write(ep, slices, cb, arg);
-}
-
-void grpc_endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
- ep->vtable->add_to_pollset(ep, pollset);
-}
-
-void grpc_endpoint_add_to_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set) {
- ep->vtable->add_to_pollset_set(ep, pollset_set);
-}
-
-void grpc_endpoint_delete_from_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set) {
- ep->vtable->delete_from_pollset_set(ep, pollset_set);
-}
-
-void grpc_endpoint_shutdown(grpc_endpoint* ep, grpc_error* why) {
- ep->vtable->shutdown(ep, why);
-}
-
-void grpc_endpoint_destroy(grpc_endpoint* ep) { ep->vtable->destroy(ep); }
-
+}
+
+void grpc_endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
+ ep->vtable->add_to_pollset(ep, pollset);
+}
+
+void grpc_endpoint_add_to_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set) {
+ ep->vtable->add_to_pollset_set(ep, pollset_set);
+}
+
+void grpc_endpoint_delete_from_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set) {
+ ep->vtable->delete_from_pollset_set(ep, pollset_set);
+}
+
+void grpc_endpoint_shutdown(grpc_endpoint* ep, grpc_error* why) {
+ ep->vtable->shutdown(ep, why);
+}
+
+void grpc_endpoint_destroy(grpc_endpoint* ep) { ep->vtable->destroy(ep); }
+
y_absl::string_view grpc_endpoint_get_peer(grpc_endpoint* ep) {
- return ep->vtable->get_peer(ep);
-}
-
+ return ep->vtable->get_peer(ep);
+}
+
y_absl::string_view grpc_endpoint_get_local_address(grpc_endpoint* ep) {
return ep->vtable->get_local_address(ep);
}
-int grpc_endpoint_get_fd(grpc_endpoint* ep) { return ep->vtable->get_fd(ep); }
-
-grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* ep) {
- return ep->vtable->get_resource_user(ep);
-}
+int grpc_endpoint_get_fd(grpc_endpoint* ep) { return ep->vtable->get_fd(ep); }
+
+grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* ep) {
+ return ep->vtable->get_resource_user(ep);
+}
bool grpc_endpoint_can_track_err(grpc_endpoint* ep) {
return ep->vtable->can_track_err(ep);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h
index e704c3be49d..6e49b4edc03 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_ENDPOINT_H
#define GRPC_CORE_LIB_IOMGR_ENDPOINT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "y_absl/strings/string_view.h"
#include <grpc/slice.h>
@@ -41,15 +41,15 @@ struct grpc_endpoint_vtable {
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);
- void (*add_to_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset);
- void (*delete_from_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset);
- void (*shutdown)(grpc_endpoint* ep, grpc_error* why);
- void (*destroy)(grpc_endpoint* ep);
- grpc_resource_user* (*get_resource_user)(grpc_endpoint* ep);
+ void (*add_to_pollset)(grpc_endpoint* ep, grpc_pollset* pollset);
+ void (*add_to_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset);
+ void (*delete_from_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset);
+ void (*shutdown)(grpc_endpoint* ep, grpc_error* why);
+ void (*destroy)(grpc_endpoint* ep);
+ grpc_resource_user* (*get_resource_user)(grpc_endpoint* ep);
y_absl::string_view (*get_peer)(grpc_endpoint* ep);
y_absl::string_view (*get_local_address)(grpc_endpoint* ep);
- int (*get_fd)(grpc_endpoint* ep);
+ int (*get_fd)(grpc_endpoint* ep);
bool (*can_track_err)(grpc_endpoint* ep);
};
@@ -58,7 +58,7 @@ struct grpc_endpoint_vtable {
indicates the endpoint is closed.
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,
+void grpc_endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* slices,
grpc_closure* cb, bool urgent);
y_absl::string_view grpc_endpoint_get_peer(grpc_endpoint* ep);
@@ -66,8 +66,8 @@ y_absl::string_view grpc_endpoint_get_peer(grpc_endpoint* ep);
y_absl::string_view grpc_endpoint_get_local_address(grpc_endpoint* ep);
/* Get the file descriptor used by \a ep. Return -1 if \a ep is not using an fd.
- */
-int grpc_endpoint_get_fd(grpc_endpoint* ep);
+ */
+int grpc_endpoint_get_fd(grpc_endpoint* ep);
/* Write slices out to the socket.
@@ -81,30 +81,30 @@ int grpc_endpoint_get_fd(grpc_endpoint* ep);
\a arg is platform specific. It is currently only used by TCP on linux
platforms as an argument that would be forwarded to the timestamps callback.
*/
-void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
+void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
grpc_closure* cb, void* arg);
/* Causes any pending and future read/write callbacks to run immediately with
success==0 */
-void grpc_endpoint_shutdown(grpc_endpoint* ep, grpc_error* why);
-void grpc_endpoint_destroy(grpc_endpoint* ep);
-
-/* Add an endpoint to a pollset or pollset_set, so that when the pollset is
- polled, events from this endpoint are considered */
-void grpc_endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset);
-void grpc_endpoint_add_to_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set);
+void grpc_endpoint_shutdown(grpc_endpoint* ep, grpc_error* why);
+void grpc_endpoint_destroy(grpc_endpoint* ep);
-/* Delete an endpoint from a pollset_set */
-void grpc_endpoint_delete_from_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set);
+/* Add an endpoint to a pollset or pollset_set, so that when the pollset is
+ polled, events from this endpoint are considered */
+void grpc_endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset);
+void grpc_endpoint_add_to_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set);
-grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* endpoint);
+/* Delete an endpoint from a pollset_set */
+void grpc_endpoint_delete_from_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set);
+grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* endpoint);
+
bool grpc_endpoint_can_track_err(grpc_endpoint* ep);
struct grpc_endpoint {
- const grpc_endpoint_vtable* vtable;
+ const grpc_endpoint_vtable* vtable;
};
#endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair.h b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair.h
index e01185b9fb2..28c04e0c321 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair.h
@@ -1,33 +1,33 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_ENDPOINT_PAIR_H
#define GRPC_CORE_LIB_IOMGR_ENDPOINT_PAIR_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/endpoint.h"
struct grpc_endpoint_pair {
- grpc_endpoint* client;
- grpc_endpoint* server;
+ grpc_endpoint* client;
+ grpc_endpoint* server;
};
-grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name,
- grpc_channel_args* args);
+grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name,
+ grpc_channel_args* args);
#endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_PAIR_H */
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 7f95da7365f..5eb31dcdbad 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
@@ -1,73 +1,73 @@
-/*
- *
- * 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"
-
+/*
+ *
+ * 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"
+
#ifdef GRPC_POSIX_SOCKET_TCP
-
-#include "src/core/lib/iomgr/endpoint_pair.h"
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-
+
+#include "src/core/lib/iomgr/endpoint_pair.h"
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/iomgr/tcp_posix.h"
-
-static void create_sockets(int sv[2]) {
- int flags;
- grpc_create_socketpair_if_unix(sv);
- flags = fcntl(sv[0], F_GETFL, 0);
- GPR_ASSERT(fcntl(sv[0], F_SETFL, flags | O_NONBLOCK) == 0);
- flags = fcntl(sv[1], F_GETFL, 0);
- GPR_ASSERT(fcntl(sv[1], F_SETFL, flags | O_NONBLOCK) == 0);
- GPR_ASSERT(grpc_set_socket_no_sigpipe_if_possible(sv[0]) == GRPC_ERROR_NONE);
- GPR_ASSERT(grpc_set_socket_no_sigpipe_if_possible(sv[1]) == GRPC_ERROR_NONE);
-}
-
-grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name,
- grpc_channel_args* args) {
- int sv[2];
- grpc_endpoint_pair p;
- create_sockets(sv);
-
- grpc_core::ExecCtx exec_ctx;
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/iomgr/tcp_posix.h"
+
+static void create_sockets(int sv[2]) {
+ int flags;
+ grpc_create_socketpair_if_unix(sv);
+ flags = fcntl(sv[0], F_GETFL, 0);
+ GPR_ASSERT(fcntl(sv[0], F_SETFL, flags | O_NONBLOCK) == 0);
+ flags = fcntl(sv[1], F_GETFL, 0);
+ GPR_ASSERT(fcntl(sv[1], F_SETFL, flags | O_NONBLOCK) == 0);
+ GPR_ASSERT(grpc_set_socket_no_sigpipe_if_possible(sv[0]) == GRPC_ERROR_NONE);
+ GPR_ASSERT(grpc_set_socket_no_sigpipe_if_possible(sv[1]) == GRPC_ERROR_NONE);
+}
+
+grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name,
+ grpc_channel_args* args) {
+ int sv[2];
+ grpc_endpoint_pair p;
+ create_sockets(sv);
+
+ grpc_core::ExecCtx exec_ctx;
+
TString final_name = y_absl::StrCat(name, ":client");
p.client = grpc_tcp_create(grpc_fd_create(sv[1], final_name.c_str(), false),
args, "socketpair-server");
final_name = y_absl::StrCat(name, ":server");
p.server = grpc_tcp_create(grpc_fd_create(sv[0], final_name.c_str(), false),
args, "socketpair-client");
-
- return p;
-}
-
-#endif
+
+ return p;
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_uv.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_uv.cc
index b99d178cb67..c9d092a875e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_pair_uv.cc
@@ -1,40 +1,40 @@
-/*
- *
- * 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"
-
-#ifdef GRPC_UV
-
-#include <stdlib.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/endpoint_pair.h"
-
-grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name,
- grpc_channel_args* args) {
- grpc_endpoint_pair endpoint_pair;
- // TODO(mlumish): implement this properly under libuv
- GPR_ASSERT(false &&
- "grpc_iomgr_create_endpoint_pair is not suppoted with libuv");
- return endpoint_pair;
-}
-
-#endif /* GRPC_UV */
+/*
+ *
+ * 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"
+
+#ifdef GRPC_UV
+
+#include <stdlib.h>
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/endpoint_pair.h"
+
+grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name,
+ grpc_channel_args* args) {
+ grpc_endpoint_pair endpoint_pair;
+ // TODO(mlumish): implement this properly under libuv
+ GPR_ASSERT(false &&
+ "grpc_iomgr_create_endpoint_pair is not suppoted with libuv");
+ return endpoint_pair;
+}
+
+#endif /* GRPC_UV */
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 9962809a27b..55a2747d05a 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
@@ -1,87 +1,87 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-#include "src/core/lib/iomgr/endpoint_pair.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <string.h>
-
-#include <grpc/support/log.h>
-#include "src/core/lib/iomgr/socket_windows.h"
-#include "src/core/lib/iomgr/tcp_windows.h"
-
-static void create_sockets(SOCKET sv[2]) {
- SOCKET svr_sock = INVALID_SOCKET;
- SOCKET lst_sock = INVALID_SOCKET;
- SOCKET cli_sock = INVALID_SOCKET;
- SOCKADDR_IN addr;
- int addr_len = sizeof(addr);
-
- lst_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 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 <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+#include "src/core/lib/iomgr/endpoint_pair.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+
+#include <grpc/support/log.h>
+#include "src/core/lib/iomgr/socket_windows.h"
+#include "src/core/lib/iomgr/tcp_windows.h"
+
+static void create_sockets(SOCKET sv[2]) {
+ SOCKET svr_sock = INVALID_SOCKET;
+ SOCKET lst_sock = INVALID_SOCKET;
+ SOCKET cli_sock = INVALID_SOCKET;
+ SOCKADDR_IN addr;
+ int addr_len = sizeof(addr);
+
+ lst_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
grpc_get_default_wsa_socket_flags());
- GPR_ASSERT(lst_sock != INVALID_SOCKET);
-
- memset(&addr, 0, sizeof(addr));
- addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- addr.sin_family = AF_INET;
- GPR_ASSERT(bind(lst_sock, (grpc_sockaddr*)&addr, sizeof(addr)) !=
- SOCKET_ERROR);
- GPR_ASSERT(listen(lst_sock, SOMAXCONN) != SOCKET_ERROR);
- GPR_ASSERT(getsockname(lst_sock, (grpc_sockaddr*)&addr, &addr_len) !=
- SOCKET_ERROR);
-
- cli_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
+ GPR_ASSERT(lst_sock != INVALID_SOCKET);
+
+ memset(&addr, 0, sizeof(addr));
+ addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ addr.sin_family = AF_INET;
+ GPR_ASSERT(bind(lst_sock, (grpc_sockaddr*)&addr, sizeof(addr)) !=
+ SOCKET_ERROR);
+ GPR_ASSERT(listen(lst_sock, SOMAXCONN) != SOCKET_ERROR);
+ GPR_ASSERT(getsockname(lst_sock, (grpc_sockaddr*)&addr, &addr_len) !=
+ SOCKET_ERROR);
+
+ cli_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
grpc_get_default_wsa_socket_flags());
- GPR_ASSERT(cli_sock != INVALID_SOCKET);
-
- GPR_ASSERT(WSAConnect(cli_sock, (grpc_sockaddr*)&addr, addr_len, NULL, NULL,
- NULL, NULL) == 0);
- svr_sock = accept(lst_sock, (grpc_sockaddr*)&addr, &addr_len);
- GPR_ASSERT(svr_sock != INVALID_SOCKET);
-
- closesocket(lst_sock);
- grpc_tcp_prepare_socket(cli_sock);
- grpc_tcp_prepare_socket(svr_sock);
-
- sv[1] = cli_sock;
- sv[0] = svr_sock;
-}
-
-grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(
- const char* name, grpc_channel_args* channel_args) {
- SOCKET sv[2];
- grpc_endpoint_pair p;
- create_sockets(sv);
- grpc_core::ExecCtx exec_ctx;
- p.client = grpc_tcp_create(grpc_winsocket_create(sv[1], "endpoint:client"),
- channel_args, "endpoint:server");
- p.server = grpc_tcp_create(grpc_winsocket_create(sv[0], "endpoint:server"),
- channel_args, "endpoint:client");
-
- return p;
-}
-
-#endif
+ GPR_ASSERT(cli_sock != INVALID_SOCKET);
+
+ GPR_ASSERT(WSAConnect(cli_sock, (grpc_sockaddr*)&addr, addr_len, NULL, NULL,
+ NULL, NULL) == 0);
+ svr_sock = accept(lst_sock, (grpc_sockaddr*)&addr, &addr_len);
+ GPR_ASSERT(svr_sock != INVALID_SOCKET);
+
+ closesocket(lst_sock);
+ grpc_tcp_prepare_socket(cli_sock);
+ grpc_tcp_prepare_socket(svr_sock);
+
+ sv[1] = cli_sock;
+ sv[0] = svr_sock;
+}
+
+grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(
+ const char* name, grpc_channel_args* channel_args) {
+ SOCKET sv[2];
+ grpc_endpoint_pair p;
+ create_sockets(sv);
+ grpc_core::ExecCtx exec_ctx;
+ p.client = grpc_tcp_create(grpc_winsocket_create(sv[1], "endpoint:client"),
+ channel_args, "endpoint:server");
+ p.server = grpc_tcp_create(grpc_winsocket_create(sv[0], "endpoint:server"),
+ channel_args, "endpoint:client");
+
+ return p;
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error.cc b/contrib/libs/grpc/src/core/lib/iomgr/error.cc
index c4b5c739526..fe1cda994f8 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/error.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/error.cc
@@ -1,310 +1,310 @@
-/*
- *
- * 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/error.h"
-
-#include <inttypes.h>
-#include <string.h>
-
-#include <grpc/status.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#ifdef GPR_WINDOWS
-#include <grpc/support/log_windows.h>
-#endif
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/error_internal.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount(false,
- "error_refcount");
-grpc_core::DebugOnlyTraceFlag grpc_trace_closure(false, "closure");
-
-static const char* error_int_name(grpc_error_ints key) {
- switch (key) {
- case GRPC_ERROR_INT_ERRNO:
- return "errno";
- case GRPC_ERROR_INT_FILE_LINE:
- return "file_line";
- case GRPC_ERROR_INT_STREAM_ID:
- return "stream_id";
- case GRPC_ERROR_INT_GRPC_STATUS:
- return "grpc_status";
- case GRPC_ERROR_INT_OFFSET:
- return "offset";
- case GRPC_ERROR_INT_INDEX:
- return "index";
- case GRPC_ERROR_INT_SIZE:
- return "size";
- case GRPC_ERROR_INT_HTTP2_ERROR:
- return "http2_error";
- case GRPC_ERROR_INT_TSI_CODE:
- return "tsi_code";
- case GRPC_ERROR_INT_SECURITY_STATUS:
- return "security_status";
- case GRPC_ERROR_INT_FD:
- return "fd";
- case GRPC_ERROR_INT_WSA_ERROR:
- return "wsa_error";
- case GRPC_ERROR_INT_HTTP_STATUS:
- return "http_status";
- case GRPC_ERROR_INT_LIMIT:
- return "limit";
- case GRPC_ERROR_INT_OCCURRED_DURING_WRITE:
- return "occurred_during_write";
+/*
+ *
+ * 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/error.h"
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <grpc/status.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#ifdef GPR_WINDOWS
+#include <grpc/support/log_windows.h>
+#endif
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/error_internal.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount(false,
+ "error_refcount");
+grpc_core::DebugOnlyTraceFlag grpc_trace_closure(false, "closure");
+
+static const char* error_int_name(grpc_error_ints key) {
+ switch (key) {
+ case GRPC_ERROR_INT_ERRNO:
+ return "errno";
+ case GRPC_ERROR_INT_FILE_LINE:
+ return "file_line";
+ case GRPC_ERROR_INT_STREAM_ID:
+ return "stream_id";
+ case GRPC_ERROR_INT_GRPC_STATUS:
+ return "grpc_status";
+ case GRPC_ERROR_INT_OFFSET:
+ return "offset";
+ case GRPC_ERROR_INT_INDEX:
+ return "index";
+ case GRPC_ERROR_INT_SIZE:
+ return "size";
+ case GRPC_ERROR_INT_HTTP2_ERROR:
+ return "http2_error";
+ case GRPC_ERROR_INT_TSI_CODE:
+ return "tsi_code";
+ case GRPC_ERROR_INT_SECURITY_STATUS:
+ return "security_status";
+ case GRPC_ERROR_INT_FD:
+ return "fd";
+ case GRPC_ERROR_INT_WSA_ERROR:
+ return "wsa_error";
+ case GRPC_ERROR_INT_HTTP_STATUS:
+ return "http_status";
+ case GRPC_ERROR_INT_LIMIT:
+ 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_MAX:
- GPR_UNREACHABLE_CODE(return "unknown");
- }
- GPR_UNREACHABLE_CODE(return "unknown");
-}
-
-static const char* error_str_name(grpc_error_strs key) {
- switch (key) {
- case GRPC_ERROR_STR_KEY:
- return "key";
- case GRPC_ERROR_STR_VALUE:
- return "value";
- case GRPC_ERROR_STR_DESCRIPTION:
- return "description";
- case GRPC_ERROR_STR_OS_ERROR:
- return "os_error";
- case GRPC_ERROR_STR_TARGET_ADDRESS:
- return "target_address";
- case GRPC_ERROR_STR_SYSCALL:
- return "syscall";
- case GRPC_ERROR_STR_FILE:
- return "file";
- case GRPC_ERROR_STR_GRPC_MESSAGE:
- return "grpc_message";
- case GRPC_ERROR_STR_RAW_BYTES:
- return "raw_bytes";
- case GRPC_ERROR_STR_TSI_ERROR:
- return "tsi_error";
- case GRPC_ERROR_STR_FILENAME:
- return "filename";
- case GRPC_ERROR_STR_QUEUED_BUFFERS:
- return "queued_buffers";
- case GRPC_ERROR_STR_MAX:
- GPR_UNREACHABLE_CODE(return "unknown");
- }
- GPR_UNREACHABLE_CODE(return "unknown");
-}
-
-static const char* error_time_name(grpc_error_times key) {
- switch (key) {
- case GRPC_ERROR_TIME_CREATED:
- return "created";
- case GRPC_ERROR_TIME_MAX:
- GPR_UNREACHABLE_CODE(return "unknown");
- }
- GPR_UNREACHABLE_CODE(return "unknown");
-}
-
-#ifndef NDEBUG
+ case GRPC_ERROR_INT_MAX:
+ GPR_UNREACHABLE_CODE(return "unknown");
+ }
+ GPR_UNREACHABLE_CODE(return "unknown");
+}
+
+static const char* error_str_name(grpc_error_strs key) {
+ switch (key) {
+ case GRPC_ERROR_STR_KEY:
+ return "key";
+ case GRPC_ERROR_STR_VALUE:
+ return "value";
+ case GRPC_ERROR_STR_DESCRIPTION:
+ return "description";
+ case GRPC_ERROR_STR_OS_ERROR:
+ return "os_error";
+ case GRPC_ERROR_STR_TARGET_ADDRESS:
+ return "target_address";
+ case GRPC_ERROR_STR_SYSCALL:
+ return "syscall";
+ case GRPC_ERROR_STR_FILE:
+ return "file";
+ case GRPC_ERROR_STR_GRPC_MESSAGE:
+ return "grpc_message";
+ case GRPC_ERROR_STR_RAW_BYTES:
+ return "raw_bytes";
+ case GRPC_ERROR_STR_TSI_ERROR:
+ return "tsi_error";
+ case GRPC_ERROR_STR_FILENAME:
+ return "filename";
+ case GRPC_ERROR_STR_QUEUED_BUFFERS:
+ return "queued_buffers";
+ case GRPC_ERROR_STR_MAX:
+ GPR_UNREACHABLE_CODE(return "unknown");
+ }
+ GPR_UNREACHABLE_CODE(return "unknown");
+}
+
+static const char* error_time_name(grpc_error_times key) {
+ switch (key) {
+ case GRPC_ERROR_TIME_CREATED:
+ return "created";
+ case GRPC_ERROR_TIME_MAX:
+ GPR_UNREACHABLE_CODE(return "unknown");
+ }
+ GPR_UNREACHABLE_CODE(return "unknown");
+}
+
+#ifndef NDEBUG
grpc_error* grpc_error_do_ref(grpc_error* err, const char* file, int line) {
- if (grpc_trace_error_refcount.enabled()) {
- gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err,
- gpr_atm_no_barrier_load(&err->atomics.refs.count),
- gpr_atm_no_barrier_load(&err->atomics.refs.count) + 1, file, line);
- }
- gpr_ref(&err->atomics.refs);
- return err;
-}
-#else
+ if (grpc_trace_error_refcount.enabled()) {
+ gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err,
+ gpr_atm_no_barrier_load(&err->atomics.refs.count),
+ gpr_atm_no_barrier_load(&err->atomics.refs.count) + 1, file, line);
+ }
+ gpr_ref(&err->atomics.refs);
+ return err;
+}
+#else
grpc_error* grpc_error_do_ref(grpc_error* err) {
- gpr_ref(&err->atomics.refs);
- return err;
-}
-#endif
-
-static void unref_errs(grpc_error* err) {
- uint8_t slot = err->first_err;
- while (slot != UINT8_MAX) {
- grpc_linked_error* lerr =
- reinterpret_cast<grpc_linked_error*>(err->arena + slot);
- GRPC_ERROR_UNREF(lerr->err);
- GPR_ASSERT(err->last_err == slot ? lerr->next == UINT8_MAX
- : lerr->next != UINT8_MAX);
- slot = lerr->next;
- }
-}
-
-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) {
+ gpr_ref(&err->atomics.refs);
+ return err;
+}
+#endif
+
+static void unref_errs(grpc_error* err) {
+ uint8_t slot = err->first_err;
+ while (slot != UINT8_MAX) {
+ grpc_linked_error* lerr =
+ reinterpret_cast<grpc_linked_error*>(err->arena + slot);
+ GRPC_ERROR_UNREF(lerr->err);
+ GPR_ASSERT(err->last_err == slot ? lerr->next == UINT8_MAX
+ : lerr->next != UINT8_MAX);
+ slot = lerr->next;
+ }
+}
+
+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));
- }
- }
-}
-
-static void error_destroy(grpc_error* err) {
- GPR_ASSERT(!grpc_error_is_special(err));
- unref_errs(err);
- unref_strs(err);
- gpr_free((void*)gpr_atm_acq_load(&err->atomics.error_string));
- gpr_free(err);
-}
-
-#ifndef NDEBUG
+ }
+ }
+}
+
+static void error_destroy(grpc_error* err) {
+ GPR_ASSERT(!grpc_error_is_special(err));
+ unref_errs(err);
+ unref_strs(err);
+ gpr_free((void*)gpr_atm_acq_load(&err->atomics.error_string));
+ gpr_free(err);
+}
+
+#ifndef NDEBUG
void grpc_error_do_unref(grpc_error* err, const char* file, int line) {
- if (grpc_trace_error_refcount.enabled()) {
- gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err,
- gpr_atm_no_barrier_load(&err->atomics.refs.count),
- gpr_atm_no_barrier_load(&err->atomics.refs.count) - 1, file, line);
- }
- if (gpr_unref(&err->atomics.refs)) {
- error_destroy(err);
- }
-}
-#else
+ if (grpc_trace_error_refcount.enabled()) {
+ gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err,
+ gpr_atm_no_barrier_load(&err->atomics.refs.count),
+ gpr_atm_no_barrier_load(&err->atomics.refs.count) - 1, file, line);
+ }
+ if (gpr_unref(&err->atomics.refs)) {
+ error_destroy(err);
+ }
+}
+#else
void grpc_error_do_unref(grpc_error* err) {
- if (gpr_unref(&err->atomics.refs)) {
- error_destroy(err);
- }
-}
-#endif
-
-static uint8_t get_placement(grpc_error** err, size_t size) {
- GPR_ASSERT(*err);
- uint8_t slots = static_cast<uint8_t>(size / sizeof(intptr_t));
- if ((*err)->arena_size + slots > (*err)->arena_capacity) {
- (*err)->arena_capacity = static_cast<uint8_t> GPR_MIN(
- UINT8_MAX - 1, (3 * (*err)->arena_capacity / 2));
- if ((*err)->arena_size + slots > (*err)->arena_capacity) {
- return UINT8_MAX;
- }
-#ifndef NDEBUG
- grpc_error* orig = *err;
-#endif
- *err = static_cast<grpc_error*>(gpr_realloc(
- *err, sizeof(grpc_error) + (*err)->arena_capacity * sizeof(intptr_t)));
-#ifndef NDEBUG
- if (grpc_trace_error_refcount.enabled()) {
- if (*err != orig) {
- gpr_log(GPR_DEBUG, "realloc %p -> %p", orig, *err);
- }
- }
-#endif
- }
- uint8_t placement = (*err)->arena_size;
- (*err)->arena_size = static_cast<uint8_t>((*err)->arena_size + slots);
- return placement;
-}
-
-static void internal_set_int(grpc_error** err, grpc_error_ints which,
- intptr_t value) {
- uint8_t slot = (*err)->ints[which];
- if (slot == UINT8_MAX) {
- slot = get_placement(err, sizeof(value));
- if (slot == UINT8_MAX) {
- gpr_log(GPR_ERROR, "Error %p is full, dropping int {\"%s\":%" PRIiPTR "}",
- *err, error_int_name(which), value);
- return;
- }
- }
- (*err)->ints[which] = slot;
- (*err)->arena[slot] = value;
-}
-
-static void internal_set_str(grpc_error** err, grpc_error_strs which,
+ if (gpr_unref(&err->atomics.refs)) {
+ error_destroy(err);
+ }
+}
+#endif
+
+static uint8_t get_placement(grpc_error** err, size_t size) {
+ GPR_ASSERT(*err);
+ uint8_t slots = static_cast<uint8_t>(size / sizeof(intptr_t));
+ if ((*err)->arena_size + slots > (*err)->arena_capacity) {
+ (*err)->arena_capacity = static_cast<uint8_t> GPR_MIN(
+ UINT8_MAX - 1, (3 * (*err)->arena_capacity / 2));
+ if ((*err)->arena_size + slots > (*err)->arena_capacity) {
+ return UINT8_MAX;
+ }
+#ifndef NDEBUG
+ grpc_error* orig = *err;
+#endif
+ *err = static_cast<grpc_error*>(gpr_realloc(
+ *err, sizeof(grpc_error) + (*err)->arena_capacity * sizeof(intptr_t)));
+#ifndef NDEBUG
+ if (grpc_trace_error_refcount.enabled()) {
+ if (*err != orig) {
+ gpr_log(GPR_DEBUG, "realloc %p -> %p", orig, *err);
+ }
+ }
+#endif
+ }
+ uint8_t placement = (*err)->arena_size;
+ (*err)->arena_size = static_cast<uint8_t>((*err)->arena_size + slots);
+ return placement;
+}
+
+static void internal_set_int(grpc_error** err, grpc_error_ints which,
+ intptr_t value) {
+ uint8_t slot = (*err)->ints[which];
+ if (slot == UINT8_MAX) {
+ slot = get_placement(err, sizeof(value));
+ if (slot == UINT8_MAX) {
+ gpr_log(GPR_ERROR, "Error %p is full, dropping int {\"%s\":%" PRIiPTR "}",
+ *err, error_int_name(which), value);
+ return;
+ }
+ }
+ (*err)->ints[which] = slot;
+ (*err)->arena[slot] = value;
+}
+
+static void internal_set_str(grpc_error** err, grpc_error_strs which,
const grpc_slice& value) {
- uint8_t slot = (*err)->strs[which];
- if (slot == UINT8_MAX) {
- slot = get_placement(err, sizeof(value));
- if (slot == UINT8_MAX) {
- const char* str = grpc_slice_to_c_string(value);
- gpr_log(GPR_ERROR, "Error %p is full, dropping string {\"%s\":\"%s\"}",
- *err, error_str_name(which), str);
- gpr_free((void*)str);
- return;
- }
- } else {
+ uint8_t slot = (*err)->strs[which];
+ if (slot == UINT8_MAX) {
+ slot = get_placement(err, sizeof(value));
+ if (slot == UINT8_MAX) {
+ const char* str = grpc_slice_to_c_string(value);
+ gpr_log(GPR_ERROR, "Error %p is full, dropping string {\"%s\":\"%s\"}",
+ *err, error_str_name(which), str);
+ gpr_free((void*)str);
+ return;
+ }
+ } else {
grpc_slice_unref_internal(
*reinterpret_cast<grpc_slice*>((*err)->arena + slot));
- }
- (*err)->strs[which] = slot;
- memcpy((*err)->arena + slot, &value, sizeof(value));
-}
-
-static char* fmt_time(gpr_timespec tm);
-static void internal_set_time(grpc_error** err, grpc_error_times which,
- gpr_timespec value) {
- uint8_t slot = (*err)->times[which];
- if (slot == UINT8_MAX) {
- slot = get_placement(err, sizeof(value));
- if (slot == UINT8_MAX) {
- const char* time_str = fmt_time(value);
- gpr_log(GPR_ERROR, "Error %p is full, dropping \"%s\":\"%s\"}", *err,
- error_time_name(which), time_str);
- gpr_free((void*)time_str);
- return;
- }
- }
- (*err)->times[which] = slot;
- memcpy((*err)->arena + slot, &value, sizeof(value));
-}
-
-static void internal_add_error(grpc_error** err, grpc_error* new_err) {
- grpc_linked_error new_last = {new_err, UINT8_MAX};
- uint8_t slot = get_placement(err, sizeof(grpc_linked_error));
- if (slot == UINT8_MAX) {
- gpr_log(GPR_ERROR, "Error %p is full, dropping error %p = %s", *err,
- new_err, grpc_error_string(new_err));
- GRPC_ERROR_UNREF(new_err);
- return;
- }
- if ((*err)->first_err == UINT8_MAX) {
- GPR_ASSERT((*err)->last_err == UINT8_MAX);
- (*err)->last_err = slot;
- (*err)->first_err = slot;
- } else {
- GPR_ASSERT((*err)->last_err != UINT8_MAX);
- grpc_linked_error* old_last =
- reinterpret_cast<grpc_linked_error*>((*err)->arena + (*err)->last_err);
- old_last->next = slot;
- (*err)->last_err = slot;
- }
- memcpy((*err)->arena + slot, &new_last, sizeof(grpc_linked_error));
-}
-
-#define SLOTS_PER_INT (sizeof(intptr_t) / sizeof(intptr_t))
-#define SLOTS_PER_STR (sizeof(grpc_slice) / sizeof(intptr_t))
-#define SLOTS_PER_TIME (sizeof(gpr_timespec) / sizeof(intptr_t))
-#define SLOTS_PER_LINKED_ERROR (sizeof(grpc_linked_error) / sizeof(intptr_t))
-
-// size of storing one int and two slices and a timespec. For line, desc, file,
-// and time created
-#define DEFAULT_ERROR_CAPACITY \
- (SLOTS_PER_INT + (SLOTS_PER_STR * 2) + SLOTS_PER_TIME)
-
-// It is very common to include and extra int and string in an error
-#define SURPLUS_CAPACITY (2 * SLOTS_PER_INT + SLOTS_PER_TIME)
-
+ }
+ (*err)->strs[which] = slot;
+ memcpy((*err)->arena + slot, &value, sizeof(value));
+}
+
+static char* fmt_time(gpr_timespec tm);
+static void internal_set_time(grpc_error** err, grpc_error_times which,
+ gpr_timespec value) {
+ uint8_t slot = (*err)->times[which];
+ if (slot == UINT8_MAX) {
+ slot = get_placement(err, sizeof(value));
+ if (slot == UINT8_MAX) {
+ const char* time_str = fmt_time(value);
+ gpr_log(GPR_ERROR, "Error %p is full, dropping \"%s\":\"%s\"}", *err,
+ error_time_name(which), time_str);
+ gpr_free((void*)time_str);
+ return;
+ }
+ }
+ (*err)->times[which] = slot;
+ memcpy((*err)->arena + slot, &value, sizeof(value));
+}
+
+static void internal_add_error(grpc_error** err, grpc_error* new_err) {
+ grpc_linked_error new_last = {new_err, UINT8_MAX};
+ uint8_t slot = get_placement(err, sizeof(grpc_linked_error));
+ if (slot == UINT8_MAX) {
+ gpr_log(GPR_ERROR, "Error %p is full, dropping error %p = %s", *err,
+ new_err, grpc_error_string(new_err));
+ GRPC_ERROR_UNREF(new_err);
+ return;
+ }
+ if ((*err)->first_err == UINT8_MAX) {
+ GPR_ASSERT((*err)->last_err == UINT8_MAX);
+ (*err)->last_err = slot;
+ (*err)->first_err = slot;
+ } else {
+ GPR_ASSERT((*err)->last_err != UINT8_MAX);
+ grpc_linked_error* old_last =
+ reinterpret_cast<grpc_linked_error*>((*err)->arena + (*err)->last_err);
+ old_last->next = slot;
+ (*err)->last_err = slot;
+ }
+ memcpy((*err)->arena + slot, &new_last, sizeof(grpc_linked_error));
+}
+
+#define SLOTS_PER_INT (sizeof(intptr_t) / sizeof(intptr_t))
+#define SLOTS_PER_STR (sizeof(grpc_slice) / sizeof(intptr_t))
+#define SLOTS_PER_TIME (sizeof(gpr_timespec) / sizeof(intptr_t))
+#define SLOTS_PER_LINKED_ERROR (sizeof(grpc_linked_error) / sizeof(intptr_t))
+
+// size of storing one int and two slices and a timespec. For line, desc, file,
+// and time created
+#define DEFAULT_ERROR_CAPACITY \
+ (SLOTS_PER_INT + (SLOTS_PER_STR * 2) + SLOTS_PER_TIME)
+
+// It is very common to include and extra int and string in an error
+#define SURPLUS_CAPACITY (2 * SLOTS_PER_INT + SLOTS_PER_TIME)
+
static gpr_atm g_error_creation_allowed = true;
void grpc_disable_error_creation() {
@@ -317,138 +317,138 @@ void grpc_enable_error_creation() {
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>(
- DEFAULT_ERROR_CAPACITY +
- static_cast<uint8_t>(num_referencing * SLOTS_PER_LINKED_ERROR) +
- SURPLUS_CAPACITY);
- grpc_error* err = static_cast<grpc_error*>(
- gpr_malloc(sizeof(*err) + initial_arena_capacity * sizeof(intptr_t)));
- if (err == nullptr) { // TODO(ctiller): make gpr_malloc return NULL
- return GRPC_ERROR_OOM;
- }
-#ifndef NDEBUG
+ size_t num_referencing) {
+ GPR_TIMER_SCOPE("grpc_error_create", 0);
+ uint8_t initial_arena_capacity = static_cast<uint8_t>(
+ DEFAULT_ERROR_CAPACITY +
+ static_cast<uint8_t>(num_referencing * SLOTS_PER_LINKED_ERROR) +
+ SURPLUS_CAPACITY);
+ grpc_error* err = static_cast<grpc_error*>(
+ gpr_malloc(sizeof(*err) + initial_arena_capacity * sizeof(intptr_t)));
+ if (err == nullptr) { // TODO(ctiller): make gpr_malloc return NULL
+ return GRPC_ERROR_OOM;
+ }
+#ifndef NDEBUG
if (!gpr_atm_no_barrier_load(&g_error_creation_allowed)) {
gpr_log(GPR_ERROR,
"Error creation occurred when error creation was disabled [%s:%d]",
file, line);
abort();
}
- if (grpc_trace_error_refcount.enabled()) {
- gpr_log(GPR_DEBUG, "%p create [%s:%d]", err, file, line);
- }
-#endif
-
- err->arena_size = 0;
- err->arena_capacity = initial_arena_capacity;
- err->first_err = UINT8_MAX;
- err->last_err = UINT8_MAX;
-
- memset(err->ints, UINT8_MAX, GRPC_ERROR_INT_MAX);
- memset(err->strs, UINT8_MAX, GRPC_ERROR_STR_MAX);
- memset(err->times, UINT8_MAX, GRPC_ERROR_TIME_MAX);
-
- internal_set_int(&err, GRPC_ERROR_INT_FILE_LINE, line);
- internal_set_str(&err, GRPC_ERROR_STR_FILE,
- grpc_slice_from_static_string(file));
- internal_set_str(&err, GRPC_ERROR_STR_DESCRIPTION, desc);
-
- for (size_t i = 0; i < num_referencing; ++i) {
- if (referencing[i] == GRPC_ERROR_NONE) continue;
- internal_add_error(
- &err,
- GRPC_ERROR_REF(
- referencing[i])); // TODO(ncteisen), change ownership semantics
- }
-
- internal_set_time(&err, GRPC_ERROR_TIME_CREATED, gpr_now(GPR_CLOCK_REALTIME));
-
- gpr_atm_no_barrier_store(&err->atomics.error_string, 0);
- gpr_ref_init(&err->atomics.refs, 1);
- return err;
-}
-
-static void ref_strs(grpc_error* err) {
- for (size_t i = 0; i < GRPC_ERROR_STR_MAX; ++i) {
- uint8_t slot = err->strs[i];
- if (slot != UINT8_MAX) {
- grpc_slice_ref_internal(
- *reinterpret_cast<grpc_slice*>(err->arena + slot));
- }
- }
-}
-
-static void ref_errs(grpc_error* err) {
- uint8_t slot = err->first_err;
- while (slot != UINT8_MAX) {
- grpc_linked_error* lerr =
- reinterpret_cast<grpc_linked_error*>(err->arena + slot);
- GRPC_ERROR_REF(lerr->err);
- slot = lerr->next;
- }
-}
-
-static grpc_error* copy_error_and_unref(grpc_error* in) {
- GPR_TIMER_SCOPE("copy_error_and_unref", 0);
- grpc_error* out;
- if (grpc_error_is_special(in)) {
- out = GRPC_ERROR_CREATE_FROM_STATIC_STRING("unknown");
- if (in == GRPC_ERROR_NONE) {
- internal_set_str(&out, GRPC_ERROR_STR_DESCRIPTION,
- grpc_slice_from_static_string("no error"));
- internal_set_int(&out, GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_OK);
- } else if (in == GRPC_ERROR_OOM) {
- internal_set_str(&out, GRPC_ERROR_STR_DESCRIPTION,
- grpc_slice_from_static_string("oom"));
- } else if (in == GRPC_ERROR_CANCELLED) {
- internal_set_str(&out, GRPC_ERROR_STR_DESCRIPTION,
- grpc_slice_from_static_string("cancelled"));
- internal_set_int(&out, GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_CANCELLED);
- }
- } else if (gpr_ref_is_unique(&in->atomics.refs)) {
- out = in;
- } else {
- uint8_t new_arena_capacity = in->arena_capacity;
- // the returned err will be added to, so we ensure this is room to avoid
- // unneeded allocations.
- if (in->arena_capacity - in->arena_size <
- static_cast<uint8_t> SLOTS_PER_STR) {
- new_arena_capacity = static_cast<uint8_t>(3 * new_arena_capacity / 2);
- }
- out = static_cast<grpc_error*>(
- gpr_malloc(sizeof(*in) + new_arena_capacity * sizeof(intptr_t)));
-#ifndef NDEBUG
- if (grpc_trace_error_refcount.enabled()) {
- gpr_log(GPR_DEBUG, "%p create copying %p", out, in);
- }
-#endif
- // bulk memcpy of the rest of the struct.
- size_t skip = sizeof(&out->atomics);
- memcpy((void*)((uintptr_t)out + skip), (void*)((uintptr_t)in + skip),
- sizeof(*in) + (in->arena_size * sizeof(intptr_t)) - skip);
- // manually set the atomics and the new capacity
- gpr_atm_no_barrier_store(&out->atomics.error_string, 0);
- gpr_ref_init(&out->atomics.refs, 1);
- out->arena_capacity = new_arena_capacity;
- ref_strs(out);
- ref_errs(out);
- GRPC_ERROR_UNREF(in);
- }
- return out;
-}
-
-grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which,
- intptr_t value) {
- GPR_TIMER_SCOPE("grpc_error_set_int", 0);
- grpc_error* new_err = copy_error_and_unref(src);
- internal_set_int(&new_err, which, value);
- return new_err;
-}
-
+ if (grpc_trace_error_refcount.enabled()) {
+ gpr_log(GPR_DEBUG, "%p create [%s:%d]", err, file, line);
+ }
+#endif
+
+ err->arena_size = 0;
+ err->arena_capacity = initial_arena_capacity;
+ err->first_err = UINT8_MAX;
+ err->last_err = UINT8_MAX;
+
+ memset(err->ints, UINT8_MAX, GRPC_ERROR_INT_MAX);
+ memset(err->strs, UINT8_MAX, GRPC_ERROR_STR_MAX);
+ memset(err->times, UINT8_MAX, GRPC_ERROR_TIME_MAX);
+
+ internal_set_int(&err, GRPC_ERROR_INT_FILE_LINE, line);
+ internal_set_str(&err, GRPC_ERROR_STR_FILE,
+ grpc_slice_from_static_string(file));
+ internal_set_str(&err, GRPC_ERROR_STR_DESCRIPTION, desc);
+
+ for (size_t i = 0; i < num_referencing; ++i) {
+ if (referencing[i] == GRPC_ERROR_NONE) continue;
+ internal_add_error(
+ &err,
+ GRPC_ERROR_REF(
+ referencing[i])); // TODO(ncteisen), change ownership semantics
+ }
+
+ internal_set_time(&err, GRPC_ERROR_TIME_CREATED, gpr_now(GPR_CLOCK_REALTIME));
+
+ gpr_atm_no_barrier_store(&err->atomics.error_string, 0);
+ gpr_ref_init(&err->atomics.refs, 1);
+ return err;
+}
+
+static void ref_strs(grpc_error* err) {
+ for (size_t i = 0; i < GRPC_ERROR_STR_MAX; ++i) {
+ uint8_t slot = err->strs[i];
+ if (slot != UINT8_MAX) {
+ grpc_slice_ref_internal(
+ *reinterpret_cast<grpc_slice*>(err->arena + slot));
+ }
+ }
+}
+
+static void ref_errs(grpc_error* err) {
+ uint8_t slot = err->first_err;
+ while (slot != UINT8_MAX) {
+ grpc_linked_error* lerr =
+ reinterpret_cast<grpc_linked_error*>(err->arena + slot);
+ GRPC_ERROR_REF(lerr->err);
+ slot = lerr->next;
+ }
+}
+
+static grpc_error* copy_error_and_unref(grpc_error* in) {
+ GPR_TIMER_SCOPE("copy_error_and_unref", 0);
+ grpc_error* out;
+ if (grpc_error_is_special(in)) {
+ out = GRPC_ERROR_CREATE_FROM_STATIC_STRING("unknown");
+ if (in == GRPC_ERROR_NONE) {
+ internal_set_str(&out, GRPC_ERROR_STR_DESCRIPTION,
+ grpc_slice_from_static_string("no error"));
+ internal_set_int(&out, GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_OK);
+ } else if (in == GRPC_ERROR_OOM) {
+ internal_set_str(&out, GRPC_ERROR_STR_DESCRIPTION,
+ grpc_slice_from_static_string("oom"));
+ } else if (in == GRPC_ERROR_CANCELLED) {
+ internal_set_str(&out, GRPC_ERROR_STR_DESCRIPTION,
+ grpc_slice_from_static_string("cancelled"));
+ internal_set_int(&out, GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_CANCELLED);
+ }
+ } else if (gpr_ref_is_unique(&in->atomics.refs)) {
+ out = in;
+ } else {
+ uint8_t new_arena_capacity = in->arena_capacity;
+ // the returned err will be added to, so we ensure this is room to avoid
+ // unneeded allocations.
+ if (in->arena_capacity - in->arena_size <
+ static_cast<uint8_t> SLOTS_PER_STR) {
+ new_arena_capacity = static_cast<uint8_t>(3 * new_arena_capacity / 2);
+ }
+ out = static_cast<grpc_error*>(
+ gpr_malloc(sizeof(*in) + new_arena_capacity * sizeof(intptr_t)));
+#ifndef NDEBUG
+ if (grpc_trace_error_refcount.enabled()) {
+ gpr_log(GPR_DEBUG, "%p create copying %p", out, in);
+ }
+#endif
+ // bulk memcpy of the rest of the struct.
+ size_t skip = sizeof(&out->atomics);
+ memcpy((void*)((uintptr_t)out + skip), (void*)((uintptr_t)in + skip),
+ sizeof(*in) + (in->arena_size * sizeof(intptr_t)) - skip);
+ // manually set the atomics and the new capacity
+ gpr_atm_no_barrier_store(&out->atomics.error_string, 0);
+ gpr_ref_init(&out->atomics.refs, 1);
+ out->arena_capacity = new_arena_capacity;
+ ref_strs(out);
+ ref_errs(out);
+ GRPC_ERROR_UNREF(in);
+ }
+ return out;
+}
+
+grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which,
+ intptr_t value) {
+ GPR_TIMER_SCOPE("grpc_error_set_int", 0);
+ grpc_error* new_err = copy_error_and_unref(src);
+ internal_set_int(&new_err, which, value);
+ return new_err;
+}
+
struct special_error_status_map {
- grpc_status_code code;
- const char* msg;
+ grpc_status_code code;
+ const char* msg;
size_t len;
};
const special_error_status_map error_status_map[] = {
@@ -459,34 +459,34 @@ const special_error_status_map error_status_map[] = {
{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) {
- GPR_TIMER_SCOPE("grpc_error_get_int", 0);
- if (grpc_error_is_special(err)) {
+};
+
+bool grpc_error_get_int(grpc_error* err, grpc_error_ints which, intptr_t* p) {
+ GPR_TIMER_SCOPE("grpc_error_get_int", 0);
+ if (grpc_error_is_special(err)) {
if (which != GRPC_ERROR_INT_GRPC_STATUS) return false;
*p = error_status_map[reinterpret_cast<size_t>(err)].code;
return true;
- }
- uint8_t slot = err->ints[which];
- if (slot != UINT8_MAX) {
- if (p != nullptr) *p = err->arena[slot];
- return true;
- }
- return false;
-}
-
-grpc_error* grpc_error_set_str(grpc_error* src, grpc_error_strs which,
+ }
+ uint8_t slot = err->ints[which];
+ if (slot != UINT8_MAX) {
+ if (p != nullptr) *p = err->arena[slot];
+ return true;
+ }
+ return false;
+}
+
+grpc_error* grpc_error_set_str(grpc_error* src, grpc_error_strs which,
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);
- return new_err;
-}
-
-bool grpc_error_get_str(grpc_error* err, grpc_error_strs which,
- grpc_slice* str) {
- if (grpc_error_is_special(err)) {
+ GPR_TIMER_SCOPE("grpc_error_set_str", 0);
+ grpc_error* new_err = copy_error_and_unref(src);
+ internal_set_str(&new_err, which, str);
+ return new_err;
+}
+
+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)];
@@ -495,18 +495,18 @@ bool grpc_error_get_str(grpc_error* err, grpc_error_strs which,
reinterpret_cast<uint8_t*>(const_cast<char*>(msg.msg));
str->data.refcounted.length = msg.len;
return true;
- }
- uint8_t slot = err->strs[which];
- if (slot != UINT8_MAX) {
- *str = *reinterpret_cast<grpc_slice*>(err->arena + slot);
- return true;
- } else {
- return false;
- }
-}
-
-grpc_error* grpc_error_add_child(grpc_error* src, grpc_error* child) {
- GPR_TIMER_SCOPE("grpc_error_add_child", 0);
+ }
+ uint8_t slot = err->strs[which];
+ if (slot != UINT8_MAX) {
+ *str = *reinterpret_cast<grpc_slice*>(err->arena + slot);
+ return true;
+ } else {
+ return false;
+ }
+}
+
+grpc_error* grpc_error_add_child(grpc_error* src, grpc_error* child) {
+ GPR_TIMER_SCOPE("grpc_error_add_child", 0);
if (src != GRPC_ERROR_NONE) {
if (child == GRPC_ERROR_NONE) {
/* \a child is empty. Simply return the ref to \a src */
@@ -525,291 +525,291 @@ grpc_error* grpc_error_add_child(grpc_error* src, grpc_error* child) {
/* \a src is empty. Simply return the ref to \a child */
return child;
}
-}
-
-static const char* no_error_string = "\"No Error\"";
-static const char* oom_error_string = "\"Out of memory\"";
-static const char* cancelled_error_string = "\"Cancelled\"";
-
+}
+
+static const char* no_error_string = "\"No Error\"";
+static const char* oom_error_string = "\"Out of memory\"";
+static const char* cancelled_error_string = "\"Cancelled\"";
+
struct kv_pair {
- char* key;
- char* value;
+ char* key;
+ char* value;
};
struct kv_pairs {
- kv_pair* kvs;
- size_t num_kvs;
- size_t cap_kvs;
+ kv_pair* kvs;
+ size_t num_kvs;
+ size_t cap_kvs;
};
-static void append_chr(char c, char** s, size_t* sz, size_t* cap) {
- if (*sz == *cap) {
- *cap = GPR_MAX(8, 3 * *cap / 2);
- *s = static_cast<char*>(gpr_realloc(*s, *cap));
- }
- (*s)[(*sz)++] = c;
-}
-
-static void append_str(const char* str, char** s, size_t* sz, size_t* cap) {
- for (const char* c = str; *c; c++) {
- append_chr(*c, s, sz, cap);
- }
-}
-
-static void append_esc_str(const uint8_t* str, size_t len, char** s, size_t* sz,
- size_t* cap) {
- static const char* hex = "0123456789abcdef";
- append_chr('"', s, sz, cap);
- for (size_t i = 0; i < len; i++, str++) {
- if (*str < 32 || *str >= 127) {
- append_chr('\\', s, sz, cap);
- switch (*str) {
- case '\b':
- append_chr('b', s, sz, cap);
- break;
- case '\f':
- append_chr('f', s, sz, cap);
- break;
- case '\n':
- append_chr('n', s, sz, cap);
- break;
- case '\r':
- append_chr('r', s, sz, cap);
- break;
- case '\t':
- append_chr('t', s, sz, cap);
- break;
- default:
- append_chr('u', s, sz, cap);
- append_chr('0', s, sz, cap);
- append_chr('0', s, sz, cap);
- append_chr(hex[*str >> 4], s, sz, cap);
- append_chr(hex[*str & 0x0f], s, sz, cap);
- break;
- }
- } else {
- append_chr(static_cast<char>(*str), s, sz, cap);
- }
- }
- append_chr('"', s, sz, cap);
-}
-
-static void append_kv(kv_pairs* kvs, char* key, char* value) {
- if (kvs->num_kvs == kvs->cap_kvs) {
- kvs->cap_kvs = GPR_MAX(3 * kvs->cap_kvs / 2, 4);
- kvs->kvs = static_cast<kv_pair*>(
- gpr_realloc(kvs->kvs, sizeof(*kvs->kvs) * kvs->cap_kvs));
- }
- kvs->kvs[kvs->num_kvs].key = key;
- kvs->kvs[kvs->num_kvs].value = value;
- kvs->num_kvs++;
-}
-
-static char* key_int(grpc_error_ints which) {
- return gpr_strdup(error_int_name(which));
-}
-
-static char* fmt_int(intptr_t p) {
- char* s;
- gpr_asprintf(&s, "%" PRIdPTR, p);
- return s;
-}
-
-static void collect_ints_kvs(grpc_error* err, kv_pairs* kvs) {
- for (size_t which = 0; which < GRPC_ERROR_INT_MAX; ++which) {
- uint8_t slot = err->ints[which];
- if (slot != UINT8_MAX) {
- append_kv(kvs, key_int(static_cast<grpc_error_ints>(which)),
- fmt_int(err->arena[slot]));
- }
- }
-}
-
-static char* key_str(grpc_error_strs which) {
- return gpr_strdup(error_str_name(which));
-}
-
+static void append_chr(char c, char** s, size_t* sz, size_t* cap) {
+ if (*sz == *cap) {
+ *cap = GPR_MAX(8, 3 * *cap / 2);
+ *s = static_cast<char*>(gpr_realloc(*s, *cap));
+ }
+ (*s)[(*sz)++] = c;
+}
+
+static void append_str(const char* str, char** s, size_t* sz, size_t* cap) {
+ for (const char* c = str; *c; c++) {
+ append_chr(*c, s, sz, cap);
+ }
+}
+
+static void append_esc_str(const uint8_t* str, size_t len, char** s, size_t* sz,
+ size_t* cap) {
+ static const char* hex = "0123456789abcdef";
+ append_chr('"', s, sz, cap);
+ for (size_t i = 0; i < len; i++, str++) {
+ if (*str < 32 || *str >= 127) {
+ append_chr('\\', s, sz, cap);
+ switch (*str) {
+ case '\b':
+ append_chr('b', s, sz, cap);
+ break;
+ case '\f':
+ append_chr('f', s, sz, cap);
+ break;
+ case '\n':
+ append_chr('n', s, sz, cap);
+ break;
+ case '\r':
+ append_chr('r', s, sz, cap);
+ break;
+ case '\t':
+ append_chr('t', s, sz, cap);
+ break;
+ default:
+ append_chr('u', s, sz, cap);
+ append_chr('0', s, sz, cap);
+ append_chr('0', s, sz, cap);
+ append_chr(hex[*str >> 4], s, sz, cap);
+ append_chr(hex[*str & 0x0f], s, sz, cap);
+ break;
+ }
+ } else {
+ append_chr(static_cast<char>(*str), s, sz, cap);
+ }
+ }
+ append_chr('"', s, sz, cap);
+}
+
+static void append_kv(kv_pairs* kvs, char* key, char* value) {
+ if (kvs->num_kvs == kvs->cap_kvs) {
+ kvs->cap_kvs = GPR_MAX(3 * kvs->cap_kvs / 2, 4);
+ kvs->kvs = static_cast<kv_pair*>(
+ gpr_realloc(kvs->kvs, sizeof(*kvs->kvs) * kvs->cap_kvs));
+ }
+ kvs->kvs[kvs->num_kvs].key = key;
+ kvs->kvs[kvs->num_kvs].value = value;
+ kvs->num_kvs++;
+}
+
+static char* key_int(grpc_error_ints which) {
+ return gpr_strdup(error_int_name(which));
+}
+
+static char* fmt_int(intptr_t p) {
+ char* s;
+ gpr_asprintf(&s, "%" PRIdPTR, p);
+ return s;
+}
+
+static void collect_ints_kvs(grpc_error* err, kv_pairs* kvs) {
+ for (size_t which = 0; which < GRPC_ERROR_INT_MAX; ++which) {
+ uint8_t slot = err->ints[which];
+ if (slot != UINT8_MAX) {
+ append_kv(kvs, key_int(static_cast<grpc_error_ints>(which)),
+ fmt_int(err->arena[slot]));
+ }
+ }
+}
+
+static char* key_str(grpc_error_strs which) {
+ return gpr_strdup(error_str_name(which));
+}
+
static char* fmt_str(const grpc_slice& slice) {
- char* s = nullptr;
- size_t sz = 0;
- size_t cap = 0;
- append_esc_str((const uint8_t*)GRPC_SLICE_START_PTR(slice),
- GRPC_SLICE_LENGTH(slice), &s, &sz, &cap);
- append_chr(0, &s, &sz, &cap);
- return s;
-}
-
-static void collect_strs_kvs(grpc_error* err, kv_pairs* kvs) {
- for (size_t which = 0; which < GRPC_ERROR_STR_MAX; ++which) {
- uint8_t slot = err->strs[which];
- if (slot != UINT8_MAX) {
- append_kv(kvs, key_str(static_cast<grpc_error_strs>(which)),
- fmt_str(*reinterpret_cast<grpc_slice*>(err->arena + slot)));
- }
- }
-}
-
-static char* key_time(grpc_error_times which) {
- return gpr_strdup(error_time_name(which));
-}
-
-static char* fmt_time(gpr_timespec tm) {
- char* out;
- const char* pfx = "!!";
- switch (tm.clock_type) {
- case GPR_CLOCK_MONOTONIC:
- pfx = "@monotonic:";
- break;
- case GPR_CLOCK_REALTIME:
- pfx = "@";
- break;
- case GPR_CLOCK_PRECISE:
- pfx = "@precise:";
- break;
- case GPR_TIMESPAN:
- pfx = "";
- break;
- }
- gpr_asprintf(&out, "\"%s%" PRId64 ".%09d\"", pfx, tm.tv_sec, tm.tv_nsec);
- return out;
-}
-
-static void collect_times_kvs(grpc_error* err, kv_pairs* kvs) {
- for (size_t which = 0; which < GRPC_ERROR_TIME_MAX; ++which) {
- uint8_t slot = err->times[which];
- if (slot != UINT8_MAX) {
- append_kv(kvs, key_time(static_cast<grpc_error_times>(which)),
- fmt_time(*reinterpret_cast<gpr_timespec*>(err->arena + slot)));
- }
- }
-}
-
-static void add_errs(grpc_error* err, char** s, size_t* sz, size_t* cap) {
- uint8_t slot = err->first_err;
- bool first = true;
- while (slot != UINT8_MAX) {
- grpc_linked_error* lerr =
- reinterpret_cast<grpc_linked_error*>(err->arena + slot);
- if (!first) append_chr(',', s, sz, cap);
- first = false;
- const char* e = grpc_error_string(lerr->err);
- append_str(e, s, sz, cap);
- GPR_ASSERT(err->last_err == slot ? lerr->next == UINT8_MAX
- : lerr->next != UINT8_MAX);
- slot = lerr->next;
- }
-}
-
-static char* errs_string(grpc_error* err) {
- char* s = nullptr;
- size_t sz = 0;
- size_t cap = 0;
- append_chr('[', &s, &sz, &cap);
- add_errs(err, &s, &sz, &cap);
- append_chr(']', &s, &sz, &cap);
- append_chr(0, &s, &sz, &cap);
- return s;
-}
-
-static int cmp_kvs(const void* a, const void* b) {
- const kv_pair* ka = static_cast<const kv_pair*>(a);
- const kv_pair* kb = static_cast<const kv_pair*>(b);
- return strcmp(ka->key, kb->key);
-}
-
-static char* finish_kvs(kv_pairs* kvs) {
- char* s = nullptr;
- size_t sz = 0;
- size_t cap = 0;
-
- append_chr('{', &s, &sz, &cap);
- for (size_t i = 0; i < kvs->num_kvs; i++) {
- if (i != 0) append_chr(',', &s, &sz, &cap);
- append_esc_str(reinterpret_cast<const uint8_t*>(kvs->kvs[i].key),
- strlen(kvs->kvs[i].key), &s, &sz, &cap);
- gpr_free(kvs->kvs[i].key);
- append_chr(':', &s, &sz, &cap);
- append_str(kvs->kvs[i].value, &s, &sz, &cap);
- gpr_free(kvs->kvs[i].value);
- }
- append_chr('}', &s, &sz, &cap);
- append_chr(0, &s, &sz, &cap);
-
- gpr_free(kvs->kvs);
- return s;
-}
-
+ char* s = nullptr;
+ size_t sz = 0;
+ size_t cap = 0;
+ append_esc_str((const uint8_t*)GRPC_SLICE_START_PTR(slice),
+ GRPC_SLICE_LENGTH(slice), &s, &sz, &cap);
+ append_chr(0, &s, &sz, &cap);
+ return s;
+}
+
+static void collect_strs_kvs(grpc_error* err, kv_pairs* kvs) {
+ for (size_t which = 0; which < GRPC_ERROR_STR_MAX; ++which) {
+ uint8_t slot = err->strs[which];
+ if (slot != UINT8_MAX) {
+ append_kv(kvs, key_str(static_cast<grpc_error_strs>(which)),
+ fmt_str(*reinterpret_cast<grpc_slice*>(err->arena + slot)));
+ }
+ }
+}
+
+static char* key_time(grpc_error_times which) {
+ return gpr_strdup(error_time_name(which));
+}
+
+static char* fmt_time(gpr_timespec tm) {
+ char* out;
+ const char* pfx = "!!";
+ switch (tm.clock_type) {
+ case GPR_CLOCK_MONOTONIC:
+ pfx = "@monotonic:";
+ break;
+ case GPR_CLOCK_REALTIME:
+ pfx = "@";
+ break;
+ case GPR_CLOCK_PRECISE:
+ pfx = "@precise:";
+ break;
+ case GPR_TIMESPAN:
+ pfx = "";
+ break;
+ }
+ gpr_asprintf(&out, "\"%s%" PRId64 ".%09d\"", pfx, tm.tv_sec, tm.tv_nsec);
+ return out;
+}
+
+static void collect_times_kvs(grpc_error* err, kv_pairs* kvs) {
+ for (size_t which = 0; which < GRPC_ERROR_TIME_MAX; ++which) {
+ uint8_t slot = err->times[which];
+ if (slot != UINT8_MAX) {
+ append_kv(kvs, key_time(static_cast<grpc_error_times>(which)),
+ fmt_time(*reinterpret_cast<gpr_timespec*>(err->arena + slot)));
+ }
+ }
+}
+
+static void add_errs(grpc_error* err, char** s, size_t* sz, size_t* cap) {
+ uint8_t slot = err->first_err;
+ bool first = true;
+ while (slot != UINT8_MAX) {
+ grpc_linked_error* lerr =
+ reinterpret_cast<grpc_linked_error*>(err->arena + slot);
+ if (!first) append_chr(',', s, sz, cap);
+ first = false;
+ const char* e = grpc_error_string(lerr->err);
+ append_str(e, s, sz, cap);
+ GPR_ASSERT(err->last_err == slot ? lerr->next == UINT8_MAX
+ : lerr->next != UINT8_MAX);
+ slot = lerr->next;
+ }
+}
+
+static char* errs_string(grpc_error* err) {
+ char* s = nullptr;
+ size_t sz = 0;
+ size_t cap = 0;
+ append_chr('[', &s, &sz, &cap);
+ add_errs(err, &s, &sz, &cap);
+ append_chr(']', &s, &sz, &cap);
+ append_chr(0, &s, &sz, &cap);
+ return s;
+}
+
+static int cmp_kvs(const void* a, const void* b) {
+ const kv_pair* ka = static_cast<const kv_pair*>(a);
+ const kv_pair* kb = static_cast<const kv_pair*>(b);
+ return strcmp(ka->key, kb->key);
+}
+
+static char* finish_kvs(kv_pairs* kvs) {
+ char* s = nullptr;
+ size_t sz = 0;
+ size_t cap = 0;
+
+ append_chr('{', &s, &sz, &cap);
+ for (size_t i = 0; i < kvs->num_kvs; i++) {
+ if (i != 0) append_chr(',', &s, &sz, &cap);
+ append_esc_str(reinterpret_cast<const uint8_t*>(kvs->kvs[i].key),
+ strlen(kvs->kvs[i].key), &s, &sz, &cap);
+ gpr_free(kvs->kvs[i].key);
+ append_chr(':', &s, &sz, &cap);
+ append_str(kvs->kvs[i].value, &s, &sz, &cap);
+ gpr_free(kvs->kvs[i].value);
+ }
+ append_chr('}', &s, &sz, &cap);
+ append_chr(0, &s, &sz, &cap);
+
+ gpr_free(kvs->kvs);
+ return s;
+}
+
// Newly allocated error string is stored into err object via atomic cas, and this drives coverity crazy
// Disable allocation checks as the code is fine.
// coverity[-alloc]
-const char* grpc_error_string(grpc_error* err) {
- GPR_TIMER_SCOPE("grpc_error_string", 0);
- if (err == GRPC_ERROR_NONE) return no_error_string;
- if (err == GRPC_ERROR_OOM) return oom_error_string;
- if (err == GRPC_ERROR_CANCELLED) return cancelled_error_string;
-
- void* p = (void*)gpr_atm_acq_load(&err->atomics.error_string);
- if (p != nullptr) {
- return static_cast<const char*>(p);
- }
-
- kv_pairs kvs;
- memset(&kvs, 0, sizeof(kvs));
-
- collect_ints_kvs(err, &kvs);
- collect_strs_kvs(err, &kvs);
- collect_times_kvs(err, &kvs);
- if (err->first_err != UINT8_MAX) {
- append_kv(&kvs, gpr_strdup("referenced_errors"), errs_string(err));
- }
-
- qsort(kvs.kvs, kvs.num_kvs, sizeof(kv_pair), cmp_kvs);
-
- char* out = finish_kvs(&kvs);
-
- if (!gpr_atm_rel_cas(&err->atomics.error_string, 0, (gpr_atm)out)) {
- gpr_free(out);
- out = (char*)gpr_atm_acq_load(&err->atomics.error_string);
- }
-
- return out;
-}
-
-grpc_error* grpc_os_error(const char* file, int line, int err,
- const char* call_name) {
- return grpc_error_set_str(
- grpc_error_set_str(
- grpc_error_set_int(
- grpc_error_create(file, line,
+const char* grpc_error_string(grpc_error* err) {
+ GPR_TIMER_SCOPE("grpc_error_string", 0);
+ if (err == GRPC_ERROR_NONE) return no_error_string;
+ if (err == GRPC_ERROR_OOM) return oom_error_string;
+ if (err == GRPC_ERROR_CANCELLED) return cancelled_error_string;
+
+ void* p = (void*)gpr_atm_acq_load(&err->atomics.error_string);
+ if (p != nullptr) {
+ return static_cast<const char*>(p);
+ }
+
+ kv_pairs kvs;
+ memset(&kvs, 0, sizeof(kvs));
+
+ collect_ints_kvs(err, &kvs);
+ collect_strs_kvs(err, &kvs);
+ collect_times_kvs(err, &kvs);
+ if (err->first_err != UINT8_MAX) {
+ append_kv(&kvs, gpr_strdup("referenced_errors"), errs_string(err));
+ }
+
+ qsort(kvs.kvs, kvs.num_kvs, sizeof(kv_pair), cmp_kvs);
+
+ char* out = finish_kvs(&kvs);
+
+ if (!gpr_atm_rel_cas(&err->atomics.error_string, 0, (gpr_atm)out)) {
+ gpr_free(out);
+ out = (char*)gpr_atm_acq_load(&err->atomics.error_string);
+ }
+
+ return out;
+}
+
+grpc_error* grpc_os_error(const char* file, int line, int err,
+ const char* call_name) {
+ return grpc_error_set_str(
+ grpc_error_set_str(
+ grpc_error_set_int(
+ grpc_error_create(file, line,
grpc_slice_from_static_string(strerror(err)),
- nullptr, 0),
- GRPC_ERROR_INT_ERRNO, err),
- GRPC_ERROR_STR_OS_ERROR,
- grpc_slice_from_static_string(strerror(err))),
- GRPC_ERROR_STR_SYSCALL, grpc_slice_from_copied_string(call_name));
-}
-
-#ifdef GPR_WINDOWS
-grpc_error* grpc_wsa_error(const char* file, int line, int err,
- const char* call_name) {
- char* utf8_message = gpr_format_message(err);
- grpc_error* error = grpc_error_set_str(
- grpc_error_set_str(
- grpc_error_set_int(
- grpc_error_create(file, line,
- grpc_slice_from_static_string("OS Error"), NULL,
- 0),
- GRPC_ERROR_INT_WSA_ERROR, err),
- GRPC_ERROR_STR_OS_ERROR, grpc_slice_from_copied_string(utf8_message)),
- GRPC_ERROR_STR_SYSCALL, grpc_slice_from_static_string(call_name));
- gpr_free(utf8_message);
- return error;
-}
-#endif
-
+ nullptr, 0),
+ GRPC_ERROR_INT_ERRNO, err),
+ GRPC_ERROR_STR_OS_ERROR,
+ grpc_slice_from_static_string(strerror(err))),
+ GRPC_ERROR_STR_SYSCALL, grpc_slice_from_copied_string(call_name));
+}
+
+#ifdef GPR_WINDOWS
+grpc_error* grpc_wsa_error(const char* file, int line, int err,
+ const char* call_name) {
+ char* utf8_message = gpr_format_message(err);
+ grpc_error* error = grpc_error_set_str(
+ grpc_error_set_str(
+ grpc_error_set_int(
+ grpc_error_create(file, line,
+ grpc_slice_from_static_string("OS Error"), NULL,
+ 0),
+ GRPC_ERROR_INT_WSA_ERROR, err),
+ GRPC_ERROR_STR_OS_ERROR, grpc_slice_from_copied_string(utf8_message)),
+ GRPC_ERROR_STR_SYSCALL, grpc_slice_from_static_string(call_name));
+ gpr_free(utf8_message);
+ return error;
+}
+#endif
+
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);
- return false;
-}
+ const char* msg = grpc_error_string(error);
+ gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "%s: %s", what, msg);
+ GRPC_ERROR_UNREF(error);
+ return false;
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error.h b/contrib/libs/grpc/src/core/lib/iomgr/error.h
index ac3ff876289..556863d361e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/error.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/error.h
@@ -1,44 +1,44 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_ERROR_H
#define GRPC_CORE_LIB_IOMGR_ERROR_H
-#include <grpc/support/port_platform.h>
-
-#include <inttypes.h>
+#include <grpc/support/port_platform.h>
+
+#include <inttypes.h>
#include <stdbool.h>
-#include <grpc/slice.h>
+#include <grpc/slice.h>
#include <grpc/status.h>
-#include <grpc/support/log.h>
+#include <grpc/support/log.h>
#include <grpc/support/time.h>
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.h"
/// Opaque representation of an error.
-/// See https://github.com/grpc/grpc/blob/master/doc/core/grpc-error.md for a
-/// full write up of this object.
-
+/// See https://github.com/grpc/grpc/blob/master/doc/core/grpc-error.md for a
+/// full write up of this object.
+
typedef struct grpc_error grpc_error;
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount;
-
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount;
+
typedef enum {
/// 'errno' from the operating system
GRPC_ERROR_INT_ERRNO,
@@ -74,9 +74,9 @@ typedef enum {
GRPC_ERROR_INT_OCCURRED_DURING_WRITE,
/// channel connectivity state associated with the error
GRPC_ERROR_INT_CHANNEL_CONNECTIVITY_STATE,
-
- /// Must always be last
- GRPC_ERROR_INT_MAX,
+
+ /// Must always be last
+ GRPC_ERROR_INT_MAX,
} grpc_error_ints;
typedef enum {
@@ -99,33 +99,33 @@ typedef enum {
/// filename that we were trying to read/write when this error occurred
GRPC_ERROR_STR_FILENAME,
/// which data was queued for writing when the error occurred
- GRPC_ERROR_STR_QUEUED_BUFFERS,
- /// key associated with the error
- GRPC_ERROR_STR_KEY,
- /// value associated with the error
- GRPC_ERROR_STR_VALUE,
-
- /// Must always be last
- GRPC_ERROR_STR_MAX,
+ GRPC_ERROR_STR_QUEUED_BUFFERS,
+ /// key associated with the error
+ GRPC_ERROR_STR_KEY,
+ /// value associated with the error
+ GRPC_ERROR_STR_VALUE,
+
+ /// Must always be last
+ GRPC_ERROR_STR_MAX,
} grpc_error_strs;
typedef enum {
/// timestamp of error creation
GRPC_ERROR_TIME_CREATED,
-
- /// Must always be last
- GRPC_ERROR_TIME_MAX,
+
+ /// Must always be last
+ GRPC_ERROR_TIME_MAX,
} grpc_error_times;
/// The following "special" errors can be propagated without allocating memory.
-/// They are always even so that other code (particularly combiner locks,
-/// polling engines) can safely use the lower bit for themselves.
+/// They are always even so that other code (particularly combiner locks,
+/// polling engines) can safely use the lower bit for themselves.
-#define GRPC_ERROR_NONE ((grpc_error*)NULL)
+#define GRPC_ERROR_NONE ((grpc_error*)NULL)
#define GRPC_ERROR_RESERVED_1 ((grpc_error*)1)
-#define GRPC_ERROR_OOM ((grpc_error*)2)
+#define GRPC_ERROR_OOM ((grpc_error*)2)
#define GRPC_ERROR_RESERVED_2 ((grpc_error*)3)
-#define GRPC_ERROR_CANCELLED ((grpc_error*)4)
+#define GRPC_ERROR_CANCELLED ((grpc_error*)4)
#define GRPC_ERROR_SPECIAL_MAX GRPC_ERROR_CANCELLED
inline bool grpc_error_is_special(struct grpc_error* err) {
@@ -137,7 +137,7 @@ inline bool grpc_error_is_special(struct grpc_error* err) {
void grpc_disable_error_creation();
void grpc_enable_error_creation();
-const char* grpc_error_string(grpc_error* error);
+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,
@@ -151,26 +151,26 @@ grpc_error* grpc_error_create(const char* file, int line,
/// err = grpc_error_create(x, y, z, r, nr) is equivalent to:
/// err = grpc_error_create(x, y, z, NULL, 0);
/// for (i=0; i<nr; i++) err = grpc_error_add_child(err, r[i]);
-#define GRPC_ERROR_CREATE_FROM_STATIC_STRING(desc) \
- grpc_error_create(__FILE__, __LINE__, grpc_slice_from_static_string(desc), \
- NULL, 0)
-#define GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc) \
- grpc_error_create(__FILE__, __LINE__, grpc_slice_from_copied_string(desc), \
- NULL, 0)
+#define GRPC_ERROR_CREATE_FROM_STATIC_STRING(desc) \
+ grpc_error_create(__FILE__, __LINE__, grpc_slice_from_static_string(desc), \
+ NULL, 0)
+#define GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc) \
+ grpc_error_create(__FILE__, __LINE__, grpc_slice_from_copied_string(desc), \
+ NULL, 0)
// Create an error that references some other errors. This function adds a
// reference to each error in errs - it does not consume an existing reference
-#define GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(desc, errs, count) \
- grpc_error_create(__FILE__, __LINE__, grpc_slice_from_static_string(desc), \
- errs, count)
-#define GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(desc, errs, count) \
- grpc_error_create(__FILE__, __LINE__, grpc_slice_from_copied_string(desc), \
- errs, count)
+#define GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(desc, errs, count) \
+ grpc_error_create(__FILE__, __LINE__, grpc_slice_from_static_string(desc), \
+ errs, count)
+#define GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(desc, errs, count) \
+ 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)
-#ifndef NDEBUG
+#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);
inline grpc_error* grpc_error_ref(grpc_error* err, const char* file, int line) {
@@ -181,8 +181,8 @@ inline void grpc_error_unref(grpc_error* err, const char* file, int line) {
if (grpc_error_is_special(err)) return;
grpc_error_do_unref(err, file, line);
}
-#define GRPC_ERROR_REF(err) grpc_error_ref(err, __FILE__, __LINE__)
-#define GRPC_ERROR_UNREF(err) grpc_error_unref(err, __FILE__, __LINE__)
+#define GRPC_ERROR_REF(err) grpc_error_ref(err, __FILE__, __LINE__)
+#define GRPC_ERROR_UNREF(err) grpc_error_unref(err, __FILE__, __LINE__)
#else
grpc_error* grpc_error_do_ref(grpc_error* err);
void grpc_error_do_unref(grpc_error* err);
@@ -217,24 +217,24 @@ static grpc_error* grpc_error_create_from_vector(const char* file, int line,
return error;
}
-grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which,
+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
/// intptr_t for `p`, even if the value of `p` is not used.
-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,
+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;
-/// 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,
- grpc_slice* s);
+/// 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,
+ grpc_slice* s);
/// Add a child error: an error that is believed to have contributed to this
/// error occurring. Allows root causing high level errors from lower level
-/// errors that contributed to them. The src error takes ownership of the
-/// child error.
+/// errors that contributed to them. The src error takes ownership of the
+/// child error.
///
/// Edge Conditions -
/// 1) If either of \a src or \a child is GRPC_ERROR_NONE, returns a reference
@@ -242,22 +242,22 @@ bool grpc_error_get_str(grpc_error* error, grpc_error_strs which,
/// returns GRPC_ERROR_NONE. 3) If \a src and \a child point to the same error,
/// returns a single reference. (Note that, 2 references should have been
/// received to the error in this case.)
-grpc_error* grpc_error_add_child(grpc_error* src,
- grpc_error* child) GRPC_MUST_USE_RESULT;
-
-grpc_error* grpc_os_error(const char* file, int line, int err,
- const char* call_name) GRPC_MUST_USE_RESULT;
-
-inline grpc_error* grpc_assert_never_ok(grpc_error* error) {
- GPR_ASSERT(error != GRPC_ERROR_NONE);
- return error;
-}
-
+grpc_error* grpc_error_add_child(grpc_error* src,
+ grpc_error* child) GRPC_MUST_USE_RESULT;
+
+grpc_error* grpc_os_error(const char* file, int line, int err,
+ const char* call_name) GRPC_MUST_USE_RESULT;
+
+inline grpc_error* grpc_assert_never_ok(grpc_error* error) {
+ GPR_ASSERT(error != GRPC_ERROR_NONE);
+ return error;
+}
+
/// create an error associated with errno!=0 (an 'operating system' error)
#define GRPC_OS_ERROR(err, call_name) \
- grpc_assert_never_ok(grpc_os_error(__FILE__, __LINE__, err, call_name))
-grpc_error* grpc_wsa_error(const char* file, int line, int err,
- const char* call_name) GRPC_MUST_USE_RESULT;
+ grpc_assert_never_ok(grpc_os_error(__FILE__, __LINE__, err, call_name))
+grpc_error* grpc_wsa_error(const char* file, int line, int err,
+ const char* call_name) GRPC_MUST_USE_RESULT;
/// windows only: create an error associated with WSAGetLastError()!=0
#define GRPC_WSA_ERROR(err, call_name) \
grpc_wsa_error(__FILE__, __LINE__, err, call_name)
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 7b0cbd6d98f..d52bab72751 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/error_internal.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/error_internal.h
@@ -1,61 +1,61 @@
-/*
- *
- * 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_IOMGR_ERROR_INTERNAL_H
-#define GRPC_CORE_LIB_IOMGR_ERROR_INTERNAL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <inttypes.h>
-#include <stdbool.h> // TODO, do we need this?
-
-#include <grpc/support/sync.h>
-#include "src/core/lib/iomgr/error.h"
-
-typedef struct grpc_linked_error grpc_linked_error;
-
-struct grpc_linked_error {
- grpc_error* err;
- uint8_t next;
-};
-
-// c core representation of an error. See error.h for high level description of
-// this object.
-struct grpc_error {
- // All atomics in grpc_error must be stored in this nested struct. The rest of
- // the object is memcpy-ed in bulk in copy_and_unref.
- struct atomics {
- gpr_refcount refs;
- gpr_atm error_string;
- } atomics;
- // These arrays index into dynamic arena at the bottom of the struct.
- // UINT8_MAX is used as a sentinel value.
- uint8_t ints[GRPC_ERROR_INT_MAX];
- 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
+/*
+ *
+ * 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_IOMGR_ERROR_INTERNAL_H
+#define GRPC_CORE_LIB_IOMGR_ERROR_INTERNAL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <inttypes.h>
+#include <stdbool.h> // TODO, do we need this?
+
+#include <grpc/support/sync.h>
+#include "src/core/lib/iomgr/error.h"
+
+typedef struct grpc_linked_error grpc_linked_error;
+
+struct grpc_linked_error {
+ grpc_error* err;
+ uint8_t next;
+};
+
+// c core representation of an error. See error.h for high level description of
+// this object.
+struct grpc_error {
+ // All atomics in grpc_error must be stored in this nested struct. The rest of
+ // the object is memcpy-ed in bulk in copy_and_unref.
+ struct atomics {
+ gpr_refcount refs;
+ gpr_atm error_string;
+ } atomics;
+ // These arrays index into dynamic arena at the bottom of the struct.
+ // UINT8_MAX is used as a sentinel value.
+ uint8_t ints[GRPC_ERROR_INT_MAX];
+ 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.
- uint8_t first_err;
- uint8_t last_err;
- // The arena is dynamically reallocated with a grow factor of 1.5.
- uint8_t arena_size;
- uint8_t arena_capacity;
- intptr_t arena[0];
-};
-
-#endif /* GRPC_CORE_LIB_IOMGR_ERROR_INTERNAL_H */
+ uint8_t first_err;
+ uint8_t last_err;
+ // The arena is dynamically reallocated with a grow factor of 1.5.
+ uint8_t arena_size;
+ uint8_t arena_capacity;
+ intptr_t arena[0];
+};
+
+#endif /* GRPC_CORE_LIB_IOMGR_ERROR_INTERNAL_H */
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 f09dcee0c06..e8c160c210b 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#include <grpc/support/log.h>
-
-/* This polling engine is only relevant on linux kernels supporting epoll
- epoll_create() or epoll_create1() */
-#ifdef GRPC_LINUX_EPOLL
-#include "src/core/lib/iomgr/ev_epoll1_linux.h"
-
-#include <assert.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <poll.h>
-#include <pthread.h>
-#include <string.h>
-#include <sys/epoll.h>
-#include <sys/socket.h>
-#include <unistd.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#include <grpc/support/log.h>
+
+/* This polling engine is only relevant on linux kernels supporting epoll
+ epoll_create() or epoll_create1() */
+#ifdef GRPC_LINUX_EPOLL
+#include "src/core/lib/iomgr/ev_epoll1_linux.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <poll.h>
+#include <pthread.h>
+#include <string.h>
+#include <sys/epoll.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
#include <util/generic/string.h>
#include <vector>
@@ -45,98 +45,98 @@
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/cpu.h>
-
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gpr/string.h"
-#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/iomgr/block_annotate.h"
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/lockfree_event.h"
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-#include "src/core/lib/profiling/timers.h"
-
-static grpc_wakeup_fd global_wakeup_fd;
-
-/*******************************************************************************
- * Singleton epoll set related fields
- */
-
-#define MAX_EPOLL_EVENTS 100
-#define MAX_EPOLL_EVENTS_HANDLED_PER_ITERATION 1
-
-/* NOTE ON SYNCHRONIZATION:
- * - Fields in this struct are only modified by the designated poller. Hence
- * there is no need for any locks to protect the struct.
- * - num_events and cursor fields have to be of atomic type to provide memory
- * visibility guarantees only. i.e In case of multiple pollers, the designated
- * polling thread keeps changing; the thread that wrote these values may be
- * different from the thread reading the values
- */
-typedef struct epoll_set {
- int epfd;
-
- /* The epoll_events after the last call to epoll_wait() */
- struct epoll_event events[MAX_EPOLL_EVENTS];
-
- /* The number of epoll_events after the last call to epoll_wait() */
- gpr_atm num_events;
-
- /* Index of the first event in epoll_events that has to be processed. This
- * field is only valid if num_events > 0 */
- gpr_atm cursor;
-} epoll_set;
-
-/* The global singleton epoll set */
-static epoll_set g_epoll_set;
-
-static int epoll_create_and_cloexec() {
-#ifdef GRPC_LINUX_EPOLL_CREATE1
- int fd = epoll_create1(EPOLL_CLOEXEC);
- if (fd < 0) {
- gpr_log(GPR_ERROR, "epoll_create1 unavailable");
- }
-#else
- int fd = epoll_create(MAX_EPOLL_EVENTS);
- if (fd < 0) {
- gpr_log(GPR_ERROR, "epoll_create unavailable");
- } else if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
- gpr_log(GPR_ERROR, "fcntl following epoll_create failed");
- return -1;
- }
-#endif
- return fd;
-}
-
-/* Must be called *only* once */
-static bool epoll_set_init() {
- g_epoll_set.epfd = epoll_create_and_cloexec();
- if (g_epoll_set.epfd < 0) {
- return false;
- }
-
- gpr_log(GPR_INFO, "grpc epoll fd: %d", g_epoll_set.epfd);
- gpr_atm_no_barrier_store(&g_epoll_set.num_events, 0);
- gpr_atm_no_barrier_store(&g_epoll_set.cursor, 0);
- return true;
-}
-
-/* epoll_set_init() MUST be called before calling this. */
-static void epoll_set_shutdown() {
- if (g_epoll_set.epfd >= 0) {
- close(g_epoll_set.epfd);
- g_epoll_set.epfd = -1;
- }
-}
-
-/*******************************************************************************
- * Fd Declarations
- */
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/cpu.h>
+
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gpr/string.h"
+#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/iomgr/block_annotate.h"
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/lockfree_event.h"
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+#include "src/core/lib/profiling/timers.h"
+
+static grpc_wakeup_fd global_wakeup_fd;
+
+/*******************************************************************************
+ * Singleton epoll set related fields
+ */
+
+#define MAX_EPOLL_EVENTS 100
+#define MAX_EPOLL_EVENTS_HANDLED_PER_ITERATION 1
+
+/* NOTE ON SYNCHRONIZATION:
+ * - Fields in this struct are only modified by the designated poller. Hence
+ * there is no need for any locks to protect the struct.
+ * - num_events and cursor fields have to be of atomic type to provide memory
+ * visibility guarantees only. i.e In case of multiple pollers, the designated
+ * polling thread keeps changing; the thread that wrote these values may be
+ * different from the thread reading the values
+ */
+typedef struct epoll_set {
+ int epfd;
+
+ /* The epoll_events after the last call to epoll_wait() */
+ struct epoll_event events[MAX_EPOLL_EVENTS];
+
+ /* The number of epoll_events after the last call to epoll_wait() */
+ gpr_atm num_events;
+
+ /* Index of the first event in epoll_events that has to be processed. This
+ * field is only valid if num_events > 0 */
+ gpr_atm cursor;
+} epoll_set;
+
+/* The global singleton epoll set */
+static epoll_set g_epoll_set;
+
+static int epoll_create_and_cloexec() {
+#ifdef GRPC_LINUX_EPOLL_CREATE1
+ int fd = epoll_create1(EPOLL_CLOEXEC);
+ if (fd < 0) {
+ gpr_log(GPR_ERROR, "epoll_create1 unavailable");
+ }
+#else
+ int fd = epoll_create(MAX_EPOLL_EVENTS);
+ if (fd < 0) {
+ gpr_log(GPR_ERROR, "epoll_create unavailable");
+ } else if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
+ gpr_log(GPR_ERROR, "fcntl following epoll_create failed");
+ return -1;
+ }
+#endif
+ return fd;
+}
+
+/* Must be called *only* once */
+static bool epoll_set_init() {
+ g_epoll_set.epfd = epoll_create_and_cloexec();
+ if (g_epoll_set.epfd < 0) {
+ return false;
+ }
+
+ gpr_log(GPR_INFO, "grpc epoll fd: %d", g_epoll_set.epfd);
+ gpr_atm_no_barrier_store(&g_epoll_set.num_events, 0);
+ gpr_atm_no_barrier_store(&g_epoll_set.cursor, 0);
+ return true;
+}
+
+/* epoll_set_init() MUST be called before calling this. */
+static void epoll_set_shutdown() {
+ if (g_epoll_set.epfd >= 0) {
+ close(g_epoll_set.epfd);
+ g_epoll_set.epfd = -1;
+ }
+}
+
+/*******************************************************************************
+ * Fd Declarations
+ */
+
/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */
struct grpc_fork_fd_list {
grpc_fd* fd;
@@ -144,61 +144,61 @@ struct grpc_fork_fd_list {
grpc_fd* prev;
};
-struct grpc_fd {
- int fd;
-
- grpc_core::ManualConstructor<grpc_core::LockfreeEvent> read_closure;
- grpc_core::ManualConstructor<grpc_core::LockfreeEvent> write_closure;
+struct grpc_fd {
+ int fd;
+
+ grpc_core::ManualConstructor<grpc_core::LockfreeEvent> read_closure;
+ grpc_core::ManualConstructor<grpc_core::LockfreeEvent> write_closure;
grpc_core::ManualConstructor<grpc_core::LockfreeEvent> error_closure;
-
- struct grpc_fd* freelist_next;
-
+
+ struct grpc_fd* freelist_next;
+
grpc_iomgr_object iomgr_object;
-
+
/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */
grpc_fork_fd_list* fork_fd_list;
-};
-
-static void fd_global_init(void);
-static void fd_global_shutdown(void);
-
-/*******************************************************************************
- * Pollset Declarations
- */
-
-typedef enum { UNKICKED, KICKED, DESIGNATED_POLLER } kick_state;
-
-static const char* kick_state_string(kick_state st) {
- switch (st) {
- case UNKICKED:
- return "UNKICKED";
- case KICKED:
- return "KICKED";
- case DESIGNATED_POLLER:
- return "DESIGNATED_POLLER";
- }
- GPR_UNREACHABLE_CODE(return "UNKNOWN");
-}
-
-struct grpc_pollset_worker {
- kick_state state;
- int kick_state_mutator; // which line of code last changed kick state
- bool initialized_cv;
- grpc_pollset_worker* next;
- grpc_pollset_worker* prev;
- gpr_cv cv;
- grpc_closure_list schedule_on_end_work;
-};
-
-#define SET_KICK_STATE(worker, kick_state) \
- do { \
- (worker)->state = (kick_state); \
- (worker)->kick_state_mutator = __LINE__; \
- } while (false)
-
-#define MAX_NEIGHBORHOODS 1024
-
-typedef struct pollset_neighborhood {
+};
+
+static void fd_global_init(void);
+static void fd_global_shutdown(void);
+
+/*******************************************************************************
+ * Pollset Declarations
+ */
+
+typedef enum { UNKICKED, KICKED, DESIGNATED_POLLER } kick_state;
+
+static const char* kick_state_string(kick_state st) {
+ switch (st) {
+ case UNKICKED:
+ return "UNKICKED";
+ case KICKED:
+ return "KICKED";
+ case DESIGNATED_POLLER:
+ return "DESIGNATED_POLLER";
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
+
+struct grpc_pollset_worker {
+ kick_state state;
+ int kick_state_mutator; // which line of code last changed kick state
+ bool initialized_cv;
+ grpc_pollset_worker* next;
+ grpc_pollset_worker* prev;
+ gpr_cv cv;
+ grpc_closure_list schedule_on_end_work;
+};
+
+#define SET_KICK_STATE(worker, kick_state) \
+ do { \
+ (worker)->state = (kick_state); \
+ (worker)->kick_state_mutator = __LINE__; \
+ } while (false)
+
+#define MAX_NEIGHBORHOODS 1024
+
+typedef struct pollset_neighborhood {
union {
char pad[GPR_CACHELINE_SIZE];
struct {
@@ -206,97 +206,97 @@ typedef struct pollset_neighborhood {
grpc_pollset* active_root;
};
};
-} pollset_neighborhood;
-
-struct grpc_pollset {
- gpr_mu mu;
- pollset_neighborhood* neighborhood;
- bool reassigning_neighborhood;
- grpc_pollset_worker* root_worker;
- bool kicked_without_poller;
-
- /* Set to true if the pollset is observed to have no workers available to
- poll */
- bool seen_inactive;
- bool shutting_down; /* Is the pollset shutting down ? */
+} pollset_neighborhood;
+
+struct grpc_pollset {
+ gpr_mu mu;
+ pollset_neighborhood* neighborhood;
+ bool reassigning_neighborhood;
+ grpc_pollset_worker* root_worker;
+ bool kicked_without_poller;
+
+ /* Set to true if the pollset is observed to have no workers available to
+ poll */
+ bool seen_inactive;
+ bool shutting_down; /* Is the pollset shutting down ? */
grpc_closure* shutdown_closure; /* Called after shutdown is complete */
-
- /* Number of workers who are *about-to* attach themselves to the pollset
- * worker list */
- int begin_refs;
-
- grpc_pollset* next;
- grpc_pollset* prev;
-};
-
-/*******************************************************************************
- * Pollset-set Declarations
- */
-
-struct grpc_pollset_set {
- char unused;
-};
-
-/*******************************************************************************
- * Common helpers
- */
-
-static bool append_error(grpc_error** composite, grpc_error* error,
- const char* desc) {
- if (error == GRPC_ERROR_NONE) return true;
- if (*composite == GRPC_ERROR_NONE) {
- *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc);
- }
- *composite = grpc_error_add_child(*composite, error);
- return false;
-}
-
-/*******************************************************************************
- * Fd Definitions
- */
-
-/* We need to keep a freelist not because of any concerns of malloc performance
- * but instead so that implementations with multiple threads in (for example)
- * epoll_wait deal with the race between pollset removal and incoming poll
- * notifications.
- *
- * The problem is that the poller ultimately holds a reference to this
- * object, so it is very difficult to know when is safe to free it, at least
- * without some expensive synchronization.
- *
- * If we keep the object freelisted, in the worst case losing this race just
- * becomes a spurious read notification on a reused fd.
- */
-
-/* The alarm system needs to be able to wakeup 'some poller' sometimes
- * (specifically when a new alarm needs to be triggered earlier than the next
- * alarm 'epoch'). This wakeup_fd gives us something to alert on when such a
- * case occurs. */
-
-static grpc_fd* fd_freelist = nullptr;
-static gpr_mu fd_freelist_mu;
-
+
+ /* Number of workers who are *about-to* attach themselves to the pollset
+ * worker list */
+ int begin_refs;
+
+ grpc_pollset* next;
+ grpc_pollset* prev;
+};
+
+/*******************************************************************************
+ * Pollset-set Declarations
+ */
+
+struct grpc_pollset_set {
+ char unused;
+};
+
+/*******************************************************************************
+ * Common helpers
+ */
+
+static bool append_error(grpc_error** composite, grpc_error* error,
+ const char* desc) {
+ if (error == GRPC_ERROR_NONE) return true;
+ if (*composite == GRPC_ERROR_NONE) {
+ *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc);
+ }
+ *composite = grpc_error_add_child(*composite, error);
+ return false;
+}
+
+/*******************************************************************************
+ * Fd Definitions
+ */
+
+/* We need to keep a freelist not because of any concerns of malloc performance
+ * but instead so that implementations with multiple threads in (for example)
+ * epoll_wait deal with the race between pollset removal and incoming poll
+ * notifications.
+ *
+ * The problem is that the poller ultimately holds a reference to this
+ * object, so it is very difficult to know when is safe to free it, at least
+ * without some expensive synchronization.
+ *
+ * If we keep the object freelisted, in the worst case losing this race just
+ * becomes a spurious read notification on a reused fd.
+ */
+
+/* The alarm system needs to be able to wakeup 'some poller' sometimes
+ * (specifically when a new alarm needs to be triggered earlier than the next
+ * alarm 'epoch'). This wakeup_fd gives us something to alert on when such a
+ * case occurs. */
+
+static grpc_fd* fd_freelist = nullptr;
+static gpr_mu fd_freelist_mu;
+
/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */
static grpc_fd* fork_fd_list_head = nullptr;
static gpr_mu fork_fd_list_mu;
-static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); }
-
-static void fd_global_shutdown(void) {
+static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); }
+
+static void fd_global_shutdown(void) {
// TODO(guantaol): We don't have a reasonable explanation about this
// lock()/unlock() pattern. It can be a valid barrier if there is at most one
// pending lock() at this point. Otherwise, there is still a possibility of
// use-after-free race. Need to reason about the code and/or clean it up.
- gpr_mu_lock(&fd_freelist_mu);
- gpr_mu_unlock(&fd_freelist_mu);
- while (fd_freelist != nullptr) {
- grpc_fd* fd = fd_freelist;
- fd_freelist = fd_freelist->freelist_next;
- gpr_free(fd);
- }
- gpr_mu_destroy(&fd_freelist_mu);
-}
-
+ gpr_mu_lock(&fd_freelist_mu);
+ gpr_mu_unlock(&fd_freelist_mu);
+ while (fd_freelist != nullptr) {
+ grpc_fd* fd = fd_freelist;
+ fd_freelist = fd_freelist->freelist_next;
+ gpr_free(fd);
+ }
+ gpr_mu_destroy(&fd_freelist_mu);
+}
+
static void fork_fd_list_add_grpc_fd(grpc_fd* fd) {
if (grpc_core::Fork::Enabled()) {
gpr_mu_lock(&fork_fd_list_mu);
@@ -330,39 +330,39 @@ static void fork_fd_list_remove_grpc_fd(grpc_fd* fd) {
}
static grpc_fd* fd_create(int fd, const char* name, bool track_err) {
- grpc_fd* new_fd = nullptr;
-
- gpr_mu_lock(&fd_freelist_mu);
- if (fd_freelist != nullptr) {
- new_fd = fd_freelist;
- fd_freelist = fd_freelist->freelist_next;
- }
- gpr_mu_unlock(&fd_freelist_mu);
-
- if (new_fd == nullptr) {
- new_fd = static_cast<grpc_fd*>(gpr_malloc(sizeof(grpc_fd)));
- new_fd->read_closure.Init();
- new_fd->write_closure.Init();
+ grpc_fd* new_fd = nullptr;
+
+ gpr_mu_lock(&fd_freelist_mu);
+ if (fd_freelist != nullptr) {
+ new_fd = fd_freelist;
+ fd_freelist = fd_freelist->freelist_next;
+ }
+ gpr_mu_unlock(&fd_freelist_mu);
+
+ if (new_fd == nullptr) {
+ new_fd = static_cast<grpc_fd*>(gpr_malloc(sizeof(grpc_fd)));
+ new_fd->read_closure.Init();
+ new_fd->write_closure.Init();
new_fd->error_closure.Init();
- }
- new_fd->fd = fd;
- new_fd->read_closure->InitEvent();
- new_fd->write_closure->InitEvent();
+ }
+ new_fd->fd = fd;
+ new_fd->read_closure->InitEvent();
+ new_fd->write_closure->InitEvent();
new_fd->error_closure->InitEvent();
-
- new_fd->freelist_next = nullptr;
-
+
+ new_fd->freelist_next = nullptr;
+
TString fd_name = y_absl::StrCat(name, " fd=", fd);
grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name.c_str());
fork_fd_list_add_grpc_fd(new_fd);
-#ifndef NDEBUG
+#ifndef NDEBUG
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
-
- struct epoll_event ev;
- ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLOUT | EPOLLET);
+ }
+#endif
+
+ struct epoll_event ev;
+ ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLOUT | EPOLLET);
/* Use the least significant bit of ev.data.ptr to store track_err. We expect
* the addresses to be word aligned. We need to store track_err to avoid
* synchronization issues when accessing it after receiving an event.
@@ -370,23 +370,23 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) {
* returned to the free list at that point. */
ev.data.ptr = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(new_fd) |
(track_err ? 1 : 0));
- if (epoll_ctl(g_epoll_set.epfd, EPOLL_CTL_ADD, fd, &ev) != 0) {
- gpr_log(GPR_ERROR, "epoll_ctl failed: %s", strerror(errno));
- }
-
- return new_fd;
-}
-
-static int fd_wrapped_fd(grpc_fd* fd) { return fd->fd; }
-
-/* if 'releasing_fd' is true, it means that we are going to detach the internal
- * fd from grpc_fd structure (i.e which means we should not be calling
- * shutdown() syscall on that fd) */
-static void fd_shutdown_internal(grpc_fd* fd, grpc_error* why,
- bool releasing_fd) {
- if (fd->read_closure->SetShutdown(GRPC_ERROR_REF(why))) {
- if (!releasing_fd) {
- shutdown(fd->fd, SHUT_RDWR);
+ if (epoll_ctl(g_epoll_set.epfd, EPOLL_CTL_ADD, fd, &ev) != 0) {
+ gpr_log(GPR_ERROR, "epoll_ctl failed: %s", strerror(errno));
+ }
+
+ return new_fd;
+}
+
+static int fd_wrapped_fd(grpc_fd* fd) { return fd->fd; }
+
+/* if 'releasing_fd' is true, it means that we are going to detach the internal
+ * fd from grpc_fd structure (i.e which means we should not be calling
+ * shutdown() syscall on that fd) */
+static void fd_shutdown_internal(grpc_fd* fd, grpc_error* why,
+ bool releasing_fd) {
+ 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;
@@ -394,860 +394,860 @@ static void fd_shutdown_internal(grpc_fd* fd, grpc_error* why,
0) {
gpr_log(GPR_ERROR, "epoll_ctl failed: %s", strerror(errno));
}
- }
- fd->write_closure->SetShutdown(GRPC_ERROR_REF(why));
+ }
+ fd->write_closure->SetShutdown(GRPC_ERROR_REF(why));
fd->error_closure->SetShutdown(GRPC_ERROR_REF(why));
- }
- GRPC_ERROR_UNREF(why);
-}
-
-/* Might be called multiple times */
-static void fd_shutdown(grpc_fd* fd, grpc_error* why) {
- fd_shutdown_internal(fd, why, false);
-}
-
-static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
+ }
+ GRPC_ERROR_UNREF(why);
+}
+
+/* Might be called multiple times */
+static void fd_shutdown(grpc_fd* fd, grpc_error* why) {
+ fd_shutdown_internal(fd, why, false);
+}
+
+static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
const char* reason) {
- grpc_error* error = GRPC_ERROR_NONE;
- bool is_release_fd = (release_fd != nullptr);
-
- if (!fd->read_closure->IsShutdown()) {
- fd_shutdown_internal(fd, GRPC_ERROR_CREATE_FROM_COPIED_STRING(reason),
- is_release_fd);
- }
-
- /* If release_fd is not NULL, we should be relinquishing control of the file
- descriptor fd->fd (but we still own the grpc_fd structure). */
- if (is_release_fd) {
- *release_fd = fd->fd;
+ grpc_error* error = GRPC_ERROR_NONE;
+ bool is_release_fd = (release_fd != nullptr);
+
+ if (!fd->read_closure->IsShutdown()) {
+ fd_shutdown_internal(fd, GRPC_ERROR_CREATE_FROM_COPIED_STRING(reason),
+ is_release_fd);
+ }
+
+ /* If release_fd is not NULL, we should be relinquishing control of the file
+ descriptor fd->fd (but we still own the grpc_fd structure). */
+ if (is_release_fd) {
+ *release_fd = fd->fd;
} else {
- close(fd->fd);
- }
-
+ close(fd->fd);
+ }
+
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, GRPC_ERROR_REF(error));
-
- grpc_iomgr_unregister_object(&fd->iomgr_object);
+
+ grpc_iomgr_unregister_object(&fd->iomgr_object);
fork_fd_list_remove_grpc_fd(fd);
- fd->read_closure->DestroyEvent();
- fd->write_closure->DestroyEvent();
+ fd->read_closure->DestroyEvent();
+ fd->write_closure->DestroyEvent();
fd->error_closure->DestroyEvent();
-
- gpr_mu_lock(&fd_freelist_mu);
- fd->freelist_next = fd_freelist;
- fd_freelist = fd;
- gpr_mu_unlock(&fd_freelist_mu);
-}
-
-static bool fd_is_shutdown(grpc_fd* fd) {
- return fd->read_closure->IsShutdown();
-}
-
-static void fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
- fd->read_closure->NotifyOn(closure);
-}
-
-static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
- fd->write_closure->NotifyOn(closure);
-}
-
+
+ gpr_mu_lock(&fd_freelist_mu);
+ fd->freelist_next = fd_freelist;
+ fd_freelist = fd;
+ gpr_mu_unlock(&fd_freelist_mu);
+}
+
+static bool fd_is_shutdown(grpc_fd* fd) {
+ return fd->read_closure->IsShutdown();
+}
+
+static void fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
+ fd->read_closure->NotifyOn(closure);
+}
+
+static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
+ fd->write_closure->NotifyOn(closure);
+}
+
static void fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) {
fd->error_closure->NotifyOn(closure);
-}
-
+}
+
static void fd_become_readable(grpc_fd* fd) { fd->read_closure->SetReady(); }
-static void fd_become_writable(grpc_fd* fd) { fd->write_closure->SetReady(); }
-
+static void fd_become_writable(grpc_fd* fd) { fd->write_closure->SetReady(); }
+
static void fd_has_errors(grpc_fd* fd) { fd->error_closure->SetReady(); }
-/*******************************************************************************
- * Pollset Definitions
- */
-
-GPR_TLS_DECL(g_current_thread_pollset);
-GPR_TLS_DECL(g_current_thread_worker);
-
-/* The designated poller */
-static gpr_atm g_active_poller;
-
-static pollset_neighborhood* g_neighborhoods;
-static size_t g_num_neighborhoods;
-
-/* Return true if first in list */
-static bool worker_insert(grpc_pollset* pollset, grpc_pollset_worker* worker) {
- if (pollset->root_worker == nullptr) {
- pollset->root_worker = worker;
- worker->next = worker->prev = worker;
- return true;
- } else {
- worker->next = pollset->root_worker;
- worker->prev = worker->next->prev;
- worker->next->prev = worker;
- worker->prev->next = worker;
- return false;
- }
-}
-
-/* Return true if last in list */
-typedef enum { EMPTIED, NEW_ROOT, REMOVED } worker_remove_result;
-
-static worker_remove_result worker_remove(grpc_pollset* pollset,
- grpc_pollset_worker* worker) {
- if (worker == pollset->root_worker) {
- if (worker == worker->next) {
- pollset->root_worker = nullptr;
- return EMPTIED;
- } else {
- pollset->root_worker = worker->next;
- worker->prev->next = worker->next;
- worker->next->prev = worker->prev;
- return NEW_ROOT;
- }
- } else {
- worker->prev->next = worker->next;
- worker->next->prev = worker->prev;
- return REMOVED;
- }
-}
-
-static size_t choose_neighborhood(void) {
- return static_cast<size_t>(gpr_cpu_current_cpu()) % g_num_neighborhoods;
-}
-
-static grpc_error* pollset_global_init(void) {
- gpr_tls_init(&g_current_thread_pollset);
- gpr_tls_init(&g_current_thread_worker);
- gpr_atm_no_barrier_store(&g_active_poller, 0);
- global_wakeup_fd.read_fd = -1;
- grpc_error* err = grpc_wakeup_fd_init(&global_wakeup_fd);
- if (err != GRPC_ERROR_NONE) return err;
- struct epoll_event ev;
- ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLET);
- ev.data.ptr = &global_wakeup_fd;
- if (epoll_ctl(g_epoll_set.epfd, EPOLL_CTL_ADD, global_wakeup_fd.read_fd,
- &ev) != 0) {
- return GRPC_OS_ERROR(errno, "epoll_ctl");
- }
- g_num_neighborhoods = GPR_CLAMP(gpr_cpu_num_cores(), 1, MAX_NEIGHBORHOODS);
- g_neighborhoods = static_cast<pollset_neighborhood*>(
- gpr_zalloc(sizeof(*g_neighborhoods) * g_num_neighborhoods));
- for (size_t i = 0; i < g_num_neighborhoods; i++) {
- gpr_mu_init(&g_neighborhoods[i].mu);
- }
- return GRPC_ERROR_NONE;
-}
-
-static void pollset_global_shutdown(void) {
- gpr_tls_destroy(&g_current_thread_pollset);
- gpr_tls_destroy(&g_current_thread_worker);
- if (global_wakeup_fd.read_fd != -1) grpc_wakeup_fd_destroy(&global_wakeup_fd);
- for (size_t i = 0; i < g_num_neighborhoods; i++) {
- gpr_mu_destroy(&g_neighborhoods[i].mu);
- }
- gpr_free(g_neighborhoods);
-}
-
-static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
- gpr_mu_init(&pollset->mu);
- *mu = &pollset->mu;
- pollset->neighborhood = &g_neighborhoods[choose_neighborhood()];
- pollset->reassigning_neighborhood = false;
- pollset->root_worker = nullptr;
- pollset->kicked_without_poller = false;
- pollset->seen_inactive = true;
- pollset->shutting_down = false;
- pollset->shutdown_closure = nullptr;
- pollset->begin_refs = 0;
- pollset->next = pollset->prev = nullptr;
-}
-
-static void pollset_destroy(grpc_pollset* pollset) {
- gpr_mu_lock(&pollset->mu);
- if (!pollset->seen_inactive) {
- pollset_neighborhood* neighborhood = pollset->neighborhood;
- gpr_mu_unlock(&pollset->mu);
- retry_lock_neighborhood:
- gpr_mu_lock(&neighborhood->mu);
- gpr_mu_lock(&pollset->mu);
- if (!pollset->seen_inactive) {
- if (pollset->neighborhood != neighborhood) {
- gpr_mu_unlock(&neighborhood->mu);
- neighborhood = pollset->neighborhood;
- gpr_mu_unlock(&pollset->mu);
- goto retry_lock_neighborhood;
- }
- pollset->prev->next = pollset->next;
- pollset->next->prev = pollset->prev;
- if (pollset == pollset->neighborhood->active_root) {
- pollset->neighborhood->active_root =
- pollset->next == pollset ? nullptr : pollset->next;
- }
- }
- gpr_mu_unlock(&pollset->neighborhood->mu);
- }
- gpr_mu_unlock(&pollset->mu);
- gpr_mu_destroy(&pollset->mu);
-}
-
-static grpc_error* pollset_kick_all(grpc_pollset* pollset) {
- GPR_TIMER_SCOPE("pollset_kick_all", 0);
- grpc_error* error = GRPC_ERROR_NONE;
- if (pollset->root_worker != nullptr) {
- grpc_pollset_worker* worker = pollset->root_worker;
- do {
- GRPC_STATS_INC_POLLSET_KICK();
- switch (worker->state) {
- case KICKED:
- GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
- break;
- case UNKICKED:
- SET_KICK_STATE(worker, KICKED);
- if (worker->initialized_cv) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
- gpr_cv_signal(&worker->cv);
- }
- break;
- case DESIGNATED_POLLER:
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
- SET_KICK_STATE(worker, KICKED);
- append_error(&error, grpc_wakeup_fd_wakeup(&global_wakeup_fd),
- "pollset_kick_all");
- break;
- }
-
- worker = worker->next;
- } while (worker != pollset->root_worker);
- }
- // TODO: sreek. Check if we need to set 'kicked_without_poller' to true here
- // in the else case
- return error;
-}
-
-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);
+/*******************************************************************************
+ * Pollset Definitions
+ */
+
+GPR_TLS_DECL(g_current_thread_pollset);
+GPR_TLS_DECL(g_current_thread_worker);
+
+/* The designated poller */
+static gpr_atm g_active_poller;
+
+static pollset_neighborhood* g_neighborhoods;
+static size_t g_num_neighborhoods;
+
+/* Return true if first in list */
+static bool worker_insert(grpc_pollset* pollset, grpc_pollset_worker* worker) {
+ if (pollset->root_worker == nullptr) {
+ pollset->root_worker = worker;
+ worker->next = worker->prev = worker;
+ return true;
+ } else {
+ worker->next = pollset->root_worker;
+ worker->prev = worker->next->prev;
+ worker->next->prev = worker;
+ worker->prev->next = worker;
+ return false;
+ }
+}
+
+/* Return true if last in list */
+typedef enum { EMPTIED, NEW_ROOT, REMOVED } worker_remove_result;
+
+static worker_remove_result worker_remove(grpc_pollset* pollset,
+ grpc_pollset_worker* worker) {
+ if (worker == pollset->root_worker) {
+ if (worker == worker->next) {
+ pollset->root_worker = nullptr;
+ return EMPTIED;
+ } else {
+ pollset->root_worker = worker->next;
+ worker->prev->next = worker->next;
+ worker->next->prev = worker->prev;
+ return NEW_ROOT;
+ }
+ } else {
+ worker->prev->next = worker->next;
+ worker->next->prev = worker->prev;
+ return REMOVED;
+ }
+}
+
+static size_t choose_neighborhood(void) {
+ return static_cast<size_t>(gpr_cpu_current_cpu()) % g_num_neighborhoods;
+}
+
+static grpc_error* pollset_global_init(void) {
+ gpr_tls_init(&g_current_thread_pollset);
+ gpr_tls_init(&g_current_thread_worker);
+ gpr_atm_no_barrier_store(&g_active_poller, 0);
+ global_wakeup_fd.read_fd = -1;
+ grpc_error* err = grpc_wakeup_fd_init(&global_wakeup_fd);
+ if (err != GRPC_ERROR_NONE) return err;
+ struct epoll_event ev;
+ ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLET);
+ ev.data.ptr = &global_wakeup_fd;
+ if (epoll_ctl(g_epoll_set.epfd, EPOLL_CTL_ADD, global_wakeup_fd.read_fd,
+ &ev) != 0) {
+ return GRPC_OS_ERROR(errno, "epoll_ctl");
+ }
+ g_num_neighborhoods = GPR_CLAMP(gpr_cpu_num_cores(), 1, MAX_NEIGHBORHOODS);
+ g_neighborhoods = static_cast<pollset_neighborhood*>(
+ gpr_zalloc(sizeof(*g_neighborhoods) * g_num_neighborhoods));
+ for (size_t i = 0; i < g_num_neighborhoods; i++) {
+ gpr_mu_init(&g_neighborhoods[i].mu);
+ }
+ return GRPC_ERROR_NONE;
+}
+
+static void pollset_global_shutdown(void) {
+ gpr_tls_destroy(&g_current_thread_pollset);
+ gpr_tls_destroy(&g_current_thread_worker);
+ if (global_wakeup_fd.read_fd != -1) grpc_wakeup_fd_destroy(&global_wakeup_fd);
+ for (size_t i = 0; i < g_num_neighborhoods; i++) {
+ gpr_mu_destroy(&g_neighborhoods[i].mu);
+ }
+ gpr_free(g_neighborhoods);
+}
+
+static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
+ gpr_mu_init(&pollset->mu);
+ *mu = &pollset->mu;
+ pollset->neighborhood = &g_neighborhoods[choose_neighborhood()];
+ pollset->reassigning_neighborhood = false;
+ pollset->root_worker = nullptr;
+ pollset->kicked_without_poller = false;
+ pollset->seen_inactive = true;
+ pollset->shutting_down = false;
+ pollset->shutdown_closure = nullptr;
+ pollset->begin_refs = 0;
+ pollset->next = pollset->prev = nullptr;
+}
+
+static void pollset_destroy(grpc_pollset* pollset) {
+ gpr_mu_lock(&pollset->mu);
+ if (!pollset->seen_inactive) {
+ pollset_neighborhood* neighborhood = pollset->neighborhood;
+ gpr_mu_unlock(&pollset->mu);
+ retry_lock_neighborhood:
+ gpr_mu_lock(&neighborhood->mu);
+ gpr_mu_lock(&pollset->mu);
+ if (!pollset->seen_inactive) {
+ if (pollset->neighborhood != neighborhood) {
+ gpr_mu_unlock(&neighborhood->mu);
+ neighborhood = pollset->neighborhood;
+ gpr_mu_unlock(&pollset->mu);
+ goto retry_lock_neighborhood;
+ }
+ pollset->prev->next = pollset->next;
+ pollset->next->prev = pollset->prev;
+ if (pollset == pollset->neighborhood->active_root) {
+ pollset->neighborhood->active_root =
+ pollset->next == pollset ? nullptr : pollset->next;
+ }
+ }
+ gpr_mu_unlock(&pollset->neighborhood->mu);
+ }
+ gpr_mu_unlock(&pollset->mu);
+ gpr_mu_destroy(&pollset->mu);
+}
+
+static grpc_error* pollset_kick_all(grpc_pollset* pollset) {
+ GPR_TIMER_SCOPE("pollset_kick_all", 0);
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (pollset->root_worker != nullptr) {
+ grpc_pollset_worker* worker = pollset->root_worker;
+ do {
+ GRPC_STATS_INC_POLLSET_KICK();
+ switch (worker->state) {
+ case KICKED:
+ GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
+ break;
+ case UNKICKED:
+ SET_KICK_STATE(worker, KICKED);
+ if (worker->initialized_cv) {
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
+ gpr_cv_signal(&worker->cv);
+ }
+ break;
+ case DESIGNATED_POLLER:
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
+ SET_KICK_STATE(worker, KICKED);
+ append_error(&error, grpc_wakeup_fd_wakeup(&global_wakeup_fd),
+ "pollset_kick_all");
+ break;
+ }
+
+ worker = worker->next;
+ } while (worker != pollset->root_worker);
+ }
+ // TODO: sreek. Check if we need to set 'kicked_without_poller' to true here
+ // in the else case
+ return error;
+}
+
+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);
- pollset->shutdown_closure = nullptr;
- }
-}
-
-static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
- GPR_TIMER_SCOPE("pollset_shutdown", 0);
- GPR_ASSERT(pollset->shutdown_closure == nullptr);
- GPR_ASSERT(!pollset->shutting_down);
- pollset->shutdown_closure = closure;
- pollset->shutting_down = true;
- GRPC_LOG_IF_ERROR("pollset_shutdown", pollset_kick_all(pollset));
- pollset_maybe_finish_shutdown(pollset);
-}
-
-static int poll_deadline_to_millis_timeout(grpc_millis millis) {
- if (millis == GRPC_MILLIS_INF_FUTURE) return -1;
- grpc_millis delta = millis - grpc_core::ExecCtx::Get()->Now();
- if (delta > INT_MAX) {
- return INT_MAX;
- } else if (delta < 0) {
- return 0;
- } else {
- return static_cast<int>(delta);
- }
-}
-
-/* Process the epoll events found by do_epoll_wait() function.
- - g_epoll_set.cursor points to the index of the first event to be processed
- - This function then processes up-to MAX_EPOLL_EVENTS_PER_ITERATION and
- updates the g_epoll_set.cursor
-
- 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 */
+ pollset->shutdown_closure = nullptr;
+ }
+}
+
+static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
+ GPR_TIMER_SCOPE("pollset_shutdown", 0);
+ GPR_ASSERT(pollset->shutdown_closure == nullptr);
+ GPR_ASSERT(!pollset->shutting_down);
+ pollset->shutdown_closure = closure;
+ pollset->shutting_down = true;
+ GRPC_LOG_IF_ERROR("pollset_shutdown", pollset_kick_all(pollset));
+ pollset_maybe_finish_shutdown(pollset);
+}
+
+static int poll_deadline_to_millis_timeout(grpc_millis millis) {
+ if (millis == GRPC_MILLIS_INF_FUTURE) return -1;
+ grpc_millis delta = millis - grpc_core::ExecCtx::Get()->Now();
+ if (delta > INT_MAX) {
+ return INT_MAX;
+ } else if (delta < 0) {
+ return 0;
+ } else {
+ return static_cast<int>(delta);
+ }
+}
+
+/* Process the epoll events found by do_epoll_wait() function.
+ - g_epoll_set.cursor points to the index of the first event to be processed
+ - This function then processes up-to MAX_EPOLL_EVENTS_PER_ITERATION and
+ updates the g_epoll_set.cursor
+
+ 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*/) {
- GPR_TIMER_SCOPE("process_epoll_events", 0);
-
- static const char* err_desc = "process_events";
- grpc_error* error = GRPC_ERROR_NONE;
- long num_events = gpr_atm_acq_load(&g_epoll_set.num_events);
- long cursor = gpr_atm_acq_load(&g_epoll_set.cursor);
- for (int idx = 0;
- (idx < MAX_EPOLL_EVENTS_HANDLED_PER_ITERATION) && cursor != num_events;
- idx++) {
- long c = cursor++;
- struct epoll_event* ev = &g_epoll_set.events[c];
- void* data_ptr = ev->data.ptr;
-
- if (data_ptr == &global_wakeup_fd) {
- append_error(&error, grpc_wakeup_fd_consume_wakeup(&global_wakeup_fd),
- err_desc);
- } else {
+ GPR_TIMER_SCOPE("process_epoll_events", 0);
+
+ static const char* err_desc = "process_events";
+ grpc_error* error = GRPC_ERROR_NONE;
+ long num_events = gpr_atm_acq_load(&g_epoll_set.num_events);
+ long cursor = gpr_atm_acq_load(&g_epoll_set.cursor);
+ for (int idx = 0;
+ (idx < MAX_EPOLL_EVENTS_HANDLED_PER_ITERATION) && cursor != num_events;
+ idx++) {
+ long c = cursor++;
+ struct epoll_event* ev = &g_epoll_set.events[c];
+ void* data_ptr = ev->data.ptr;
+
+ if (data_ptr == &global_wakeup_fd) {
+ append_error(&error, grpc_wakeup_fd_consume_wakeup(&global_wakeup_fd),
+ err_desc);
+ } else {
grpc_fd* fd = reinterpret_cast<grpc_fd*>(
reinterpret_cast<intptr_t>(data_ptr) & ~static_cast<intptr_t>(1));
bool track_err =
reinterpret_cast<intptr_t>(data_ptr) & static_cast<intptr_t>(1);
bool cancel = (ev->events & EPOLLHUP) != 0;
bool error = (ev->events & EPOLLERR) != 0;
- bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0;
- bool write_ev = (ev->events & EPOLLOUT) != 0;
+ bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0;
+ bool write_ev = (ev->events & EPOLLOUT) != 0;
bool err_fallback = error && !track_err;
-
+
if (error && !err_fallback) {
fd_has_errors(fd);
- }
-
+ }
+
if (read_ev || cancel || err_fallback) {
fd_become_readable(fd);
}
if (write_ev || cancel || err_fallback) {
- fd_become_writable(fd);
- }
- }
- }
- gpr_atm_rel_store(&g_epoll_set.cursor, cursor);
- return error;
-}
-
-/* Do epoll_wait and store the events in g_epoll_set.events field. This does not
- "process" any of the events yet; that is done in process_epoll_events().
- *See process_epoll_events() function for more details.
-
- NOTE ON SYNCHRONIZATION: At any point of time, only the g_active_poller
- (i.e the designated poller thread) will be calling this function. So there is
- no need for any synchronization when accesing fields in g_epoll_set */
-static grpc_error* do_epoll_wait(grpc_pollset* ps, grpc_millis deadline) {
- GPR_TIMER_SCOPE("do_epoll_wait", 0);
-
- int r;
- int timeout = poll_deadline_to_millis_timeout(deadline);
- if (timeout != 0) {
- GRPC_SCHEDULING_START_BLOCKING_REGION;
- }
- do {
- GRPC_STATS_INC_SYSCALL_POLL();
- r = epoll_wait(g_epoll_set.epfd, g_epoll_set.events, MAX_EPOLL_EVENTS,
- timeout);
- } while (r < 0 && errno == EINTR);
- if (timeout != 0) {
- GRPC_SCHEDULING_END_BLOCKING_REGION;
- }
-
- if (r < 0) return GRPC_OS_ERROR(errno, "epoll_wait");
-
- GRPC_STATS_INC_POLL_EVENTS_RETURNED(r);
-
+ fd_become_writable(fd);
+ }
+ }
+ }
+ gpr_atm_rel_store(&g_epoll_set.cursor, cursor);
+ return error;
+}
+
+/* Do epoll_wait and store the events in g_epoll_set.events field. This does not
+ "process" any of the events yet; that is done in process_epoll_events().
+ *See process_epoll_events() function for more details.
+
+ NOTE ON SYNCHRONIZATION: At any point of time, only the g_active_poller
+ (i.e the designated poller thread) will be calling this function. So there is
+ no need for any synchronization when accesing fields in g_epoll_set */
+static grpc_error* do_epoll_wait(grpc_pollset* ps, grpc_millis deadline) {
+ GPR_TIMER_SCOPE("do_epoll_wait", 0);
+
+ int r;
+ int timeout = poll_deadline_to_millis_timeout(deadline);
+ if (timeout != 0) {
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
+ }
+ do {
+ GRPC_STATS_INC_SYSCALL_POLL();
+ r = epoll_wait(g_epoll_set.epfd, g_epoll_set.events, MAX_EPOLL_EVENTS,
+ timeout);
+ } while (r < 0 && errno == EINTR);
+ if (timeout != 0) {
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+ }
+
+ if (r < 0) return GRPC_OS_ERROR(errno, "epoll_wait");
+
+ GRPC_STATS_INC_POLL_EVENTS_RETURNED(r);
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "ps: %p poll got %d events", ps, r);
- }
-
- gpr_atm_rel_store(&g_epoll_set.num_events, r);
- gpr_atm_rel_store(&g_epoll_set.cursor, 0);
-
- return GRPC_ERROR_NONE;
-}
-
-static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
- grpc_pollset_worker** worker_hdl,
- grpc_millis deadline) {
- GPR_TIMER_SCOPE("begin_worker", 0);
- if (worker_hdl != nullptr) *worker_hdl = worker;
- worker->initialized_cv = false;
- SET_KICK_STATE(worker, UNKICKED);
- worker->schedule_on_end_work = (grpc_closure_list)GRPC_CLOSURE_LIST_INIT;
- pollset->begin_refs++;
-
+ gpr_log(GPR_INFO, "ps: %p poll got %d events", ps, r);
+ }
+
+ gpr_atm_rel_store(&g_epoll_set.num_events, r);
+ gpr_atm_rel_store(&g_epoll_set.cursor, 0);
+
+ return GRPC_ERROR_NONE;
+}
+
+static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
+ grpc_pollset_worker** worker_hdl,
+ grpc_millis deadline) {
+ GPR_TIMER_SCOPE("begin_worker", 0);
+ if (worker_hdl != nullptr) *worker_hdl = worker;
+ worker->initialized_cv = false;
+ SET_KICK_STATE(worker, UNKICKED);
+ worker->schedule_on_end_work = (grpc_closure_list)GRPC_CLOSURE_LIST_INIT;
+ pollset->begin_refs++;
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "PS:%p BEGIN_STARTS:%p", pollset, worker);
- }
-
- if (pollset->seen_inactive) {
- // pollset has been observed to be inactive, we need to move back to the
- // active list
- bool is_reassigning = false;
- if (!pollset->reassigning_neighborhood) {
- is_reassigning = true;
- pollset->reassigning_neighborhood = true;
- pollset->neighborhood = &g_neighborhoods[choose_neighborhood()];
- }
- pollset_neighborhood* neighborhood = pollset->neighborhood;
- gpr_mu_unlock(&pollset->mu);
- // pollset unlocked: state may change (even worker->kick_state)
- retry_lock_neighborhood:
- gpr_mu_lock(&neighborhood->mu);
- gpr_mu_lock(&pollset->mu);
+ gpr_log(GPR_INFO, "PS:%p BEGIN_STARTS:%p", pollset, worker);
+ }
+
+ if (pollset->seen_inactive) {
+ // pollset has been observed to be inactive, we need to move back to the
+ // active list
+ bool is_reassigning = false;
+ if (!pollset->reassigning_neighborhood) {
+ is_reassigning = true;
+ pollset->reassigning_neighborhood = true;
+ pollset->neighborhood = &g_neighborhoods[choose_neighborhood()];
+ }
+ pollset_neighborhood* neighborhood = pollset->neighborhood;
+ gpr_mu_unlock(&pollset->mu);
+ // pollset unlocked: state may change (even worker->kick_state)
+ retry_lock_neighborhood:
+ gpr_mu_lock(&neighborhood->mu);
+ gpr_mu_lock(&pollset->mu);
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);
- }
- if (pollset->seen_inactive) {
- if (neighborhood != pollset->neighborhood) {
- gpr_mu_unlock(&neighborhood->mu);
- neighborhood = pollset->neighborhood;
- gpr_mu_unlock(&pollset->mu);
- goto retry_lock_neighborhood;
- }
-
- /* In the brief time we released the pollset locks above, the worker MAY
- have been kicked. In this case, the worker should get out of this
- pollset ASAP and hence this should neither add the pollset to
- neighborhood nor mark the pollset as active.
-
- On a side note, the only way a worker's kick state could have changed
- at this point is if it were "kicked specifically". Since the worker has
- not added itself to the pollset yet (by calling worker_insert()), it is
- not visible in the "kick any" path yet */
- if (worker->state == UNKICKED) {
- pollset->seen_inactive = false;
- if (neighborhood->active_root == nullptr) {
- neighborhood->active_root = pollset->next = pollset->prev = pollset;
- /* Make this the designated poller if there isn't one already */
- if (worker->state == UNKICKED &&
- gpr_atm_no_barrier_cas(&g_active_poller, 0, (gpr_atm)worker)) {
- SET_KICK_STATE(worker, DESIGNATED_POLLER);
- }
- } else {
- pollset->next = neighborhood->active_root;
- pollset->prev = pollset->next->prev;
- pollset->next->prev = pollset->prev->next = pollset;
- }
- }
- }
- if (is_reassigning) {
- GPR_ASSERT(pollset->reassigning_neighborhood);
- pollset->reassigning_neighborhood = false;
- }
- gpr_mu_unlock(&neighborhood->mu);
- }
-
- worker_insert(pollset, worker);
- pollset->begin_refs--;
- if (worker->state == UNKICKED && !pollset->kicked_without_poller) {
- GPR_ASSERT(gpr_atm_no_barrier_load(&g_active_poller) != (gpr_atm)worker);
- worker->initialized_cv = true;
- gpr_cv_init(&worker->cv);
- while (worker->state == UNKICKED && !pollset->shutting_down) {
+ gpr_log(GPR_INFO, "PS:%p BEGIN_REORG:%p kick_state=%s is_reassigning=%d",
+ pollset, worker, kick_state_string(worker->state),
+ is_reassigning);
+ }
+ if (pollset->seen_inactive) {
+ if (neighborhood != pollset->neighborhood) {
+ gpr_mu_unlock(&neighborhood->mu);
+ neighborhood = pollset->neighborhood;
+ gpr_mu_unlock(&pollset->mu);
+ goto retry_lock_neighborhood;
+ }
+
+ /* In the brief time we released the pollset locks above, the worker MAY
+ have been kicked. In this case, the worker should get out of this
+ pollset ASAP and hence this should neither add the pollset to
+ neighborhood nor mark the pollset as active.
+
+ On a side note, the only way a worker's kick state could have changed
+ at this point is if it were "kicked specifically". Since the worker has
+ not added itself to the pollset yet (by calling worker_insert()), it is
+ not visible in the "kick any" path yet */
+ if (worker->state == UNKICKED) {
+ pollset->seen_inactive = false;
+ if (neighborhood->active_root == nullptr) {
+ neighborhood->active_root = pollset->next = pollset->prev = pollset;
+ /* Make this the designated poller if there isn't one already */
+ if (worker->state == UNKICKED &&
+ gpr_atm_no_barrier_cas(&g_active_poller, 0, (gpr_atm)worker)) {
+ SET_KICK_STATE(worker, DESIGNATED_POLLER);
+ }
+ } else {
+ pollset->next = neighborhood->active_root;
+ pollset->prev = pollset->next->prev;
+ pollset->next->prev = pollset->prev->next = pollset;
+ }
+ }
+ }
+ if (is_reassigning) {
+ GPR_ASSERT(pollset->reassigning_neighborhood);
+ pollset->reassigning_neighborhood = false;
+ }
+ gpr_mu_unlock(&neighborhood->mu);
+ }
+
+ worker_insert(pollset, worker);
+ pollset->begin_refs--;
+ if (worker->state == UNKICKED && !pollset->kicked_without_poller) {
+ GPR_ASSERT(gpr_atm_no_barrier_load(&g_active_poller) != (gpr_atm)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)) {
- gpr_log(GPR_INFO, "PS:%p BEGIN_WAIT:%p kick_state=%s shutdown=%d",
- pollset, worker, kick_state_string(worker->state),
- pollset->shutting_down);
- }
-
- if (gpr_cv_wait(&worker->cv, &pollset->mu,
- grpc_millis_to_timespec(deadline, GPR_CLOCK_MONOTONIC)) &&
- worker->state == UNKICKED) {
- /* If gpr_cv_wait returns true (i.e a timeout), pretend that the worker
- received a kick */
- SET_KICK_STATE(worker, KICKED);
- }
- }
- grpc_core::ExecCtx::Get()->InvalidateNow();
- }
-
+ gpr_log(GPR_INFO, "PS:%p BEGIN_WAIT:%p kick_state=%s shutdown=%d",
+ pollset, worker, kick_state_string(worker->state),
+ pollset->shutting_down);
+ }
+
+ if (gpr_cv_wait(&worker->cv, &pollset->mu,
+ grpc_millis_to_timespec(deadline, GPR_CLOCK_MONOTONIC)) &&
+ worker->state == UNKICKED) {
+ /* If gpr_cv_wait returns true (i.e a timeout), pretend that the worker
+ received a kick */
+ SET_KICK_STATE(worker, KICKED);
+ }
+ }
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+ }
+
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",
- pollset, worker, kick_state_string(worker->state),
- pollset->shutting_down, pollset->kicked_without_poller);
- }
-
- /* We release pollset lock in this function at a couple of places:
- * 1. Briefly when assigning pollset to a neighborhood
- * 2. When doing gpr_cv_wait()
- * It is possible that 'kicked_without_poller' was set to true during (1) and
- * 'shutting_down' is set to true during (1) or (2). If either of them is
- * true, this worker cannot do polling */
- /* TODO(sreek): Perhaps there is a better way to handle kicked_without_poller
- * case; especially when the worker is the DESIGNATED_POLLER */
-
- if (pollset->kicked_without_poller) {
- pollset->kicked_without_poller = false;
- return false;
- }
-
- return worker->state == DESIGNATED_POLLER && !pollset->shutting_down;
-}
-
-static bool check_neighborhood_for_available_poller(
- pollset_neighborhood* neighborhood) {
- GPR_TIMER_SCOPE("check_neighborhood_for_available_poller", 0);
- bool found_worker = false;
- do {
- grpc_pollset* inspect = neighborhood->active_root;
- if (inspect == nullptr) {
- break;
- }
- gpr_mu_lock(&inspect->mu);
- GPR_ASSERT(!inspect->seen_inactive);
- grpc_pollset_worker* inspect_worker = inspect->root_worker;
- if (inspect_worker != nullptr) {
- do {
- switch (inspect_worker->state) {
- case UNKICKED:
- if (gpr_atm_no_barrier_cas(&g_active_poller, 0,
- (gpr_atm)inspect_worker)) {
+ gpr_log(GPR_INFO,
+ "PS:%p BEGIN_DONE:%p kick_state=%s shutdown=%d "
+ "kicked_without_poller: %d",
+ pollset, worker, kick_state_string(worker->state),
+ pollset->shutting_down, pollset->kicked_without_poller);
+ }
+
+ /* We release pollset lock in this function at a couple of places:
+ * 1. Briefly when assigning pollset to a neighborhood
+ * 2. When doing gpr_cv_wait()
+ * It is possible that 'kicked_without_poller' was set to true during (1) and
+ * 'shutting_down' is set to true during (1) or (2). If either of them is
+ * true, this worker cannot do polling */
+ /* TODO(sreek): Perhaps there is a better way to handle kicked_without_poller
+ * case; especially when the worker is the DESIGNATED_POLLER */
+
+ if (pollset->kicked_without_poller) {
+ pollset->kicked_without_poller = false;
+ return false;
+ }
+
+ return worker->state == DESIGNATED_POLLER && !pollset->shutting_down;
+}
+
+static bool check_neighborhood_for_available_poller(
+ pollset_neighborhood* neighborhood) {
+ GPR_TIMER_SCOPE("check_neighborhood_for_available_poller", 0);
+ bool found_worker = false;
+ do {
+ grpc_pollset* inspect = neighborhood->active_root;
+ if (inspect == nullptr) {
+ break;
+ }
+ gpr_mu_lock(&inspect->mu);
+ GPR_ASSERT(!inspect->seen_inactive);
+ grpc_pollset_worker* inspect_worker = inspect->root_worker;
+ if (inspect_worker != nullptr) {
+ do {
+ switch (inspect_worker->state) {
+ case UNKICKED:
+ if (gpr_atm_no_barrier_cas(&g_active_poller, 0,
+ (gpr_atm)inspect_worker)) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. choose next poller to be %p",
- inspect_worker);
- }
- SET_KICK_STATE(inspect_worker, DESIGNATED_POLLER);
- if (inspect_worker->initialized_cv) {
- GPR_TIMER_MARK("signal worker", 0);
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
- gpr_cv_signal(&inspect_worker->cv);
- }
- } else {
+ gpr_log(GPR_INFO, " .. choose next poller to be %p",
+ inspect_worker);
+ }
+ SET_KICK_STATE(inspect_worker, DESIGNATED_POLLER);
+ if (inspect_worker->initialized_cv) {
+ GPR_TIMER_MARK("signal worker", 0);
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
+ gpr_cv_signal(&inspect_worker->cv);
+ }
+ } else {
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. beaten to choose next poller");
- }
- }
- // even if we didn't win the cas, there's a worker, we can stop
- found_worker = true;
- break;
- case KICKED:
- break;
- case DESIGNATED_POLLER:
- found_worker = true; // ok, so someone else found the worker, but
- // we'll accept that
- break;
- }
- inspect_worker = inspect_worker->next;
- } while (!found_worker && inspect_worker != inspect->root_worker);
- }
- if (!found_worker) {
+ gpr_log(GPR_INFO, " .. beaten to choose next poller");
+ }
+ }
+ // even if we didn't win the cas, there's a worker, we can stop
+ found_worker = true;
+ break;
+ case KICKED:
+ break;
+ case DESIGNATED_POLLER:
+ found_worker = true; // ok, so someone else found the worker, but
+ // we'll accept that
+ break;
+ }
+ inspect_worker = inspect_worker->next;
+ } while (!found_worker && inspect_worker != inspect->root_worker);
+ }
+ if (!found_worker) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. mark pollset %p inactive", inspect);
- }
- inspect->seen_inactive = true;
- if (inspect == neighborhood->active_root) {
- neighborhood->active_root =
- inspect->next == inspect ? nullptr : inspect->next;
- }
- inspect->next->prev = inspect->prev;
- inspect->prev->next = inspect->next;
- inspect->next = inspect->prev = nullptr;
- }
- gpr_mu_unlock(&inspect->mu);
- } while (!found_worker);
- return found_worker;
-}
-
-static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
- grpc_pollset_worker** worker_hdl) {
- GPR_TIMER_SCOPE("end_worker", 0);
+ gpr_log(GPR_INFO, " .. mark pollset %p inactive", inspect);
+ }
+ inspect->seen_inactive = true;
+ if (inspect == neighborhood->active_root) {
+ neighborhood->active_root =
+ inspect->next == inspect ? nullptr : inspect->next;
+ }
+ inspect->next->prev = inspect->prev;
+ inspect->prev->next = inspect->next;
+ inspect->next = inspect->prev = nullptr;
+ }
+ gpr_mu_unlock(&inspect->mu);
+ } while (!found_worker);
+ return found_worker;
+}
+
+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)) {
- gpr_log(GPR_INFO, "PS:%p END_WORKER:%p", pollset, worker);
- }
- if (worker_hdl != nullptr) *worker_hdl = nullptr;
- /* Make sure we appear kicked */
- SET_KICK_STATE(worker, KICKED);
- grpc_closure_list_move(&worker->schedule_on_end_work,
- 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) {
+ gpr_log(GPR_INFO, "PS:%p END_WORKER:%p", pollset, worker);
+ }
+ if (worker_hdl != nullptr) *worker_hdl = nullptr;
+ /* Make sure we appear kicked */
+ SET_KICK_STATE(worker, KICKED);
+ grpc_closure_list_move(&worker->schedule_on_end_work,
+ 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)) {
- gpr_log(GPR_INFO, " .. choose next poller to be peer %p", worker);
- }
- GPR_ASSERT(worker->next->initialized_cv);
- gpr_atm_no_barrier_store(&g_active_poller, (gpr_atm)worker->next);
- SET_KICK_STATE(worker->next, DESIGNATED_POLLER);
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
- gpr_cv_signal(&worker->next->cv);
- if (grpc_core::ExecCtx::Get()->HasWork()) {
- gpr_mu_unlock(&pollset->mu);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(&pollset->mu);
- }
- } else {
- gpr_atm_no_barrier_store(&g_active_poller, 0);
- size_t poller_neighborhood_idx =
- static_cast<size_t>(pollset->neighborhood - g_neighborhoods);
- gpr_mu_unlock(&pollset->mu);
- bool found_worker = false;
- bool scan_state[MAX_NEIGHBORHOODS];
- for (size_t i = 0; !found_worker && i < g_num_neighborhoods; i++) {
- pollset_neighborhood* neighborhood =
- &g_neighborhoods[(poller_neighborhood_idx + i) %
- g_num_neighborhoods];
- if (gpr_mu_trylock(&neighborhood->mu)) {
- found_worker = check_neighborhood_for_available_poller(neighborhood);
- gpr_mu_unlock(&neighborhood->mu);
- scan_state[i] = true;
- } else {
- scan_state[i] = false;
- }
- }
- for (size_t i = 0; !found_worker && i < g_num_neighborhoods; i++) {
- if (scan_state[i]) continue;
- pollset_neighborhood* neighborhood =
- &g_neighborhoods[(poller_neighborhood_idx + i) %
- g_num_neighborhoods];
- gpr_mu_lock(&neighborhood->mu);
- found_worker = check_neighborhood_for_available_poller(neighborhood);
- gpr_mu_unlock(&neighborhood->mu);
- }
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(&pollset->mu);
- }
- } else if (grpc_core::ExecCtx::Get()->HasWork()) {
- gpr_mu_unlock(&pollset->mu);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(&pollset->mu);
- }
- if (worker->initialized_cv) {
- gpr_cv_destroy(&worker->cv);
- }
+ gpr_log(GPR_INFO, " .. choose next poller to be peer %p", worker);
+ }
+ GPR_ASSERT(worker->next->initialized_cv);
+ gpr_atm_no_barrier_store(&g_active_poller, (gpr_atm)worker->next);
+ SET_KICK_STATE(worker->next, DESIGNATED_POLLER);
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
+ gpr_cv_signal(&worker->next->cv);
+ if (grpc_core::ExecCtx::Get()->HasWork()) {
+ gpr_mu_unlock(&pollset->mu);
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(&pollset->mu);
+ }
+ } else {
+ gpr_atm_no_barrier_store(&g_active_poller, 0);
+ size_t poller_neighborhood_idx =
+ static_cast<size_t>(pollset->neighborhood - g_neighborhoods);
+ gpr_mu_unlock(&pollset->mu);
+ bool found_worker = false;
+ bool scan_state[MAX_NEIGHBORHOODS];
+ for (size_t i = 0; !found_worker && i < g_num_neighborhoods; i++) {
+ pollset_neighborhood* neighborhood =
+ &g_neighborhoods[(poller_neighborhood_idx + i) %
+ g_num_neighborhoods];
+ if (gpr_mu_trylock(&neighborhood->mu)) {
+ found_worker = check_neighborhood_for_available_poller(neighborhood);
+ gpr_mu_unlock(&neighborhood->mu);
+ scan_state[i] = true;
+ } else {
+ scan_state[i] = false;
+ }
+ }
+ for (size_t i = 0; !found_worker && i < g_num_neighborhoods; i++) {
+ if (scan_state[i]) continue;
+ pollset_neighborhood* neighborhood =
+ &g_neighborhoods[(poller_neighborhood_idx + i) %
+ g_num_neighborhoods];
+ gpr_mu_lock(&neighborhood->mu);
+ found_worker = check_neighborhood_for_available_poller(neighborhood);
+ gpr_mu_unlock(&neighborhood->mu);
+ }
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(&pollset->mu);
+ }
+ } else if (grpc_core::ExecCtx::Get()->HasWork()) {
+ gpr_mu_unlock(&pollset->mu);
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(&pollset->mu);
+ }
+ if (worker->initialized_cv) {
+ gpr_cv_destroy(&worker->cv);
+ }
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. remove worker");
- }
- if (EMPTIED == worker_remove(pollset, worker)) {
- pollset_maybe_finish_shutdown(pollset);
- }
- GPR_ASSERT(gpr_atm_no_barrier_load(&g_active_poller) != (gpr_atm)worker);
-}
-
-/* pollset->po.mu lock must be held by the caller before calling this.
- The function pollset_work() may temporarily release the lock (pollset->po.mu)
- during the course of its execution but it will always re-acquire the lock and
- ensure that it is held by the time the function returns */
-static grpc_error* pollset_work(grpc_pollset* ps,
- grpc_pollset_worker** worker_hdl,
- grpc_millis deadline) {
- GPR_TIMER_SCOPE("pollset_work", 0);
- grpc_pollset_worker worker;
- grpc_error* error = GRPC_ERROR_NONE;
- static const char* err_desc = "pollset_work";
- if (ps->kicked_without_poller) {
- ps->kicked_without_poller = false;
- return GRPC_ERROR_NONE;
- }
-
- if (begin_worker(ps, &worker, worker_hdl, deadline)) {
- gpr_tls_set(&g_current_thread_pollset, (intptr_t)ps);
- gpr_tls_set(&g_current_thread_worker, (intptr_t)&worker);
- GPR_ASSERT(!ps->shutting_down);
- GPR_ASSERT(!ps->seen_inactive);
-
- gpr_mu_unlock(&ps->mu); /* unlock */
- /* This is the designated polling thread at this point and should ideally do
- polling. However, if there are unprocessed events left from a previous
- call to do_epoll_wait(), skip calling epoll_wait() in this iteration and
- process the pending epoll events.
-
- The reason for decoupling do_epoll_wait and process_epoll_events is to
+ gpr_log(GPR_INFO, " .. remove worker");
+ }
+ if (EMPTIED == worker_remove(pollset, worker)) {
+ pollset_maybe_finish_shutdown(pollset);
+ }
+ GPR_ASSERT(gpr_atm_no_barrier_load(&g_active_poller) != (gpr_atm)worker);
+}
+
+/* pollset->po.mu lock must be held by the caller before calling this.
+ The function pollset_work() may temporarily release the lock (pollset->po.mu)
+ during the course of its execution but it will always re-acquire the lock and
+ ensure that it is held by the time the function returns */
+static grpc_error* pollset_work(grpc_pollset* ps,
+ grpc_pollset_worker** worker_hdl,
+ grpc_millis deadline) {
+ GPR_TIMER_SCOPE("pollset_work", 0);
+ grpc_pollset_worker worker;
+ grpc_error* error = GRPC_ERROR_NONE;
+ static const char* err_desc = "pollset_work";
+ if (ps->kicked_without_poller) {
+ ps->kicked_without_poller = false;
+ return GRPC_ERROR_NONE;
+ }
+
+ if (begin_worker(ps, &worker, worker_hdl, deadline)) {
+ gpr_tls_set(&g_current_thread_pollset, (intptr_t)ps);
+ gpr_tls_set(&g_current_thread_worker, (intptr_t)&worker);
+ GPR_ASSERT(!ps->shutting_down);
+ GPR_ASSERT(!ps->seen_inactive);
+
+ gpr_mu_unlock(&ps->mu); /* unlock */
+ /* This is the designated polling thread at this point and should ideally do
+ polling. However, if there are unprocessed events left from a previous
+ call to do_epoll_wait(), skip calling epoll_wait() in this iteration and
+ 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
- threads
-
- process_epoll_events() returns very quickly: It just queues the work on
- exec_ctx but does not execute it (the actual exectution or more
- accurately grpc_core::ExecCtx::Get()->Flush() happens in end_worker()
- AFTER selecting a designated poller). So we are not waiting long periods
- without a designated poller */
- if (gpr_atm_acq_load(&g_epoll_set.cursor) ==
- gpr_atm_acq_load(&g_epoll_set.num_events)) {
- append_error(&error, do_epoll_wait(ps, deadline), err_desc);
- }
- append_error(&error, process_epoll_events(ps), err_desc);
-
- gpr_mu_lock(&ps->mu); /* lock */
-
- gpr_tls_set(&g_current_thread_worker, 0);
- } else {
- gpr_tls_set(&g_current_thread_pollset, (intptr_t)ps);
- }
- end_worker(ps, &worker, worker_hdl);
-
- gpr_tls_set(&g_current_thread_pollset, 0);
- return error;
-}
-
-static grpc_error* pollset_kick(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker) {
- GPR_TIMER_SCOPE("pollset_kick", 0);
- GRPC_STATS_INC_POLLSET_KICK();
- grpc_error* ret_err = GRPC_ERROR_NONE;
+ threads
+
+ process_epoll_events() returns very quickly: It just queues the work on
+ exec_ctx but does not execute it (the actual exectution or more
+ accurately grpc_core::ExecCtx::Get()->Flush() happens in end_worker()
+ AFTER selecting a designated poller). So we are not waiting long periods
+ without a designated poller */
+ if (gpr_atm_acq_load(&g_epoll_set.cursor) ==
+ gpr_atm_acq_load(&g_epoll_set.num_events)) {
+ append_error(&error, do_epoll_wait(ps, deadline), err_desc);
+ }
+ append_error(&error, process_epoll_events(ps), err_desc);
+
+ gpr_mu_lock(&ps->mu); /* lock */
+
+ gpr_tls_set(&g_current_thread_worker, 0);
+ } else {
+ gpr_tls_set(&g_current_thread_pollset, (intptr_t)ps);
+ }
+ end_worker(ps, &worker, worker_hdl);
+
+ gpr_tls_set(&g_current_thread_pollset, 0);
+ return error;
+}
+
+static grpc_error* pollset_kick(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker) {
+ 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)) {
std::vector<TString> log;
log.push_back(y_absl::StrFormat(
"PS:%p KICK:%p curps=%p curworker=%p root=%p", pollset, specific_worker,
(void*)gpr_tls_get(&g_current_thread_pollset),
(void*)gpr_tls_get(&g_current_thread_worker), pollset->root_worker));
- if (pollset->root_worker != nullptr) {
+ if (pollset->root_worker != nullptr) {
log.push_back(y_absl::StrFormat(
" {kick_state=%s next=%p {kick_state=%s}}",
kick_state_string(pollset->root_worker->state),
pollset->root_worker->next,
kick_state_string(pollset->root_worker->next->state)));
- }
- if (specific_worker != nullptr) {
+ }
+ if (specific_worker != nullptr) {
log.push_back(y_absl::StrFormat(" worker_kick_state=%s",
kick_state_string(specific_worker->state)));
- }
+ }
gpr_log(GPR_DEBUG, "%s", y_absl::StrJoin(log, "").c_str());
- }
-
- if (specific_worker == nullptr) {
- if (gpr_tls_get(&g_current_thread_pollset) != (intptr_t)pollset) {
- grpc_pollset_worker* root_worker = pollset->root_worker;
- if (root_worker == nullptr) {
- GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER();
- pollset->kicked_without_poller = true;
+ }
+
+ if (specific_worker == nullptr) {
+ if (gpr_tls_get(&g_current_thread_pollset) != (intptr_t)pollset) {
+ grpc_pollset_worker* root_worker = pollset->root_worker;
+ if (root_worker == nullptr) {
+ GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER();
+ pollset->kicked_without_poller = true;
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. kicked_without_poller");
- }
- goto done;
- }
- grpc_pollset_worker* next_worker = root_worker->next;
- if (root_worker->state == KICKED) {
- GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
+ gpr_log(GPR_INFO, " .. kicked_without_poller");
+ }
+ goto done;
+ }
+ 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)) {
- 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();
+ 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)) {
- gpr_log(GPR_INFO, " .. already kicked %p", next_worker);
- }
- SET_KICK_STATE(next_worker, KICKED);
- goto done;
+ gpr_log(GPR_INFO, " .. already kicked %p", next_worker);
+ }
+ SET_KICK_STATE(next_worker, KICKED);
+ goto done;
} else if (root_worker == next_worker && // only try and wake up a poller
// if there is no next worker
- root_worker == (grpc_pollset_worker*)gpr_atm_no_barrier_load(
- &g_active_poller)) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
+ 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)) {
- gpr_log(GPR_INFO, " .. kicked %p", root_worker);
- }
- SET_KICK_STATE(root_worker, KICKED);
- ret_err = grpc_wakeup_fd_wakeup(&global_wakeup_fd);
- goto done;
- } else if (next_worker->state == UNKICKED) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
+ gpr_log(GPR_INFO, " .. kicked %p", root_worker);
+ }
+ SET_KICK_STATE(root_worker, KICKED);
+ ret_err = grpc_wakeup_fd_wakeup(&global_wakeup_fd);
+ goto done;
+ } else if (next_worker->state == UNKICKED) {
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. kicked %p", next_worker);
- }
- GPR_ASSERT(next_worker->initialized_cv);
- SET_KICK_STATE(next_worker, KICKED);
- gpr_cv_signal(&next_worker->cv);
- goto done;
- } else if (next_worker->state == DESIGNATED_POLLER) {
- if (root_worker->state != DESIGNATED_POLLER) {
+ gpr_log(GPR_INFO, " .. kicked %p", next_worker);
+ }
+ GPR_ASSERT(next_worker->initialized_cv);
+ SET_KICK_STATE(next_worker, KICKED);
+ gpr_cv_signal(&next_worker->cv);
+ goto done;
+ } else if (next_worker->state == DESIGNATED_POLLER) {
+ if (root_worker->state != DESIGNATED_POLLER) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(
- GPR_INFO,
- " .. kicked root non-poller %p (initialized_cv=%d) (poller=%p)",
- root_worker, root_worker->initialized_cv, next_worker);
- }
- SET_KICK_STATE(root_worker, KICKED);
- if (root_worker->initialized_cv) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
- gpr_cv_signal(&root_worker->cv);
- }
- goto done;
- } else {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
+ gpr_log(
+ GPR_INFO,
+ " .. kicked root non-poller %p (initialized_cv=%d) (poller=%p)",
+ root_worker, root_worker->initialized_cv, next_worker);
+ }
+ SET_KICK_STATE(root_worker, KICKED);
+ if (root_worker->initialized_cv) {
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
+ gpr_cv_signal(&root_worker->cv);
+ }
+ goto done;
+ } else {
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. non-root poller %p (root=%p)", next_worker,
- root_worker);
- }
- SET_KICK_STATE(next_worker, KICKED);
- ret_err = grpc_wakeup_fd_wakeup(&global_wakeup_fd);
- goto done;
- }
- } else {
- GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
- GPR_ASSERT(next_worker->state == KICKED);
- SET_KICK_STATE(next_worker, KICKED);
- goto done;
- }
- } else {
- GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
+ gpr_log(GPR_INFO, " .. non-root poller %p (root=%p)", next_worker,
+ root_worker);
+ }
+ SET_KICK_STATE(next_worker, KICKED);
+ ret_err = grpc_wakeup_fd_wakeup(&global_wakeup_fd);
+ goto done;
+ }
+ } else {
+ GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
+ GPR_ASSERT(next_worker->state == KICKED);
+ SET_KICK_STATE(next_worker, KICKED);
+ goto done;
+ }
+ } else {
+ GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. kicked while waking up");
- }
- goto done;
- }
-
- GPR_UNREACHABLE_CODE(goto done);
- }
-
- if (specific_worker->state == KICKED) {
+ gpr_log(GPR_INFO, " .. kicked while waking up");
+ }
+ goto done;
+ }
+
+ GPR_UNREACHABLE_CODE(goto done);
+ }
+
+ if (specific_worker->state == KICKED) {
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();
+ 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)) {
- gpr_log(GPR_INFO, " .. mark %p kicked", specific_worker);
- }
- SET_KICK_STATE(specific_worker, KICKED);
- goto done;
- } else if (specific_worker ==
- (grpc_pollset_worker*)gpr_atm_no_barrier_load(&g_active_poller)) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
+ gpr_log(GPR_INFO, " .. mark %p kicked", specific_worker);
+ }
+ SET_KICK_STATE(specific_worker, KICKED);
+ goto done;
+ } 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)) {
- gpr_log(GPR_INFO, " .. kick active poller");
- }
- SET_KICK_STATE(specific_worker, KICKED);
- ret_err = grpc_wakeup_fd_wakeup(&global_wakeup_fd);
- goto done;
- } else if (specific_worker->initialized_cv) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
+ gpr_log(GPR_INFO, " .. kick active poller");
+ }
+ SET_KICK_STATE(specific_worker, KICKED);
+ ret_err = grpc_wakeup_fd_wakeup(&global_wakeup_fd);
+ goto done;
+ } else if (specific_worker->initialized_cv) {
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. kick waiting worker");
- }
- SET_KICK_STATE(specific_worker, KICKED);
- gpr_cv_signal(&specific_worker->cv);
- goto done;
- } else {
- GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
+ gpr_log(GPR_INFO, " .. kick waiting worker");
+ }
+ SET_KICK_STATE(specific_worker, KICKED);
+ gpr_cv_signal(&specific_worker->cv);
+ goto done;
+ } else {
+ GRPC_STATS_INC_POLLSET_KICKED_AGAIN();
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, " .. kick non-waiting worker");
- }
- SET_KICK_STATE(specific_worker, KICKED);
- goto done;
- }
-done:
- return ret_err;
-}
-
+ gpr_log(GPR_INFO, " .. kick non-waiting worker");
+ }
+ SET_KICK_STATE(specific_worker, KICKED);
+ goto done;
+ }
+done:
+ return ret_err;
+}
+
static void pollset_add_fd(grpc_pollset* /*pollset*/, grpc_fd* /*fd*/) {}
-
-/*******************************************************************************
- * Pollset-set Definitions
- */
-
-static grpc_pollset_set* pollset_set_create(void) {
- return (grpc_pollset_set*)(static_cast<intptr_t>(0xdeafbeef));
-}
-
+
+/*******************************************************************************
+ * Pollset-set Definitions
+ */
+
+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_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_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_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*/) {}
-
-/*******************************************************************************
- * Event engine binding
- */
-
+
+/*******************************************************************************
+ * Event engine binding
+ */
+
static bool is_any_background_poller_thread(void) { return false; }
static void shutdown_background_closure(void) {}
@@ -1257,55 +1257,55 @@ static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
return false;
}
-static void shutdown_engine(void) {
- fd_global_shutdown();
- pollset_global_shutdown();
- epoll_set_shutdown();
+static void shutdown_engine(void) {
+ fd_global_shutdown();
+ pollset_global_shutdown();
+ epoll_set_shutdown();
if (grpc_core::Fork::Enabled()) {
gpr_mu_destroy(&fork_fd_list_mu);
grpc_core::Fork::SetResetChildPollingEngineFunc(nullptr);
}
-}
-
-static const grpc_event_engine_vtable vtable = {
- sizeof(grpc_pollset),
+}
+
+static const grpc_event_engine_vtable vtable = {
+ sizeof(grpc_pollset),
true,
false,
-
- fd_create,
- fd_wrapped_fd,
- fd_orphan,
- fd_shutdown,
- fd_notify_on_read,
- fd_notify_on_write,
+
+ fd_create,
+ fd_wrapped_fd,
+ fd_orphan,
+ fd_shutdown,
+ fd_notify_on_read,
+ fd_notify_on_write,
fd_notify_on_error,
fd_become_readable,
fd_become_writable,
fd_has_errors,
- fd_is_shutdown,
-
- pollset_init,
- pollset_shutdown,
- pollset_destroy,
- pollset_work,
- pollset_kick,
- pollset_add_fd,
-
- pollset_set_create,
- pollset_set_destroy,
- pollset_set_add_pollset,
- pollset_set_del_pollset,
- pollset_set_add_pollset_set,
- pollset_set_del_pollset_set,
- pollset_set_add_fd,
- pollset_set_del_fd,
-
+ fd_is_shutdown,
+
+ pollset_init,
+ pollset_shutdown,
+ pollset_destroy,
+ pollset_work,
+ pollset_kick,
+ pollset_add_fd,
+
+ pollset_set_create,
+ pollset_set_destroy,
+ pollset_set_add_pollset,
+ pollset_set_del_pollset,
+ pollset_set_add_pollset_set,
+ pollset_set_del_pollset_set,
+ pollset_set_add_fd,
+ pollset_set_del_fd,
+
is_any_background_poller_thread,
shutdown_background_closure,
- shutdown_engine,
+ shutdown_engine,
add_closure_to_background_poller,
-};
-
+};
+
/* Called by the child process's post-fork handler to close open fds, including
* the global epoll fd. This allows gRPC to shutdown in the child process
* without interfering with connections or RPCs ongoing in the parent. */
@@ -1321,44 +1321,44 @@ static void reset_event_manager_on_fork() {
grpc_init_epoll1_linux(true);
}
-/* 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 */
+/* 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*/) {
- if (!grpc_has_wakeup_fd()) {
- gpr_log(GPR_ERROR, "Skipping epoll1 because of no wakeup fd.");
- return nullptr;
- }
-
- if (!epoll_set_init()) {
- return nullptr;
- }
-
- fd_global_init();
-
- if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
- fd_global_shutdown();
- epoll_set_shutdown();
- return nullptr;
- }
-
+ if (!grpc_has_wakeup_fd()) {
+ gpr_log(GPR_ERROR, "Skipping epoll1 because of no wakeup fd.");
+ return nullptr;
+ }
+
+ if (!epoll_set_init()) {
+ return nullptr;
+ }
+
+ fd_global_init();
+
+ if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
+ fd_global_shutdown();
+ epoll_set_shutdown();
+ return nullptr;
+ }
+
if (grpc_core::Fork::Enabled()) {
gpr_mu_init(&fork_fd_list_mu);
grpc_core::Fork::SetResetChildPollingEngineFunc(
reset_event_manager_on_fork);
}
- return &vtable;
-}
-
-#else /* defined(GRPC_LINUX_EPOLL) */
+ return &vtable;
+}
+
+#else /* defined(GRPC_LINUX_EPOLL) */
#if defined(GRPC_POSIX_SOCKET_EV_EPOLL1)
-#include "src/core/lib/iomgr/ev_epoll1_linux.h"
-/* If GRPC_LINUX_EPOLL is not defined, it means epoll is not available. Return
- * NULL */
+#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*/) {
- return nullptr;
-}
+ return nullptr;
+}
#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLL1) */
-#endif /* !defined(GRPC_LINUX_EPOLL) */
+#endif /* !defined(GRPC_LINUX_EPOLL) */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.h b/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.h
index ca0db7250f0..c63d420c46e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.h
@@ -1,31 +1,31 @@
-/*
- *
- * 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_IOMGR_EV_EPOLL1_LINUX_H
-#define GRPC_CORE_LIB_IOMGR_EV_EPOLL1_LINUX_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/port.h"
-
-// a polling engine that utilizes a singleton epoll set and turnstile polling
-
-const grpc_event_engine_vtable* grpc_init_epoll1_linux(bool explicit_request);
-
-#endif /* GRPC_CORE_LIB_IOMGR_EV_EPOLL1_LINUX_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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_EV_EPOLL1_LINUX_H
+#define GRPC_CORE_LIB_IOMGR_EV_EPOLL1_LINUX_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/port.h"
+
+// a polling engine that utilizes a singleton epoll set and turnstile polling
+
+const grpc_event_engine_vtable* grpc_init_epoll1_linux(bool explicit_request);
+
+#endif /* GRPC_CORE_LIB_IOMGR_EV_EPOLL1_LINUX_H */
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 2dd9bbdffd8..77e5a0addd1 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
@@ -1,140 +1,140 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#include <grpc/support/log.h>
-
-/* This polling engine is only relevant on linux kernels supporting epoll() */
-#ifdef GRPC_LINUX_EPOLL_CREATE1
-
-#include "src/core/lib/iomgr/ev_epollex_linux.h"
-
-#include <assert.h>
-#include <errno.h>
-#include <limits.h>
-#include <poll.h>
-#include <pthread.h>
-#include <string.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#include <grpc/support/log.h>
+
+/* This polling engine is only relevant on linux kernels supporting epoll() */
+#ifdef GRPC_LINUX_EPOLL_CREATE1
+
+#include "src/core/lib/iomgr/ev_epollex_linux.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <poll.h>
+#include <pthread.h>
+#include <string.h>
#include <sys/epoll.h>
-#include <sys/socket.h>
-#include <sys/syscall.h>
-#include <unistd.h>
-
+#include <sys/socket.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
#include <util/generic/string.h>
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gpr/spinlock.h"
-#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
+#include <grpc/support/alloc.h>
+
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gpr/spinlock.h"
+#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/iomgr/block_annotate.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/is_epollexclusive_available.h"
-#include "src/core/lib/iomgr/lockfree_event.h"
-#include "src/core/lib/iomgr/sys_epoll_wrapper.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-#include "src/core/lib/profiling/timers.h"
-
-// debug aid: create workers on the heap (allows asan to spot
-// use-after-destruction)
-//#define GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP 1
-
-#define MAX_EPOLL_EVENTS 100
+#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"
+#include "src/core/lib/iomgr/lockfree_event.h"
+#include "src/core/lib/iomgr/sys_epoll_wrapper.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+#include "src/core/lib/profiling/timers.h"
+
+// debug aid: create workers on the heap (allows asan to spot
+// use-after-destruction)
+//#define GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP 1
+
+#define MAX_EPOLL_EVENTS 100
#define MAX_FDS_IN_CACHE 32
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_pollable_refcount(false,
- "pollable_refcount");
-
-/*******************************************************************************
- * pollable Declarations
- */
-
-typedef enum { PO_MULTI, PO_FD, PO_EMPTY } pollable_type;
-
-typedef struct pollable pollable;
-
-/// A pollable is something that can be polled: it has an epoll set to poll on,
-/// and a wakeup fd for kicks
-/// There are three broad types:
-/// - PO_EMPTY - the empty pollable, used before file descriptors are added to
-/// a pollset
-/// - PO_FD - a pollable containing only one FD - used to optimize single-fd
-/// pollsets (which are common with synchronous api usage)
-/// - PO_MULTI - a pollable containing many fds
-struct pollable {
- pollable_type type; // immutable
+
+grpc_core::DebugOnlyTraceFlag grpc_trace_pollable_refcount(false,
+ "pollable_refcount");
+
+/*******************************************************************************
+ * pollable Declarations
+ */
+
+typedef enum { PO_MULTI, PO_FD, PO_EMPTY } pollable_type;
+
+typedef struct pollable pollable;
+
+/// A pollable is something that can be polled: it has an epoll set to poll on,
+/// and a wakeup fd for kicks
+/// There are three broad types:
+/// - PO_EMPTY - the empty pollable, used before file descriptors are added to
+/// a pollset
+/// - PO_FD - a pollable containing only one FD - used to optimize single-fd
+/// pollsets (which are common with synchronous api usage)
+/// - PO_MULTI - a pollable containing many fds
+struct pollable {
+ pollable_type type; // immutable
grpc_core::RefCount refs;
-
- int epfd;
- grpc_wakeup_fd wakeup;
-
+
+ int epfd;
+ grpc_wakeup_fd wakeup;
+
// The following are relevant only for type PO_FD
grpc_fd* owner_fd; // Set to the owner_fd if the type is PO_FD
gpr_mu owner_orphan_mu; // Synchronizes access to owner_orphaned field
bool owner_orphaned; // Is the owner fd orphaned
-
- grpc_pollset_set* pollset_set;
- pollable* next;
- pollable* prev;
-
- gpr_mu mu;
- grpc_pollset_worker* root_worker;
-
- int event_cursor;
- int event_count;
- struct epoll_event events[MAX_EPOLL_EVENTS];
-};
-
-static const char* pollable_type_string(pollable_type t) {
- switch (t) {
- case PO_MULTI:
- return "pollset";
- case PO_FD:
- return "fd";
- case PO_EMPTY:
- return "empty";
- }
- return "<invalid>";
-}
-
+
+ grpc_pollset_set* pollset_set;
+ pollable* next;
+ pollable* prev;
+
+ gpr_mu mu;
+ grpc_pollset_worker* root_worker;
+
+ int event_cursor;
+ int event_count;
+ struct epoll_event events[MAX_EPOLL_EVENTS];
+};
+
+static const char* pollable_type_string(pollable_type t) {
+ switch (t) {
+ case PO_MULTI:
+ return "pollset";
+ case PO_FD:
+ return "fd";
+ case PO_EMPTY:
+ return "empty";
+ }
+ return "<invalid>";
+}
+
static TString pollable_desc(pollable* p) {
return y_absl::StrFormat("type=%s epfd=%d wakeup=%d",
pollable_type_string(p->type), p->epfd,
p->wakeup.read_fd);
-}
-
-/// Shared empty pollable - used by pollset to poll on until the first fd is
-/// added
-static pollable* g_empty_pollable;
-
-static grpc_error* pollable_create(pollable_type type, pollable** p);
+}
+
+/// Shared empty pollable - used by pollset to poll on until the first fd is
+/// added
+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) {
@@ -155,12 +155,12 @@ static void pollable_unref(pollable* p, const grpc_core::DebugLocation& dbg_loc,
}
#define POLLABLE_REF(p, r) pollable_ref((p), DEBUG_LOCATION, (r))
#define POLLABLE_UNREF(p, r) pollable_unref((p), DEBUG_LOCATION, (r))
-
-/*******************************************************************************
- * Fd Declarations
- */
-
-struct grpc_fd {
+
+/*******************************************************************************
+ * Fd Declarations
+ */
+
+struct grpc_fd {
grpc_fd(int fd, const char* name, bool track_err)
: fd(fd), track_err(track_err) {
gpr_mu_init(&orphan_mu);
@@ -225,137 +225,137 @@ struct grpc_fd {
void invalidate() {}
#endif
- int fd;
-
+ int fd;
+
// refst format:
// bit 0 : 1=Active / 0=Orphaned
// bits 1-n : refcount
// Ref/Unref by two to avoid altering the orphaned bit
gpr_atm refst = 1;
- gpr_mu orphan_mu;
-
+ gpr_mu orphan_mu;
+
// Protects pollable_obj and pollset_fds.
- gpr_mu pollable_mu;
+ gpr_mu pollable_mu;
y_absl::InlinedVector<int, 1> pollset_fds; // Used in PO_MULTI.
pollable* pollable_obj = nullptr; // Used in PO_FD.
-
+
grpc_core::LockfreeEvent read_closure;
grpc_core::LockfreeEvent write_closure;
grpc_core::LockfreeEvent error_closure;
-
+
struct grpc_fd* freelist_next = nullptr;
grpc_closure* on_done_closure = nullptr;
-
+
grpc_iomgr_object iomgr_object;
-
+
// Do we need to track EPOLLERR events separately?
bool track_err;
-};
-
-static void fd_global_init(void);
-static void fd_global_shutdown(void);
-
-/*******************************************************************************
- * Pollset Declarations
- */
-
+};
+
+static void fd_global_init(void);
+static void fd_global_shutdown(void);
+
+/*******************************************************************************
+ * Pollset Declarations
+ */
+
struct pwlink {
- grpc_pollset_worker* next;
- grpc_pollset_worker* prev;
+ grpc_pollset_worker* next;
+ grpc_pollset_worker* prev;
};
-typedef enum { PWLINK_POLLABLE = 0, PWLINK_POLLSET, PWLINK_COUNT } pwlinks;
-
-struct grpc_pollset_worker {
- bool kicked;
- bool initialized_cv;
-#ifndef NDEBUG
- // debug aid: which thread started this worker
- pid_t originator;
-#endif
- gpr_cv cv;
- grpc_pollset* pollset;
- pollable* pollable_obj;
-
- pwlink links[PWLINK_COUNT];
-};
-
-struct grpc_pollset {
- gpr_mu mu;
- gpr_atm worker_count;
+typedef enum { PWLINK_POLLABLE = 0, PWLINK_POLLSET, PWLINK_COUNT } pwlinks;
+
+struct grpc_pollset_worker {
+ bool kicked;
+ bool initialized_cv;
+#ifndef NDEBUG
+ // debug aid: which thread started this worker
+ pid_t originator;
+#endif
+ gpr_cv cv;
+ grpc_pollset* pollset;
+ pollable* pollable_obj;
+
+ pwlink links[PWLINK_COUNT];
+};
+
+struct grpc_pollset {
+ gpr_mu mu;
+ gpr_atm worker_count;
gpr_atm active_pollable_type;
- pollable* active_pollable;
- bool kicked_without_poller;
- grpc_closure* shutdown_closure;
- bool already_shutdown;
- grpc_pollset_worker* root_worker;
- int containing_pollset_set_count;
-};
-
-/*******************************************************************************
- * Pollset-set Declarations
- */
-
-struct grpc_pollset_set {
+ pollable* active_pollable;
+ bool kicked_without_poller;
+ grpc_closure* shutdown_closure;
+ bool already_shutdown;
+ grpc_pollset_worker* root_worker;
+ int containing_pollset_set_count;
+};
+
+/*******************************************************************************
+ * Pollset-set Declarations
+ */
+
+struct grpc_pollset_set {
grpc_core::RefCount refs;
- gpr_mu mu;
- grpc_pollset_set* parent;
-
- size_t pollset_count;
- size_t pollset_capacity;
- grpc_pollset** pollsets;
-
- size_t fd_count;
- size_t fd_capacity;
- grpc_fd** fds;
-};
-
-/*******************************************************************************
- * Common helpers
- */
-
-static bool append_error(grpc_error** composite, grpc_error* error,
- const char* desc) {
- if (error == GRPC_ERROR_NONE) return true;
- if (*composite == GRPC_ERROR_NONE) {
- *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc);
- }
- *composite = grpc_error_add_child(*composite, error);
- return false;
-}
-
-/*******************************************************************************
- * Fd Definitions
- */
-
-/* We need to keep a freelist not because of any concerns of malloc performance
- * but instead so that implementations with multiple threads in (for example)
- * epoll_wait deal with the race between pollset removal and incoming poll
- * notifications.
- *
- * The problem is that the poller ultimately holds a reference to this
- * object, so it is very difficult to know when is safe to free it, at least
- * without some expensive synchronization.
- *
- * If we keep the object freelisted, in the worst case losing this race just
- * becomes a spurious read notification on a reused fd.
- */
-
-static grpc_fd* fd_freelist = nullptr;
-static gpr_mu fd_freelist_mu;
-
-#ifndef NDEBUG
-#define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__)
-#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) {
+ gpr_mu mu;
+ grpc_pollset_set* parent;
+
+ size_t pollset_count;
+ size_t pollset_capacity;
+ grpc_pollset** pollsets;
+
+ size_t fd_count;
+ size_t fd_capacity;
+ grpc_fd** fds;
+};
+
+/*******************************************************************************
+ * Common helpers
+ */
+
+static bool append_error(grpc_error** composite, grpc_error* error,
+ const char* desc) {
+ if (error == GRPC_ERROR_NONE) return true;
+ if (*composite == GRPC_ERROR_NONE) {
+ *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc);
+ }
+ *composite = grpc_error_add_child(*composite, error);
+ return false;
+}
+
+/*******************************************************************************
+ * Fd Definitions
+ */
+
+/* We need to keep a freelist not because of any concerns of malloc performance
+ * but instead so that implementations with multiple threads in (for example)
+ * epoll_wait deal with the race between pollset removal and incoming poll
+ * notifications.
+ *
+ * The problem is that the poller ultimately holds a reference to this
+ * object, so it is very difficult to know when is safe to free it, at least
+ * without some expensive synchronization.
+ *
+ * If we keep the object freelisted, in the worst case losing this race just
+ * becomes a spurious read notification on a reused fd.
+ */
+
+static grpc_fd* fd_freelist = nullptr;
+static gpr_mu fd_freelist_mu;
+
+#ifndef NDEBUG
+#define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__)
+#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)) {
- 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
+ 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); \
@@ -366,91 +366,91 @@ static void ref_by(grpc_fd* fd, int n, const char* reason, const char* file,
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);
-}
-
+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*/) {
- grpc_fd* fd = static_cast<grpc_fd*>(arg);
+ grpc_fd* fd = static_cast<grpc_fd*>(arg);
fd->destroy();
- /* Add the fd to the freelist */
- gpr_mu_lock(&fd_freelist_mu);
- fd->freelist_next = fd_freelist;
- fd_freelist = fd;
- gpr_mu_unlock(&fd_freelist_mu);
-}
-
-#ifndef NDEBUG
-static void unref_by(grpc_fd* fd, int n, const char* reason, const char* file,
- int line) {
+ /* Add the fd to the freelist */
+ gpr_mu_lock(&fd_freelist_mu);
+ fd->freelist_next = fd_freelist;
+ fd_freelist = fd;
+ gpr_mu_unlock(&fd_freelist_mu);
+}
+
+#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)) {
- 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),
- gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line);
- }
-#else
-static void unref_by(grpc_fd* fd, int n) {
-#endif
- gpr_atm old = gpr_atm_full_fetch_add(&fd->refst, -n);
- if (old == n) {
+ 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),
+ gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line);
+ }
+#else
+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_CLOSURE_CREATE(fd_destroy, fd, grpc_schedule_on_exec_ctx),
- GRPC_ERROR_NONE);
- } else {
- GPR_ASSERT(old > n);
- }
-}
-
-static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); }
-
-static void fd_global_shutdown(void) {
+ GRPC_CLOSURE_CREATE(fd_destroy, fd, grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_NONE);
+ } else {
+ GPR_ASSERT(old > n);
+ }
+}
+
+static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); }
+
+static void fd_global_shutdown(void) {
// TODO(guantaol): We don't have a reasonable explanation about this
// lock()/unlock() pattern. It can be a valid barrier if there is at most one
// pending lock() at this point. Otherwise, there is still a possibility of
// use-after-free race. Need to reason about the code and/or clean it up.
- gpr_mu_lock(&fd_freelist_mu);
- gpr_mu_unlock(&fd_freelist_mu);
- while (fd_freelist != nullptr) {
- grpc_fd* fd = fd_freelist;
- fd_freelist = fd_freelist->freelist_next;
- gpr_free(fd);
- }
- gpr_mu_destroy(&fd_freelist_mu);
-}
-
+ gpr_mu_lock(&fd_freelist_mu);
+ gpr_mu_unlock(&fd_freelist_mu);
+ while (fd_freelist != nullptr) {
+ grpc_fd* fd = fd_freelist;
+ fd_freelist = fd_freelist->freelist_next;
+ gpr_free(fd);
+ }
+ gpr_mu_destroy(&fd_freelist_mu);
+}
+
static grpc_fd* fd_create(int fd, const char* name, bool track_err) {
- grpc_fd* new_fd = nullptr;
-
- gpr_mu_lock(&fd_freelist_mu);
- if (fd_freelist != nullptr) {
- new_fd = fd_freelist;
- fd_freelist = fd_freelist->freelist_next;
- }
- gpr_mu_unlock(&fd_freelist_mu);
-
- if (new_fd == nullptr) {
- new_fd = static_cast<grpc_fd*>(gpr_malloc(sizeof(grpc_fd)));
- }
-
+ grpc_fd* new_fd = nullptr;
+
+ gpr_mu_lock(&fd_freelist_mu);
+ if (fd_freelist != nullptr) {
+ new_fd = fd_freelist;
+ fd_freelist = fd_freelist->freelist_next;
+ }
+ gpr_mu_unlock(&fd_freelist_mu);
+
+ if (new_fd == nullptr) {
+ new_fd = static_cast<grpc_fd*>(gpr_malloc(sizeof(grpc_fd)));
+ }
+
return new (new_fd) grpc_fd(fd, name, track_err);
-}
-
-static int fd_wrapped_fd(grpc_fd* fd) {
- int ret_fd = fd->fd;
- return (gpr_atm_acq_load(&fd->refst) & 1) ? ret_fd : -1;
-}
-
-static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
+}
+
+static int fd_wrapped_fd(grpc_fd* fd) {
+ int ret_fd = fd->fd;
+ return (gpr_atm_acq_load(&fd->refst) & 1) ? ret_fd : -1;
+}
+
+static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
const char* reason) {
bool is_fd_closed = false;
-
- gpr_mu_lock(&fd->orphan_mu);
-
+
+ gpr_mu_lock(&fd->orphan_mu);
+
// Get the fd->pollable_obj and set the owner_orphaned on that pollable to
// true so that the pollable will no longer access its owner_fd field.
gpr_mu_lock(&fd->pollable_mu);
@@ -461,11 +461,11 @@ static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
pollable_obj->owner_orphaned = true;
}
- fd->on_done_closure = on_done;
-
- /* If release_fd is not NULL, we should be relinquishing control of the file
- descriptor fd->fd (but we still own the grpc_fd structure). */
- if (release_fd != nullptr) {
+ fd->on_done_closure = on_done;
+
+ /* If release_fd is not NULL, we should be relinquishing control of the file
+ descriptor fd->fd (but we still own the grpc_fd structure). */
+ if (release_fd != nullptr) {
// Remove the FD from all epolls sets, before releasing it.
// Otherwise, we will receive epoll events after we release the FD.
epoll_event ev_fd;
@@ -477,39 +477,39 @@ static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
const int epfd = fd->pollset_fds[i];
epoll_ctl(epfd, EPOLL_CTL_DEL, fd->fd, &ev_fd);
}
- *release_fd = fd->fd;
+ *release_fd = fd->fd;
} else {
- close(fd->fd);
- is_fd_closed = true;
- }
-
+ close(fd->fd);
+ is_fd_closed = true;
+ }
+
// TODO(sreek): handle fd removal (where is_fd_closed=false)
- if (!is_fd_closed) {
+ if (!is_fd_closed) {
GRPC_FD_TRACE("epoll_fd %p (%d) was orphaned but not closed.", fd, fd->fd);
- }
-
- /* Remove the active status but keep referenced. We want this grpc_fd struct
- to be alive (and not added to freelist) until the end of this function */
- REF_BY(fd, 1, reason);
-
+ }
+
+ /* Remove the active status but keep referenced. We want this grpc_fd struct
+ 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);
-
+
if (pollable_obj) {
gpr_mu_unlock(&pollable_obj->owner_orphan_mu);
}
gpr_mu_unlock(&fd->pollable_mu);
- gpr_mu_unlock(&fd->orphan_mu);
-
- UNREF_BY(fd, 2, reason); /* Drop the reference */
-}
-
-static bool fd_is_shutdown(grpc_fd* fd) {
+ gpr_mu_unlock(&fd->orphan_mu);
+
+ UNREF_BY(fd, 2, reason); /* Drop the reference */
+}
+
+static bool fd_is_shutdown(grpc_fd* fd) {
return fd->read_closure.IsShutdown();
-}
-
-/* Might be called multiple times */
-static void fd_shutdown(grpc_fd* fd, grpc_error* why) {
+}
+
+/* Might be called multiple times */
+static void fd_shutdown(grpc_fd* fd, grpc_error* why) {
if (fd->read_closure.SetShutdown(GRPC_ERROR_REF(why))) {
if (shutdown(fd->fd, SHUT_RDWR)) {
if (errno != ENOTCONN) {
@@ -519,18 +519,18 @@ static void fd_shutdown(grpc_fd* fd, grpc_error* why) {
}
fd->write_closure.SetShutdown(GRPC_ERROR_REF(why));
fd->error_closure.SetShutdown(GRPC_ERROR_REF(why));
- }
- GRPC_ERROR_UNREF(why);
-}
-
-static void fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
+ }
+ GRPC_ERROR_UNREF(why);
+}
+
+static void fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
fd->read_closure.NotifyOn(closure);
-}
-
-static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
+}
+
+static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
fd->write_closure.NotifyOn(closure);
-}
-
+}
+
static void fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) {
fd->error_closure.NotifyOn(closure);
}
@@ -552,70 +552,70 @@ static void fd_add_pollset(grpc_fd* fd, grpc_pollset* pollset) {
fd->pollset_fds.push_back(epfd);
}
-/*******************************************************************************
- * Pollable Definitions
- */
-
-static grpc_error* pollable_create(pollable_type type, pollable** p) {
- *p = nullptr;
-
- int epfd = epoll_create1(EPOLL_CLOEXEC);
- if (epfd == -1) {
- return GRPC_OS_ERROR(errno, "epoll_create1");
- }
+/*******************************************************************************
+ * Pollable Definitions
+ */
+
+static grpc_error* pollable_create(pollable_type type, pollable** p) {
+ *p = nullptr;
+
+ int epfd = epoll_create1(EPOLL_CLOEXEC);
+ if (epfd == -1) {
+ return GRPC_OS_ERROR(errno, "epoll_create1");
+ }
GRPC_FD_TRACE("Pollable_create: created epfd: %d (type: %d)", epfd, type);
- *p = static_cast<pollable*>(gpr_malloc(sizeof(**p)));
- grpc_error* err = grpc_wakeup_fd_init(&(*p)->wakeup);
- if (err != GRPC_ERROR_NONE) {
+ *p = static_cast<pollable*>(gpr_malloc(sizeof(**p)));
+ grpc_error* err = grpc_wakeup_fd_init(&(*p)->wakeup);
+ if (err != GRPC_ERROR_NONE) {
GRPC_FD_TRACE(
"Pollable_create: closed epfd: %d (type: %d). wakeupfd_init error",
epfd, type);
- close(epfd);
- gpr_free(*p);
- *p = nullptr;
- return err;
- }
- struct epoll_event ev;
- ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLET);
- ev.data.ptr = (void*)(1 | (intptr_t) & (*p)->wakeup);
- if (epoll_ctl(epfd, EPOLL_CTL_ADD, (*p)->wakeup.read_fd, &ev) != 0) {
- err = GRPC_OS_ERROR(errno, "epoll_ctl");
+ close(epfd);
+ gpr_free(*p);
+ *p = nullptr;
+ return err;
+ }
+ struct epoll_event ev;
+ ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLET);
+ ev.data.ptr = (void*)(1 | (intptr_t) & (*p)->wakeup);
+ if (epoll_ctl(epfd, EPOLL_CTL_ADD, (*p)->wakeup.read_fd, &ev) != 0) {
+ err = GRPC_OS_ERROR(errno, "epoll_ctl");
GRPC_FD_TRACE(
"Pollable_create: closed epfd: %d (type: %d). epoll_ctl error", epfd,
type);
- close(epfd);
- grpc_wakeup_fd_destroy(&(*p)->wakeup);
- gpr_free(*p);
- *p = nullptr;
- return err;
- }
-
- (*p)->type = type;
+ close(epfd);
+ grpc_wakeup_fd_destroy(&(*p)->wakeup);
+ gpr_free(*p);
+ *p = nullptr;
+ return err;
+ }
+
+ (*p)->type = type;
new (&(*p)->refs) grpc_core::RefCount(1, &grpc_trace_pollable_refcount);
- gpr_mu_init(&(*p)->mu);
- (*p)->epfd = epfd;
- (*p)->owner_fd = nullptr;
+ gpr_mu_init(&(*p)->mu);
+ (*p)->epfd = epfd;
+ (*p)->owner_fd = nullptr;
gpr_mu_init(&(*p)->owner_orphan_mu);
(*p)->owner_orphaned = false;
- (*p)->pollset_set = nullptr;
- (*p)->next = (*p)->prev = *p;
- (*p)->root_worker = nullptr;
- (*p)->event_cursor = 0;
- (*p)->event_count = 0;
- return GRPC_ERROR_NONE;
-}
-
-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;
+ (*p)->pollset_set = nullptr;
+ (*p)->next = (*p)->prev = *p;
+ (*p)->root_worker = nullptr;
+ (*p)->event_cursor = 0;
+ (*p)->event_count = 0;
+ return GRPC_ERROR_NONE;
+}
+
+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)) {
- gpr_log(GPR_INFO, "add fd %p (%d) to pollable %p", fd, fd->fd, p);
- }
-
- struct epoll_event ev_fd;
- ev_fd.events =
- static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLOUT | EPOLLEXCLUSIVE);
+ gpr_log(GPR_INFO, "add fd %p (%d) to pollable %p", fd, fd->fd, p);
+ }
+
+ struct epoll_event ev_fd;
+ ev_fd.events =
+ static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLOUT | EPOLLEXCLUSIVE);
/* Use the second least significant bit of ev_fd.data.ptr to store track_err
* to avoid synchronization issues when accessing it after receiving an event.
* Accessing fd would be a data race there because the fd might have been
@@ -623,662 +623,662 @@ static grpc_error* pollable_add_fd(pollable* p, grpc_fd* fd) {
ev_fd.data.ptr = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(fd) |
(fd->track_err ? 2 : 0));
GRPC_STATS_INC_SYSCALL_EPOLL_CTL();
- if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd->fd, &ev_fd) != 0) {
- switch (errno) {
- case EEXIST:
- break;
- default:
- append_error(&error, GRPC_OS_ERROR(errno, "epoll_ctl"), err_desc);
- }
- }
-
- return error;
-}
-
-/*******************************************************************************
- * Pollset Definitions
- */
-
-GPR_TLS_DECL(g_current_thread_pollset);
-GPR_TLS_DECL(g_current_thread_worker);
-
-/* Global state management */
-static grpc_error* pollset_global_init(void) {
- gpr_tls_init(&g_current_thread_pollset);
- gpr_tls_init(&g_current_thread_worker);
- return pollable_create(PO_EMPTY, &g_empty_pollable);
-}
-
-static void pollset_global_shutdown(void) {
- POLLABLE_UNREF(g_empty_pollable, "g_empty_pollable");
- gpr_tls_destroy(&g_current_thread_pollset);
- gpr_tls_destroy(&g_current_thread_worker);
-}
-
-/* pollset->mu must be held while calling this function */
-static void pollset_maybe_finish_shutdown(grpc_pollset* pollset) {
+ if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd->fd, &ev_fd) != 0) {
+ switch (errno) {
+ case EEXIST:
+ break;
+ default:
+ append_error(&error, GRPC_OS_ERROR(errno, "epoll_ctl"), err_desc);
+ }
+ }
+
+ return error;
+}
+
+/*******************************************************************************
+ * Pollset Definitions
+ */
+
+GPR_TLS_DECL(g_current_thread_pollset);
+GPR_TLS_DECL(g_current_thread_worker);
+
+/* Global state management */
+static grpc_error* pollset_global_init(void) {
+ gpr_tls_init(&g_current_thread_pollset);
+ gpr_tls_init(&g_current_thread_worker);
+ return pollable_create(PO_EMPTY, &g_empty_pollable);
+}
+
+static void pollset_global_shutdown(void) {
+ POLLABLE_UNREF(g_empty_pollable, "g_empty_pollable");
+ gpr_tls_destroy(&g_current_thread_pollset);
+ gpr_tls_destroy(&g_current_thread_worker);
+}
+
+/* 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)) {
- gpr_log(GPR_INFO,
- "PS:%p (pollable:%p) maybe_finish_shutdown sc=%p (target:!NULL) "
- "rw=%p (target:NULL) cpsc=%d (target:0)",
- pollset, pollset->active_pollable, pollset->shutdown_closure,
- pollset->root_worker, pollset->containing_pollset_set_count);
- }
- if (pollset->shutdown_closure != nullptr && pollset->root_worker == nullptr &&
- pollset->containing_pollset_set_count == 0) {
- GPR_TIMER_MARK("pollset_finish_shutdown", 0);
+ gpr_log(GPR_INFO,
+ "PS:%p (pollable:%p) maybe_finish_shutdown sc=%p (target:!NULL) "
+ "rw=%p (target:NULL) cpsc=%d (target:0)",
+ pollset, pollset->active_pollable, pollset->shutdown_closure,
+ pollset->root_worker, pollset->containing_pollset_set_count);
+ }
+ 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);
- pollset->shutdown_closure = nullptr;
- pollset->already_shutdown = true;
- }
-}
-
-/* pollset->mu must be held before calling this function,
- * pollset->active_pollable->mu & specific_worker->pollable_obj->mu must not be
- * held */
-static grpc_error* kick_one_worker(grpc_pollset_worker* specific_worker) {
- GPR_TIMER_SCOPE("kick_one_worker", 0);
- pollable* p = specific_worker->pollable_obj;
+ pollset->shutdown_closure = nullptr;
+ pollset->already_shutdown = true;
+ }
+}
+
+/* pollset->mu must be held before calling this function,
+ * pollset->active_pollable->mu & specific_worker->pollable_obj->mu must not be
+ * held */
+static grpc_error* kick_one_worker(grpc_pollset_worker* specific_worker) {
+ GPR_TIMER_SCOPE("kick_one_worker", 0);
+ pollable* p = specific_worker->pollable_obj;
grpc_core::MutexLock lock(&p->mu);
- GPR_ASSERT(specific_worker != nullptr);
- if (specific_worker->kicked) {
+ GPR_ASSERT(specific_worker != nullptr);
+ if (specific_worker->kicked) {
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) {
+ 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)) {
- gpr_log(GPR_INFO, "PS:%p kicked_specific_but_awake", p);
- }
- GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
- specific_worker->kicked = true;
- return GRPC_ERROR_NONE;
- }
- if (specific_worker == p->root_worker) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
+ gpr_log(GPR_INFO, "PS:%p kicked_specific_but_awake", p);
+ }
+ GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
+ specific_worker->kicked = true;
+ return GRPC_ERROR_NONE;
+ }
+ if (specific_worker == p->root_worker) {
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD();
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "PS:%p kicked_specific_via_wakeup_fd", p);
- }
- specific_worker->kicked = true;
- grpc_error* error = grpc_wakeup_fd_wakeup(&p->wakeup);
- return error;
- }
- if (specific_worker->initialized_cv) {
- GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
+ gpr_log(GPR_INFO, "PS:%p kicked_specific_via_wakeup_fd", p);
+ }
+ specific_worker->kicked = true;
+ grpc_error* error = grpc_wakeup_fd_wakeup(&p->wakeup);
+ return error;
+ }
+ if (specific_worker->initialized_cv) {
+ GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV();
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "PS:%p kicked_specific_via_cv", p);
- }
- specific_worker->kicked = true;
- gpr_cv_signal(&specific_worker->cv);
- return GRPC_ERROR_NONE;
- }
- // we can get here during end_worker after removing specific_worker from the
- // pollable list but before removing it from the pollset list
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* pollset_kick(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker) {
- GPR_TIMER_SCOPE("pollset_kick", 0);
- GRPC_STATS_INC_POLLSET_KICK();
+ gpr_log(GPR_INFO, "PS:%p kicked_specific_via_cv", p);
+ }
+ specific_worker->kicked = true;
+ gpr_cv_signal(&specific_worker->cv);
+ return GRPC_ERROR_NONE;
+ }
+ // we can get here during end_worker after removing specific_worker from the
+ // pollable list but before removing it from the pollset list
+ return GRPC_ERROR_NONE;
+}
+
+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)) {
- gpr_log(GPR_INFO,
- "PS:%p kick %p tls_pollset=%p tls_worker=%p pollset.root_worker=%p",
- pollset, specific_worker,
- (void*)gpr_tls_get(&g_current_thread_pollset),
- (void*)gpr_tls_get(&g_current_thread_worker), pollset->root_worker);
- }
- if (specific_worker == nullptr) {
- if (gpr_tls_get(&g_current_thread_pollset) != (intptr_t)pollset) {
- if (pollset->root_worker == nullptr) {
+ gpr_log(GPR_INFO,
+ "PS:%p kick %p tls_pollset=%p tls_worker=%p pollset.root_worker=%p",
+ pollset, specific_worker,
+ (void*)gpr_tls_get(&g_current_thread_pollset),
+ (void*)gpr_tls_get(&g_current_thread_worker), pollset->root_worker);
+ }
+ 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)) {
- gpr_log(GPR_INFO, "PS:%p kicked_any_without_poller", pollset);
- }
- GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER();
- pollset->kicked_without_poller = true;
- return GRPC_ERROR_NONE;
- } else {
- // We've been asked to kick a poller, but we haven't been told which one
- // ... any will do
- // We look at the pollset worker list because:
- // 1. the pollable list may include workers from other pollers, so we'd
- // need to do an O(N) search
- // 2. we'd additionally need to take the pollable lock, which we've so
- // far avoided
- // Now, we would prefer to wake a poller in cv_wait, and not in
- // epoll_wait (since the latter would imply the need to do an additional
- // wakeup)
- // We know that if a worker is at the root of a pollable, it's (likely)
- // also the root of a pollset, and we know that if a worker is NOT at
- // the root of a pollset, it's (likely) not at the root of a pollable,
- // so we take our chances and choose the SECOND worker enqueued against
- // the pollset as a worker that's likely to be in cv_wait
- return kick_one_worker(
- pollset->root_worker->links[PWLINK_POLLSET].next);
- }
- } else {
+ gpr_log(GPR_INFO, "PS:%p kicked_any_without_poller", pollset);
+ }
+ GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER();
+ pollset->kicked_without_poller = true;
+ return GRPC_ERROR_NONE;
+ } else {
+ // We've been asked to kick a poller, but we haven't been told which one
+ // ... any will do
+ // We look at the pollset worker list because:
+ // 1. the pollable list may include workers from other pollers, so we'd
+ // need to do an O(N) search
+ // 2. we'd additionally need to take the pollable lock, which we've so
+ // far avoided
+ // Now, we would prefer to wake a poller in cv_wait, and not in
+ // epoll_wait (since the latter would imply the need to do an additional
+ // wakeup)
+ // We know that if a worker is at the root of a pollable, it's (likely)
+ // also the root of a pollset, and we know that if a worker is NOT at
+ // the root of a pollset, it's (likely) not at the root of a pollable,
+ // so we take our chances and choose the SECOND worker enqueued against
+ // the pollset as a worker that's likely to be in cv_wait
+ return kick_one_worker(
+ pollset->root_worker->links[PWLINK_POLLSET].next);
+ }
+ } else {
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();
- return GRPC_ERROR_NONE;
- }
- } else {
- return kick_one_worker(specific_worker);
- }
-}
-
-static grpc_error* pollset_kick_all(grpc_pollset* pollset) {
- GPR_TIMER_SCOPE("pollset_kick_all", 0);
- grpc_error* error = GRPC_ERROR_NONE;
- const char* err_desc = "pollset_kick_all";
- grpc_pollset_worker* w = pollset->root_worker;
- if (w != nullptr) {
- do {
- GRPC_STATS_INC_POLLSET_KICK();
- append_error(&error, kick_one_worker(w), err_desc);
- w = w->links[PWLINK_POLLSET].next;
- } while (w != pollset->root_worker);
- }
- return error;
-}
-
-static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
- gpr_mu_init(&pollset->mu);
- gpr_atm_no_barrier_store(&pollset->worker_count, 0);
+ gpr_log(GPR_INFO, "PS:%p kicked_any_but_awake", pollset);
+ }
+ GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD();
+ return GRPC_ERROR_NONE;
+ }
+ } else {
+ return kick_one_worker(specific_worker);
+ }
+}
+
+static grpc_error* pollset_kick_all(grpc_pollset* pollset) {
+ GPR_TIMER_SCOPE("pollset_kick_all", 0);
+ grpc_error* error = GRPC_ERROR_NONE;
+ const char* err_desc = "pollset_kick_all";
+ grpc_pollset_worker* w = pollset->root_worker;
+ if (w != nullptr) {
+ do {
+ GRPC_STATS_INC_POLLSET_KICK();
+ append_error(&error, kick_one_worker(w), err_desc);
+ w = w->links[PWLINK_POLLSET].next;
+ } while (w != pollset->root_worker);
+ }
+ return error;
+}
+
+static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
+ gpr_mu_init(&pollset->mu);
+ gpr_atm_no_barrier_store(&pollset->worker_count, 0);
gpr_atm_no_barrier_store(&pollset->active_pollable_type, PO_EMPTY);
- pollset->active_pollable = POLLABLE_REF(g_empty_pollable, "pollset");
- pollset->kicked_without_poller = false;
- pollset->shutdown_closure = nullptr;
- pollset->already_shutdown = false;
- pollset->root_worker = nullptr;
- pollset->containing_pollset_set_count = 0;
- *mu = &pollset->mu;
-}
-
-static int poll_deadline_to_millis_timeout(grpc_millis millis) {
- if (millis == GRPC_MILLIS_INF_FUTURE) return -1;
- grpc_millis delta = millis - grpc_core::ExecCtx::Get()->Now();
- if (delta > INT_MAX)
- return INT_MAX;
- else if (delta < 0)
- return 0;
- else
- return static_cast<int>(delta);
-}
-
+ pollset->active_pollable = POLLABLE_REF(g_empty_pollable, "pollset");
+ pollset->kicked_without_poller = false;
+ pollset->shutdown_closure = nullptr;
+ pollset->already_shutdown = false;
+ pollset->root_worker = nullptr;
+ pollset->containing_pollset_set_count = 0;
+ *mu = &pollset->mu;
+}
+
+static int poll_deadline_to_millis_timeout(grpc_millis millis) {
+ if (millis == GRPC_MILLIS_INF_FUTURE) return -1;
+ grpc_millis delta = millis - grpc_core::ExecCtx::Get()->Now();
+ if (delta > INT_MAX)
+ return INT_MAX;
+ else if (delta < 0)
+ return 0;
+ else
+ return static_cast<int>(delta);
+}
+
static void fd_become_readable(grpc_fd* fd) { fd->read_closure.SetReady(); }
-
+
static void fd_become_writable(grpc_fd* fd) { fd->write_closure.SetReady(); }
-
+
static void fd_has_errors(grpc_fd* fd) { fd->error_closure.SetReady(); }
-
+
/* Get the pollable_obj attached to this fd. If none is attached, create a new
* pollable object (of type PO_FD), attach it to the fd and return it
*
* Note that if a pollable object is already attached to the fd, it may be of
* either PO_FD or PO_MULTI type */
static grpc_error* get_fd_pollable(grpc_fd* fd, pollable** p) {
- gpr_mu_lock(&fd->pollable_mu);
- grpc_error* error = GRPC_ERROR_NONE;
+ gpr_mu_lock(&fd->pollable_mu);
+ grpc_error* error = GRPC_ERROR_NONE;
static const char* err_desc = "get_fd_pollable";
- if (fd->pollable_obj == nullptr) {
- if (append_error(&error, pollable_create(PO_FD, &fd->pollable_obj),
- err_desc)) {
- fd->pollable_obj->owner_fd = fd;
- if (!append_error(&error, pollable_add_fd(fd->pollable_obj, fd),
- err_desc)) {
- POLLABLE_UNREF(fd->pollable_obj, "fd_pollable");
- fd->pollable_obj = nullptr;
- }
- }
- }
- if (error == GRPC_ERROR_NONE) {
- GPR_ASSERT(fd->pollable_obj != nullptr);
- *p = POLLABLE_REF(fd->pollable_obj, "pollset");
- } else {
- GPR_ASSERT(fd->pollable_obj == nullptr);
- *p = nullptr;
- }
- gpr_mu_unlock(&fd->pollable_mu);
- return error;
-}
-
-/* pollset->po.mu lock must be held by the caller before calling this */
-static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
- GPR_TIMER_SCOPE("pollset_shutdown", 0);
- GPR_ASSERT(pollset->shutdown_closure == nullptr);
- pollset->shutdown_closure = closure;
- GRPC_LOG_IF_ERROR("pollset_shutdown", pollset_kick_all(pollset));
- pollset_maybe_finish_shutdown(pollset);
-}
-
-static grpc_error* pollable_process_events(grpc_pollset* pollset,
- pollable* pollable_obj, bool drain) {
- GPR_TIMER_SCOPE("pollable_process_events", 0);
- static const char* err_desc = "pollset_process_events";
- // Use a simple heuristic to determine how many fd events to process
- // per loop iteration. (events/workers)
- int handle_count = 1;
- int worker_count = gpr_atm_no_barrier_load(&pollset->worker_count);
- GPR_ASSERT(worker_count > 0);
- handle_count =
- (pollable_obj->event_count - pollable_obj->event_cursor) / worker_count;
- if (handle_count == 0) {
- handle_count = 1;
- }
- grpc_error* error = GRPC_ERROR_NONE;
- for (int i = 0; (drain || i < handle_count) &&
- pollable_obj->event_cursor != pollable_obj->event_count;
- i++) {
- int n = pollable_obj->event_cursor++;
- struct epoll_event* ev = &pollable_obj->events[n];
- void* data_ptr = ev->data.ptr;
- if (1 & (intptr_t)data_ptr) {
+ if (fd->pollable_obj == nullptr) {
+ if (append_error(&error, pollable_create(PO_FD, &fd->pollable_obj),
+ err_desc)) {
+ fd->pollable_obj->owner_fd = fd;
+ if (!append_error(&error, pollable_add_fd(fd->pollable_obj, fd),
+ err_desc)) {
+ POLLABLE_UNREF(fd->pollable_obj, "fd_pollable");
+ fd->pollable_obj = nullptr;
+ }
+ }
+ }
+ if (error == GRPC_ERROR_NONE) {
+ GPR_ASSERT(fd->pollable_obj != nullptr);
+ *p = POLLABLE_REF(fd->pollable_obj, "pollset");
+ } else {
+ GPR_ASSERT(fd->pollable_obj == nullptr);
+ *p = nullptr;
+ }
+ gpr_mu_unlock(&fd->pollable_mu);
+ return error;
+}
+
+/* pollset->po.mu lock must be held by the caller before calling this */
+static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
+ GPR_TIMER_SCOPE("pollset_shutdown", 0);
+ GPR_ASSERT(pollset->shutdown_closure == nullptr);
+ pollset->shutdown_closure = closure;
+ GRPC_LOG_IF_ERROR("pollset_shutdown", pollset_kick_all(pollset));
+ pollset_maybe_finish_shutdown(pollset);
+}
+
+static grpc_error* pollable_process_events(grpc_pollset* pollset,
+ pollable* pollable_obj, bool drain) {
+ GPR_TIMER_SCOPE("pollable_process_events", 0);
+ static const char* err_desc = "pollset_process_events";
+ // Use a simple heuristic to determine how many fd events to process
+ // per loop iteration. (events/workers)
+ int handle_count = 1;
+ int worker_count = gpr_atm_no_barrier_load(&pollset->worker_count);
+ GPR_ASSERT(worker_count > 0);
+ handle_count =
+ (pollable_obj->event_count - pollable_obj->event_cursor) / worker_count;
+ if (handle_count == 0) {
+ handle_count = 1;
+ }
+ grpc_error* error = GRPC_ERROR_NONE;
+ for (int i = 0; (drain || i < handle_count) &&
+ pollable_obj->event_cursor != pollable_obj->event_count;
+ i++) {
+ int n = pollable_obj->event_cursor++;
+ 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)) {
- gpr_log(GPR_INFO, "PS:%p got pollset_wakeup %p", pollset, data_ptr);
- }
- append_error(&error,
- grpc_wakeup_fd_consume_wakeup(
- (grpc_wakeup_fd*)((~static_cast<intptr_t>(1)) &
- (intptr_t)data_ptr)),
- err_desc);
- } else {
+ gpr_log(GPR_INFO, "PS:%p got pollset_wakeup %p", pollset, data_ptr);
+ }
+ append_error(&error,
+ grpc_wakeup_fd_consume_wakeup(
+ (grpc_wakeup_fd*)((~static_cast<intptr_t>(1)) &
+ (intptr_t)data_ptr)),
+ err_desc);
+ } else {
grpc_fd* fd =
reinterpret_cast<grpc_fd*>(reinterpret_cast<intptr_t>(data_ptr) & ~2);
bool track_err = reinterpret_cast<intptr_t>(data_ptr) & 2;
bool cancel = (ev->events & EPOLLHUP) != 0;
bool error = (ev->events & EPOLLERR) != 0;
- bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0;
- bool write_ev = (ev->events & EPOLLOUT) != 0;
+ bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0;
+ bool write_ev = (ev->events & EPOLLOUT) != 0;
bool err_fallback = error && !track_err;
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO,
- "PS:%p got fd %p: cancel=%d read=%d "
- "write=%d",
- pollset, fd, cancel, read_ev, write_ev);
- }
+ gpr_log(GPR_INFO,
+ "PS:%p got fd %p: cancel=%d read=%d "
+ "write=%d",
+ pollset, fd, cancel, read_ev, write_ev);
+ }
if (error && !err_fallback) {
fd_has_errors(fd);
- }
+ }
if (read_ev || cancel || err_fallback) {
fd_become_readable(fd);
}
if (write_ev || cancel || err_fallback) {
- fd_become_writable(fd);
- }
- }
- }
-
- return error;
-}
-
-/* pollset_shutdown is guaranteed to be called before pollset_destroy. */
-static void pollset_destroy(grpc_pollset* pollset) {
- POLLABLE_UNREF(pollset->active_pollable, "pollset");
- pollset->active_pollable = nullptr;
- gpr_mu_destroy(&pollset->mu);
-}
-
-static grpc_error* pollable_epoll(pollable* p, grpc_millis deadline) {
- GPR_TIMER_SCOPE("pollable_epoll", 0);
- int timeout = poll_deadline_to_millis_timeout(deadline);
-
+ fd_become_writable(fd);
+ }
+ }
+ }
+
+ return error;
+}
+
+/* pollset_shutdown is guaranteed to be called before pollset_destroy. */
+static void pollset_destroy(grpc_pollset* pollset) {
+ POLLABLE_UNREF(pollset->active_pollable, "pollset");
+ pollset->active_pollable = nullptr;
+ gpr_mu_destroy(&pollset->mu);
+}
+
+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)) {
gpr_log(GPR_INFO, "POLLABLE:%p[%s] poll for %dms", p,
pollable_desc(p).c_str(), timeout);
- }
-
- if (timeout != 0) {
- GRPC_SCHEDULING_START_BLOCKING_REGION;
- }
- int r;
- do {
- GRPC_STATS_INC_SYSCALL_POLL();
- r = epoll_wait(p->epfd, p->events, MAX_EPOLL_EVENTS, timeout);
- } while (r < 0 && errno == EINTR);
- if (timeout != 0) {
- GRPC_SCHEDULING_END_BLOCKING_REGION;
- }
-
- if (r < 0) return GRPC_OS_ERROR(errno, "epoll_wait");
-
+ }
+
+ if (timeout != 0) {
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
+ }
+ int r;
+ do {
+ GRPC_STATS_INC_SYSCALL_POLL();
+ r = epoll_wait(p->epfd, p->events, MAX_EPOLL_EVENTS, timeout);
+ } while (r < 0 && errno == EINTR);
+ if (timeout != 0) {
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+ }
+
+ if (r < 0) return GRPC_OS_ERROR(errno, "epoll_wait");
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "POLLABLE:%p got %d events", p, r);
- }
-
- p->event_cursor = 0;
- p->event_count = r;
-
- return GRPC_ERROR_NONE;
-}
-
-/* Return true if first in list */
-static bool worker_insert(grpc_pollset_worker** root_worker,
- grpc_pollset_worker* worker, pwlinks link) {
- if (*root_worker == nullptr) {
- *root_worker = worker;
- worker->links[link].next = worker->links[link].prev = worker;
- return true;
- } else {
- worker->links[link].next = *root_worker;
- worker->links[link].prev = worker->links[link].next->links[link].prev;
- worker->links[link].next->links[link].prev = worker;
- worker->links[link].prev->links[link].next = worker;
- return false;
- }
-}
-
-/* returns the new root IFF the root changed */
-typedef enum { WRR_NEW_ROOT, WRR_EMPTIED, WRR_REMOVED } worker_remove_result;
-
-static worker_remove_result worker_remove(grpc_pollset_worker** root_worker,
- grpc_pollset_worker* worker,
- pwlinks link) {
- if (worker == *root_worker) {
- if (worker == worker->links[link].next) {
- *root_worker = nullptr;
- return WRR_EMPTIED;
- } else {
- *root_worker = worker->links[link].next;
- worker->links[link].prev->links[link].next = worker->links[link].next;
- worker->links[link].next->links[link].prev = worker->links[link].prev;
- return WRR_NEW_ROOT;
- }
- } else {
- worker->links[link].prev->links[link].next = worker->links[link].next;
- worker->links[link].next->links[link].prev = worker->links[link].prev;
- return WRR_REMOVED;
- }
-}
-
-/* Return true if this thread should poll */
-static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
- grpc_pollset_worker** worker_hdl,
- grpc_millis deadline) {
- GPR_TIMER_SCOPE("begin_worker", 0);
- bool do_poll =
- (pollset->shutdown_closure == nullptr && !pollset->already_shutdown);
- gpr_atm_no_barrier_fetch_add(&pollset->worker_count, 1);
- if (worker_hdl != nullptr) *worker_hdl = worker;
- worker->initialized_cv = false;
- worker->kicked = false;
- worker->pollset = pollset;
- worker->pollable_obj =
- POLLABLE_REF(pollset->active_pollable, "pollset_worker");
- worker_insert(&pollset->root_worker, worker, PWLINK_POLLSET);
- gpr_mu_lock(&worker->pollable_obj->mu);
- if (!worker_insert(&worker->pollable_obj->root_worker, worker,
- PWLINK_POLLABLE)) {
- worker->initialized_cv = true;
- gpr_cv_init(&worker->cv);
- gpr_mu_unlock(&pollset->mu);
+ gpr_log(GPR_INFO, "POLLABLE:%p got %d events", p, r);
+ }
+
+ p->event_cursor = 0;
+ p->event_count = r;
+
+ return GRPC_ERROR_NONE;
+}
+
+/* Return true if first in list */
+static bool worker_insert(grpc_pollset_worker** root_worker,
+ grpc_pollset_worker* worker, pwlinks link) {
+ if (*root_worker == nullptr) {
+ *root_worker = worker;
+ worker->links[link].next = worker->links[link].prev = worker;
+ return true;
+ } else {
+ worker->links[link].next = *root_worker;
+ worker->links[link].prev = worker->links[link].next->links[link].prev;
+ worker->links[link].next->links[link].prev = worker;
+ worker->links[link].prev->links[link].next = worker;
+ return false;
+ }
+}
+
+/* returns the new root IFF the root changed */
+typedef enum { WRR_NEW_ROOT, WRR_EMPTIED, WRR_REMOVED } worker_remove_result;
+
+static worker_remove_result worker_remove(grpc_pollset_worker** root_worker,
+ grpc_pollset_worker* worker,
+ pwlinks link) {
+ if (worker == *root_worker) {
+ if (worker == worker->links[link].next) {
+ *root_worker = nullptr;
+ return WRR_EMPTIED;
+ } else {
+ *root_worker = worker->links[link].next;
+ worker->links[link].prev->links[link].next = worker->links[link].next;
+ worker->links[link].next->links[link].prev = worker->links[link].prev;
+ return WRR_NEW_ROOT;
+ }
+ } else {
+ worker->links[link].prev->links[link].next = worker->links[link].next;
+ worker->links[link].next->links[link].prev = worker->links[link].prev;
+ return WRR_REMOVED;
+ }
+}
+
+/* Return true if this thread should poll */
+static bool begin_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
+ grpc_pollset_worker** worker_hdl,
+ grpc_millis deadline) {
+ GPR_TIMER_SCOPE("begin_worker", 0);
+ bool do_poll =
+ (pollset->shutdown_closure == nullptr && !pollset->already_shutdown);
+ gpr_atm_no_barrier_fetch_add(&pollset->worker_count, 1);
+ if (worker_hdl != nullptr) *worker_hdl = worker;
+ worker->initialized_cv = false;
+ worker->kicked = false;
+ worker->pollset = pollset;
+ worker->pollable_obj =
+ POLLABLE_REF(pollset->active_pollable, "pollset_worker");
+ worker_insert(&pollset->root_worker, worker, PWLINK_POLLSET);
+ gpr_mu_lock(&worker->pollable_obj->mu);
+ if (!worker_insert(&worker->pollable_obj->root_worker, worker,
+ PWLINK_POLLABLE)) {
+ worker->initialized_cv = true;
+ gpr_cv_init(&worker->cv);
+ gpr_mu_unlock(&pollset->mu);
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,
- poll_deadline_to_millis_timeout(deadline));
- }
- 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))) {
+ worker->pollable_obj->root_worker != worker) {
+ gpr_log(GPR_INFO, "PS:%p wait %p w=%p for %dms", pollset,
+ worker->pollable_obj, worker,
+ poll_deadline_to_millis_timeout(deadline));
+ }
+ 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)) {
- gpr_log(GPR_INFO, "PS:%p timeout_wait %p w=%p", pollset,
- worker->pollable_obj, worker);
- }
- do_poll = false;
- } else if (worker->kicked) {
+ 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)) {
- gpr_log(GPR_INFO, "PS:%p wakeup %p w=%p", pollset,
- worker->pollable_obj, worker);
- }
- do_poll = false;
+ 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) &&
- worker->pollable_obj->root_worker != worker) {
- gpr_log(GPR_INFO, "PS:%p spurious_wakeup %p w=%p", pollset,
- worker->pollable_obj, worker);
- }
- }
- grpc_core::ExecCtx::Get()->InvalidateNow();
- } else {
- gpr_mu_unlock(&pollset->mu);
- }
- gpr_mu_unlock(&worker->pollable_obj->mu);
-
- return do_poll;
-}
-
-static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
+ worker->pollable_obj->root_worker != worker) {
+ gpr_log(GPR_INFO, "PS:%p spurious_wakeup %p w=%p", pollset,
+ worker->pollable_obj, worker);
+ }
+ }
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+ } else {
+ gpr_mu_unlock(&pollset->mu);
+ }
+ gpr_mu_unlock(&worker->pollable_obj->mu);
+
+ return do_poll;
+}
+
+static void end_worker(grpc_pollset* pollset, grpc_pollset_worker* worker,
grpc_pollset_worker** /*worker_hdl*/) {
- GPR_TIMER_SCOPE("end_worker", 0);
- gpr_mu_lock(&pollset->mu);
- gpr_mu_lock(&worker->pollable_obj->mu);
- switch (worker_remove(&worker->pollable_obj->root_worker, worker,
- PWLINK_POLLABLE)) {
- case WRR_NEW_ROOT: {
- // wakeup new poller
- grpc_pollset_worker* new_root = worker->pollable_obj->root_worker;
- GPR_ASSERT(new_root->initialized_cv);
- gpr_cv_signal(&new_root->cv);
- break;
- }
- case WRR_EMPTIED:
- if (pollset->active_pollable != worker->pollable_obj) {
- // pollable no longer being polled: flush events
- pollable_process_events(pollset, worker->pollable_obj, true);
- }
- break;
- case WRR_REMOVED:
- break;
- }
- gpr_mu_unlock(&worker->pollable_obj->mu);
- POLLABLE_UNREF(worker->pollable_obj, "pollset_worker");
- if (worker_remove(&pollset->root_worker, worker, PWLINK_POLLSET) ==
- WRR_EMPTIED) {
- pollset_maybe_finish_shutdown(pollset);
- }
- if (worker->initialized_cv) {
- gpr_cv_destroy(&worker->cv);
- }
- gpr_atm_no_barrier_fetch_add(&pollset->worker_count, -1);
-}
-
-#ifndef NDEBUG
+ GPR_TIMER_SCOPE("end_worker", 0);
+ gpr_mu_lock(&pollset->mu);
+ gpr_mu_lock(&worker->pollable_obj->mu);
+ switch (worker_remove(&worker->pollable_obj->root_worker, worker,
+ PWLINK_POLLABLE)) {
+ case WRR_NEW_ROOT: {
+ // wakeup new poller
+ grpc_pollset_worker* new_root = worker->pollable_obj->root_worker;
+ GPR_ASSERT(new_root->initialized_cv);
+ gpr_cv_signal(&new_root->cv);
+ break;
+ }
+ case WRR_EMPTIED:
+ if (pollset->active_pollable != worker->pollable_obj) {
+ // pollable no longer being polled: flush events
+ pollable_process_events(pollset, worker->pollable_obj, true);
+ }
+ break;
+ case WRR_REMOVED:
+ break;
+ }
+ gpr_mu_unlock(&worker->pollable_obj->mu);
+ POLLABLE_UNREF(worker->pollable_obj, "pollset_worker");
+ if (worker_remove(&pollset->root_worker, worker, PWLINK_POLLSET) ==
+ WRR_EMPTIED) {
+ pollset_maybe_finish_shutdown(pollset);
+ }
+ if (worker->initialized_cv) {
+ gpr_cv_destroy(&worker->cv);
+ }
+ gpr_atm_no_barrier_fetch_add(&pollset->worker_count, -1);
+}
+
+#ifndef NDEBUG
static long sys_gettid(void) { return syscall(__NR_gettid); }
-#endif
-
-/* pollset->mu lock must be held by the caller before calling this.
- The function pollset_work() may temporarily release the lock (pollset->po.mu)
- during the course of its execution but it will always re-acquire the lock and
- ensure that it is held by the time the function returns */
-static grpc_error* pollset_work(grpc_pollset* pollset,
- grpc_pollset_worker** worker_hdl,
- grpc_millis deadline) {
- GPR_TIMER_SCOPE("pollset_work", 0);
-#ifdef GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP
- grpc_pollset_worker* worker =
- (grpc_pollset_worker*)gpr_malloc(sizeof(*worker));
-#define WORKER_PTR (worker)
-#else
- grpc_pollset_worker worker;
-#define WORKER_PTR (&worker)
-#endif
-#ifndef NDEBUG
+#endif
+
+/* pollset->mu lock must be held by the caller before calling this.
+ The function pollset_work() may temporarily release the lock (pollset->po.mu)
+ during the course of its execution but it will always re-acquire the lock and
+ ensure that it is held by the time the function returns */
+static grpc_error* pollset_work(grpc_pollset* pollset,
+ grpc_pollset_worker** worker_hdl,
+ grpc_millis deadline) {
+ GPR_TIMER_SCOPE("pollset_work", 0);
+#ifdef GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP
+ grpc_pollset_worker* worker =
+ (grpc_pollset_worker*)gpr_malloc(sizeof(*worker));
+#define WORKER_PTR (worker)
+#else
+ grpc_pollset_worker worker;
+#define WORKER_PTR (&worker)
+#endif
+#ifndef NDEBUG
WORKER_PTR->originator = sys_gettid();
-#endif
+#endif
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"PS:%p work hdl=%p worker=%p now=%" PRId64 " deadline=%" PRId64
- " kwp=%d pollable=%p",
- pollset, worker_hdl, WORKER_PTR, grpc_core::ExecCtx::Get()->Now(),
- deadline, pollset->kicked_without_poller, pollset->active_pollable);
- }
- static const char* err_desc = "pollset_work";
- grpc_error* error = GRPC_ERROR_NONE;
- if (pollset->kicked_without_poller) {
- pollset->kicked_without_poller = false;
- } else {
- if (begin_worker(pollset, WORKER_PTR, worker_hdl, deadline)) {
- gpr_tls_set(&g_current_thread_pollset, (intptr_t)pollset);
- gpr_tls_set(&g_current_thread_worker, (intptr_t)WORKER_PTR);
- if (WORKER_PTR->pollable_obj->event_cursor ==
- WORKER_PTR->pollable_obj->event_count) {
- append_error(&error, pollable_epoll(WORKER_PTR->pollable_obj, deadline),
- err_desc);
- }
- append_error(
- &error,
- pollable_process_events(pollset, WORKER_PTR->pollable_obj, false),
- err_desc);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_tls_set(&g_current_thread_pollset, 0);
- gpr_tls_set(&g_current_thread_worker, 0);
- }
- end_worker(pollset, WORKER_PTR, worker_hdl);
- }
-#ifdef GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP
- gpr_free(worker);
-#endif
-#undef WORKER_PTR
- return error;
-}
-
-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;
+ " kwp=%d pollable=%p",
+ pollset, worker_hdl, WORKER_PTR, grpc_core::ExecCtx::Get()->Now(),
+ deadline, pollset->kicked_without_poller, pollset->active_pollable);
+ }
+ static const char* err_desc = "pollset_work";
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (pollset->kicked_without_poller) {
+ pollset->kicked_without_poller = false;
+ } else {
+ if (begin_worker(pollset, WORKER_PTR, worker_hdl, deadline)) {
+ gpr_tls_set(&g_current_thread_pollset, (intptr_t)pollset);
+ gpr_tls_set(&g_current_thread_worker, (intptr_t)WORKER_PTR);
+ if (WORKER_PTR->pollable_obj->event_cursor ==
+ WORKER_PTR->pollable_obj->event_count) {
+ append_error(&error, pollable_epoll(WORKER_PTR->pollable_obj, deadline),
+ err_desc);
+ }
+ append_error(
+ &error,
+ pollable_process_events(pollset, WORKER_PTR->pollable_obj, false),
+ err_desc);
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_tls_set(&g_current_thread_pollset, 0);
+ gpr_tls_set(&g_current_thread_worker, 0);
+ }
+ end_worker(pollset, WORKER_PTR, worker_hdl);
+ }
+#ifdef GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP
+ gpr_free(worker);
+#endif
+#undef WORKER_PTR
+ return error;
+}
+
+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)) {
- gpr_log(GPR_INFO,
- "PS:%p add fd %p (%d); transition pollable from empty to fd",
- pollset, fd, fd->fd);
- }
- append_error(&error, pollset_kick_all(pollset), err_desc);
- POLLABLE_UNREF(pollset->active_pollable, "pollset");
+ gpr_log(GPR_INFO,
+ "PS:%p add fd %p (%d); transition pollable from empty to fd",
+ pollset, fd, fd->fd);
+ }
+ append_error(&error, pollset_kick_all(pollset), err_desc);
+ POLLABLE_UNREF(pollset->active_pollable, "pollset");
append_error(&error, get_fd_pollable(fd, &pollset->active_pollable),
- err_desc);
- return error;
-}
-
-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;
+ err_desc);
+ return error;
+}
+
+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)) {
- gpr_log(
- GPR_INFO,
- "PS:%p add fd %p (%d); transition pollable from fd %p to multipoller",
- pollset, and_add_fd, and_add_fd ? and_add_fd->fd : -1,
- pollset->active_pollable->owner_fd);
- }
- append_error(&error, pollset_kick_all(pollset), err_desc);
- grpc_fd* initial_fd = pollset->active_pollable->owner_fd;
- POLLABLE_UNREF(pollset->active_pollable, "pollset");
- pollset->active_pollable = nullptr;
- if (append_error(&error, pollable_create(PO_MULTI, &pollset->active_pollable),
- err_desc)) {
- append_error(&error, pollable_add_fd(pollset->active_pollable, initial_fd),
- err_desc);
- if (and_add_fd != nullptr) {
- append_error(&error,
- pollable_add_fd(pollset->active_pollable, and_add_fd),
- err_desc);
- }
- }
- return error;
-}
-
-/* expects pollsets locked, flag whether fd is locked or not */
-static grpc_error* pollset_add_fd_locked(grpc_pollset* pollset, grpc_fd* fd) {
- grpc_error* error = GRPC_ERROR_NONE;
- pollable* po_at_start =
- POLLABLE_REF(pollset->active_pollable, "pollset_add_fd");
- switch (pollset->active_pollable->type) {
- case PO_EMPTY:
- /* empty pollable --> single fd pollable */
- error = pollset_transition_pollable_from_empty_to_fd_locked(pollset, fd);
- break;
- case PO_FD:
+ gpr_log(
+ GPR_INFO,
+ "PS:%p add fd %p (%d); transition pollable from fd %p to multipoller",
+ pollset, and_add_fd, and_add_fd ? and_add_fd->fd : -1,
+ pollset->active_pollable->owner_fd);
+ }
+ append_error(&error, pollset_kick_all(pollset), err_desc);
+ grpc_fd* initial_fd = pollset->active_pollable->owner_fd;
+ POLLABLE_UNREF(pollset->active_pollable, "pollset");
+ pollset->active_pollable = nullptr;
+ if (append_error(&error, pollable_create(PO_MULTI, &pollset->active_pollable),
+ err_desc)) {
+ append_error(&error, pollable_add_fd(pollset->active_pollable, initial_fd),
+ err_desc);
+ if (and_add_fd != nullptr) {
+ append_error(&error,
+ pollable_add_fd(pollset->active_pollable, and_add_fd),
+ err_desc);
+ }
+ }
+ return error;
+}
+
+/* expects pollsets locked, flag whether fd is locked or not */
+static grpc_error* pollset_add_fd_locked(grpc_pollset* pollset, grpc_fd* fd) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ pollable* po_at_start =
+ POLLABLE_REF(pollset->active_pollable, "pollset_add_fd");
+ switch (pollset->active_pollable->type) {
+ case PO_EMPTY:
+ /* empty pollable --> single fd pollable */
+ error = pollset_transition_pollable_from_empty_to_fd_locked(pollset, fd);
+ break;
+ case PO_FD:
gpr_mu_lock(&po_at_start->owner_orphan_mu);
if (po_at_start->owner_orphaned) {
- error =
- pollset_transition_pollable_from_empty_to_fd_locked(pollset, fd);
- } else {
- /* fd --> multipoller */
- error =
- pollset_transition_pollable_from_fd_to_multi_locked(pollset, fd);
- }
+ error =
+ pollset_transition_pollable_from_empty_to_fd_locked(pollset, fd);
+ } else {
+ /* fd --> multipoller */
+ error =
+ pollset_transition_pollable_from_fd_to_multi_locked(pollset, fd);
+ }
gpr_mu_unlock(&po_at_start->owner_orphan_mu);
- break;
- case PO_MULTI:
- error = pollable_add_fd(pollset->active_pollable, fd);
- break;
- }
- if (error != GRPC_ERROR_NONE) {
- POLLABLE_UNREF(pollset->active_pollable, "pollset");
- pollset->active_pollable = po_at_start;
- } else {
+ break;
+ case PO_MULTI:
+ error = pollable_add_fd(pollset->active_pollable, fd);
+ break;
+ }
+ if (error != GRPC_ERROR_NONE) {
+ POLLABLE_UNREF(pollset->active_pollable, "pollset");
+ pollset->active_pollable = po_at_start;
+ } else {
gpr_atm_rel_store(&pollset->active_pollable_type,
pollset->active_pollable->type);
- POLLABLE_UNREF(po_at_start, "pollset_add_fd");
- }
- return error;
-}
-
-static grpc_error* pollset_as_multipollable_locked(grpc_pollset* pollset,
- pollable** pollable_obj) {
- grpc_error* error = GRPC_ERROR_NONE;
- pollable* po_at_start =
- POLLABLE_REF(pollset->active_pollable, "pollset_as_multipollable");
- switch (pollset->active_pollable->type) {
- case PO_EMPTY:
- POLLABLE_UNREF(pollset->active_pollable, "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 */
+ POLLABLE_UNREF(po_at_start, "pollset_add_fd");
+ }
+ return error;
+}
+
+static grpc_error* pollset_as_multipollable_locked(grpc_pollset* pollset,
+ pollable** pollable_obj) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ pollable* po_at_start =
+ POLLABLE_REF(pollset->active_pollable, "pollset_as_multipollable");
+ switch (pollset->active_pollable->type) {
+ case PO_EMPTY:
+ POLLABLE_UNREF(pollset->active_pollable, "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)) {
- gpr_log(GPR_INFO,
- "PS:%p active pollable transition from empty to multi",
- pollset);
- }
- static const char* err_desc =
- "pollset_as_multipollable_locked: empty -> multi";
- append_error(&error, pollset_kick_all(pollset), err_desc);
- break;
- case PO_FD:
+ gpr_log(GPR_INFO,
+ "PS:%p active pollable transition from empty to multi",
+ pollset);
+ }
+ static const char* err_desc =
+ "pollset_as_multipollable_locked: empty -> multi";
+ append_error(&error, pollset_kick_all(pollset), err_desc);
+ break;
+ case PO_FD:
gpr_mu_lock(&po_at_start->owner_orphan_mu);
if (po_at_start->owner_orphaned) {
// Unlock before Unref'ing the pollable
gpr_mu_unlock(&po_at_start->owner_orphan_mu);
- POLLABLE_UNREF(pollset->active_pollable, "pollset");
- error = pollable_create(PO_MULTI, &pollset->active_pollable);
- } else {
- error = pollset_transition_pollable_from_fd_to_multi_locked(pollset,
- nullptr);
+ POLLABLE_UNREF(pollset->active_pollable, "pollset");
+ error = pollable_create(PO_MULTI, &pollset->active_pollable);
+ } else {
+ error = pollset_transition_pollable_from_fd_to_multi_locked(pollset,
+ nullptr);
gpr_mu_unlock(&po_at_start->owner_orphan_mu);
- }
- break;
- case PO_MULTI:
- break;
- }
- if (error != GRPC_ERROR_NONE) {
- POLLABLE_UNREF(pollset->active_pollable, "pollset");
- pollset->active_pollable = po_at_start;
- *pollable_obj = nullptr;
- } else {
+ }
+ break;
+ case PO_MULTI:
+ break;
+ }
+ if (error != GRPC_ERROR_NONE) {
+ POLLABLE_UNREF(pollset->active_pollable, "pollset");
+ pollset->active_pollable = po_at_start;
+ *pollable_obj = nullptr;
+ } else {
gpr_atm_rel_store(&pollset->active_pollable_type,
pollset->active_pollable->type);
- *pollable_obj = POLLABLE_REF(pollset->active_pollable, "pollset_set");
- POLLABLE_UNREF(po_at_start, "pollset_as_multipollable");
- }
- return error;
-}
-
-static void pollset_add_fd(grpc_pollset* pollset, grpc_fd* fd) {
- GPR_TIMER_SCOPE("pollset_add_fd", 0);
+ *pollable_obj = POLLABLE_REF(pollset->active_pollable, "pollset_set");
+ POLLABLE_UNREF(po_at_start, "pollset_as_multipollable");
+ }
+ return error;
+}
+
+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)
// and, thus, it is safe to simply store and check whether the FD has already
@@ -1289,277 +1289,277 @@ static void pollset_add_fd(grpc_pollset* pollset, grpc_fd* fd) {
}
grpc_core::MutexLock lock(&pollset->mu);
- grpc_error* error = pollset_add_fd_locked(pollset, fd);
+ grpc_error* error = pollset_add_fd_locked(pollset, fd);
// If we are in PO_MULTI mode, we should update the pollsets of the FD.
if (gpr_atm_no_barrier_load(&pollset->active_pollable_type) == PO_MULTI) {
fd_add_pollset(fd, pollset);
}
- GRPC_LOG_IF_ERROR("pollset_add_fd", error);
-}
-
-/*******************************************************************************
- * Pollset-set Definitions
- */
-
-static grpc_pollset_set* pss_lock_adam(grpc_pollset_set* pss) {
- gpr_mu_lock(&pss->mu);
- while (pss->parent != nullptr) {
- gpr_mu_unlock(&pss->mu);
- pss = pss->parent;
- gpr_mu_lock(&pss->mu);
- }
- return pss;
-}
-
-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);
+ GRPC_LOG_IF_ERROR("pollset_add_fd", error);
+}
+
+/*******************************************************************************
+ * Pollset-set Definitions
+ */
+
+static grpc_pollset_set* pss_lock_adam(grpc_pollset_set* pss) {
+ gpr_mu_lock(&pss->mu);
+ while (pss->parent != nullptr) {
+ gpr_mu_unlock(&pss->mu);
+ pss = pss->parent;
+ gpr_mu_lock(&pss->mu);
+ }
+ return pss;
+}
+
+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();
- return pss;
-}
-
-static void pollset_set_unref(grpc_pollset_set* pss) {
- if (pss == nullptr) return;
+ return pss;
+}
+
+static void pollset_set_unref(grpc_pollset_set* pss) {
+ if (pss == nullptr) 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++) {
- gpr_mu_lock(&pss->pollsets[i]->mu);
- if (0 == --pss->pollsets[i]->containing_pollset_set_count) {
- pollset_maybe_finish_shutdown(pss->pollsets[i]);
- }
- gpr_mu_unlock(&pss->pollsets[i]->mu);
- }
- for (size_t i = 0; i < pss->fd_count; i++) {
- UNREF_BY(pss->fds[i], 2, "pollset_set");
- }
- gpr_free(pss->pollsets);
- gpr_free(pss->fds);
- gpr_free(pss);
-}
-
-static void pollset_set_add_fd(grpc_pollset_set* pss, grpc_fd* fd) {
- GPR_TIMER_SCOPE("pollset_set_add_fd", 0);
+ pollset_set_unref(pss->parent);
+ gpr_mu_destroy(&pss->mu);
+ for (size_t i = 0; i < pss->pollset_count; i++) {
+ gpr_mu_lock(&pss->pollsets[i]->mu);
+ if (0 == --pss->pollsets[i]->containing_pollset_set_count) {
+ pollset_maybe_finish_shutdown(pss->pollsets[i]);
+ }
+ gpr_mu_unlock(&pss->pollsets[i]->mu);
+ }
+ for (size_t i = 0; i < pss->fd_count; i++) {
+ UNREF_BY(pss->fds[i], 2, "pollset_set");
+ }
+ gpr_free(pss->pollsets);
+ gpr_free(pss->fds);
+ gpr_free(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)) {
- gpr_log(GPR_INFO, "PSS:%p: add fd %p (%d)", pss, fd, fd->fd);
- }
- grpc_error* error = GRPC_ERROR_NONE;
- static const char* err_desc = "pollset_set_add_fd";
- pss = pss_lock_adam(pss);
- for (size_t i = 0; i < pss->pollset_count; i++) {
- append_error(&error, pollable_add_fd(pss->pollsets[i]->active_pollable, fd),
- err_desc);
- }
- if (pss->fd_count == pss->fd_capacity) {
- pss->fd_capacity = GPR_MAX(pss->fd_capacity * 2, 8);
- pss->fds = static_cast<grpc_fd**>(
- gpr_realloc(pss->fds, pss->fd_capacity * sizeof(*pss->fds)));
- }
- REF_BY(fd, 2, "pollset_set");
- pss->fds[pss->fd_count++] = fd;
- gpr_mu_unlock(&pss->mu);
-
- GRPC_LOG_IF_ERROR(err_desc, error);
-}
-
-static void pollset_set_del_fd(grpc_pollset_set* pss, grpc_fd* fd) {
- GPR_TIMER_SCOPE("pollset_set_del_fd", 0);
+ gpr_log(GPR_INFO, "PSS:%p: add fd %p (%d)", pss, fd, fd->fd);
+ }
+ grpc_error* error = GRPC_ERROR_NONE;
+ static const char* err_desc = "pollset_set_add_fd";
+ pss = pss_lock_adam(pss);
+ for (size_t i = 0; i < pss->pollset_count; i++) {
+ append_error(&error, pollable_add_fd(pss->pollsets[i]->active_pollable, fd),
+ err_desc);
+ }
+ if (pss->fd_count == pss->fd_capacity) {
+ pss->fd_capacity = GPR_MAX(pss->fd_capacity * 2, 8);
+ pss->fds = static_cast<grpc_fd**>(
+ gpr_realloc(pss->fds, pss->fd_capacity * sizeof(*pss->fds)));
+ }
+ REF_BY(fd, 2, "pollset_set");
+ pss->fds[pss->fd_count++] = fd;
+ gpr_mu_unlock(&pss->mu);
+
+ GRPC_LOG_IF_ERROR(err_desc, error);
+}
+
+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)) {
- gpr_log(GPR_INFO, "PSS:%p: del fd %p", pss, fd);
- }
- pss = pss_lock_adam(pss);
- size_t i;
- for (i = 0; i < pss->fd_count; i++) {
- if (pss->fds[i] == fd) {
- UNREF_BY(fd, 2, "pollset_set");
- break;
- }
- }
- GPR_ASSERT(i != pss->fd_count);
- for (; i < pss->fd_count - 1; i++) {
- pss->fds[i] = pss->fds[i + 1];
- }
- pss->fd_count--;
- gpr_mu_unlock(&pss->mu);
-}
-
-static void pollset_set_del_pollset(grpc_pollset_set* pss, grpc_pollset* ps) {
- GPR_TIMER_SCOPE("pollset_set_del_pollset", 0);
+ gpr_log(GPR_INFO, "PSS:%p: del fd %p", pss, fd);
+ }
+ pss = pss_lock_adam(pss);
+ size_t i;
+ for (i = 0; i < pss->fd_count; i++) {
+ if (pss->fds[i] == fd) {
+ UNREF_BY(fd, 2, "pollset_set");
+ break;
+ }
+ }
+ GPR_ASSERT(i != pss->fd_count);
+ for (; i < pss->fd_count - 1; i++) {
+ pss->fds[i] = pss->fds[i + 1];
+ }
+ pss->fd_count--;
+ gpr_mu_unlock(&pss->mu);
+}
+
+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)) {
- gpr_log(GPR_INFO, "PSS:%p: del pollset %p", pss, ps);
- }
- pss = pss_lock_adam(pss);
- size_t i;
- for (i = 0; i < pss->pollset_count; i++) {
- if (pss->pollsets[i] == ps) {
- break;
- }
- }
- GPR_ASSERT(i != pss->pollset_count);
- for (; i < pss->pollset_count - 1; i++) {
- pss->pollsets[i] = pss->pollsets[i + 1];
- }
- pss->pollset_count--;
- gpr_mu_unlock(&pss->mu);
- gpr_mu_lock(&ps->mu);
- if (0 == --ps->containing_pollset_set_count) {
- pollset_maybe_finish_shutdown(ps);
- }
- gpr_mu_unlock(&ps->mu);
-}
-
-// add all fds to pollables, and output a new array of unorphaned out_fds
-// assumes pollsets are multipollable
-static grpc_error* add_fds_to_pollsets(grpc_fd** fds, size_t fd_count,
- grpc_pollset** pollsets,
- size_t pollset_count,
- const char* err_desc, grpc_fd** out_fds,
- size_t* out_fd_count) {
- GPR_TIMER_SCOPE("add_fds_to_pollsets", 0);
- grpc_error* error = GRPC_ERROR_NONE;
- for (size_t i = 0; i < fd_count; i++) {
- gpr_mu_lock(&fds[i]->orphan_mu);
- if ((gpr_atm_no_barrier_load(&fds[i]->refst) & 1) == 0) {
- gpr_mu_unlock(&fds[i]->orphan_mu);
- UNREF_BY(fds[i], 2, "pollset_set");
- } else {
- for (size_t j = 0; j < pollset_count; j++) {
- append_error(&error,
- pollable_add_fd(pollsets[j]->active_pollable, fds[i]),
- err_desc);
- }
- gpr_mu_unlock(&fds[i]->orphan_mu);
- out_fds[(*out_fd_count)++] = fds[i];
- }
- }
- return error;
-}
-
-static void pollset_set_add_pollset(grpc_pollset_set* pss, grpc_pollset* ps) {
- GPR_TIMER_SCOPE("pollset_set_add_pollset", 0);
+ gpr_log(GPR_INFO, "PSS:%p: del pollset %p", pss, ps);
+ }
+ pss = pss_lock_adam(pss);
+ size_t i;
+ for (i = 0; i < pss->pollset_count; i++) {
+ if (pss->pollsets[i] == ps) {
+ break;
+ }
+ }
+ GPR_ASSERT(i != pss->pollset_count);
+ for (; i < pss->pollset_count - 1; i++) {
+ pss->pollsets[i] = pss->pollsets[i + 1];
+ }
+ pss->pollset_count--;
+ gpr_mu_unlock(&pss->mu);
+ gpr_mu_lock(&ps->mu);
+ if (0 == --ps->containing_pollset_set_count) {
+ pollset_maybe_finish_shutdown(ps);
+ }
+ gpr_mu_unlock(&ps->mu);
+}
+
+// add all fds to pollables, and output a new array of unorphaned out_fds
+// assumes pollsets are multipollable
+static grpc_error* add_fds_to_pollsets(grpc_fd** fds, size_t fd_count,
+ grpc_pollset** pollsets,
+ size_t pollset_count,
+ const char* err_desc, grpc_fd** out_fds,
+ size_t* out_fd_count) {
+ GPR_TIMER_SCOPE("add_fds_to_pollsets", 0);
+ grpc_error* error = GRPC_ERROR_NONE;
+ for (size_t i = 0; i < fd_count; i++) {
+ gpr_mu_lock(&fds[i]->orphan_mu);
+ if ((gpr_atm_no_barrier_load(&fds[i]->refst) & 1) == 0) {
+ gpr_mu_unlock(&fds[i]->orphan_mu);
+ UNREF_BY(fds[i], 2, "pollset_set");
+ } else {
+ for (size_t j = 0; j < pollset_count; j++) {
+ append_error(&error,
+ pollable_add_fd(pollsets[j]->active_pollable, fds[i]),
+ err_desc);
+ }
+ gpr_mu_unlock(&fds[i]->orphan_mu);
+ out_fds[(*out_fd_count)++] = fds[i];
+ }
+ }
+ return error;
+}
+
+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)) {
- gpr_log(GPR_INFO, "PSS:%p: add pollset %p", pss, ps);
- }
- grpc_error* error = GRPC_ERROR_NONE;
- static const char* err_desc = "pollset_set_add_pollset";
- pollable* pollable_obj = nullptr;
- gpr_mu_lock(&ps->mu);
- if (!GRPC_LOG_IF_ERROR(err_desc,
- pollset_as_multipollable_locked(ps, &pollable_obj))) {
- GPR_ASSERT(pollable_obj == nullptr);
- gpr_mu_unlock(&ps->mu);
- return;
- }
- ps->containing_pollset_set_count++;
- gpr_mu_unlock(&ps->mu);
- pss = pss_lock_adam(pss);
- size_t initial_fd_count = pss->fd_count;
- pss->fd_count = 0;
- append_error(&error,
- add_fds_to_pollsets(pss->fds, initial_fd_count, &ps, 1, err_desc,
- pss->fds, &pss->fd_count),
- err_desc);
- if (pss->pollset_count == pss->pollset_capacity) {
- pss->pollset_capacity = GPR_MAX(pss->pollset_capacity * 2, 8);
- pss->pollsets = static_cast<grpc_pollset**>(gpr_realloc(
- pss->pollsets, pss->pollset_capacity * sizeof(*pss->pollsets)));
- }
- pss->pollsets[pss->pollset_count++] = ps;
- gpr_mu_unlock(&pss->mu);
- POLLABLE_UNREF(pollable_obj, "pollset_set");
-
- GRPC_LOG_IF_ERROR(err_desc, error);
-}
-
-static void pollset_set_add_pollset_set(grpc_pollset_set* a,
- grpc_pollset_set* b) {
- GPR_TIMER_SCOPE("pollset_set_add_pollset_set", 0);
+ gpr_log(GPR_INFO, "PSS:%p: add pollset %p", pss, ps);
+ }
+ grpc_error* error = GRPC_ERROR_NONE;
+ static const char* err_desc = "pollset_set_add_pollset";
+ pollable* pollable_obj = nullptr;
+ gpr_mu_lock(&ps->mu);
+ if (!GRPC_LOG_IF_ERROR(err_desc,
+ pollset_as_multipollable_locked(ps, &pollable_obj))) {
+ GPR_ASSERT(pollable_obj == nullptr);
+ gpr_mu_unlock(&ps->mu);
+ return;
+ }
+ ps->containing_pollset_set_count++;
+ gpr_mu_unlock(&ps->mu);
+ pss = pss_lock_adam(pss);
+ size_t initial_fd_count = pss->fd_count;
+ pss->fd_count = 0;
+ append_error(&error,
+ add_fds_to_pollsets(pss->fds, initial_fd_count, &ps, 1, err_desc,
+ pss->fds, &pss->fd_count),
+ err_desc);
+ if (pss->pollset_count == pss->pollset_capacity) {
+ pss->pollset_capacity = GPR_MAX(pss->pollset_capacity * 2, 8);
+ pss->pollsets = static_cast<grpc_pollset**>(gpr_realloc(
+ pss->pollsets, pss->pollset_capacity * sizeof(*pss->pollsets)));
+ }
+ pss->pollsets[pss->pollset_count++] = ps;
+ gpr_mu_unlock(&pss->mu);
+ POLLABLE_UNREF(pollable_obj, "pollset_set");
+
+ GRPC_LOG_IF_ERROR(err_desc, error);
+}
+
+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)) {
- gpr_log(GPR_INFO, "PSS: merge (%p, %p)", a, b);
- }
- grpc_error* error = GRPC_ERROR_NONE;
- static const char* err_desc = "pollset_set_add_fd";
- for (;;) {
- if (a == b) {
- // pollset ancestors are the same: nothing to do
- return;
- }
- if (a > b) {
- GPR_SWAP(grpc_pollset_set*, a, b);
- }
- gpr_mu* a_mu = &a->mu;
- gpr_mu* b_mu = &b->mu;
- gpr_mu_lock(a_mu);
- gpr_mu_lock(b_mu);
- if (a->parent != nullptr) {
- a = a->parent;
- } else if (b->parent != nullptr) {
- b = b->parent;
- } else {
- break; // exit loop, both pollsets locked
- }
- gpr_mu_unlock(a_mu);
- gpr_mu_unlock(b_mu);
- }
- // try to do the least copying possible
+ gpr_log(GPR_INFO, "PSS: merge (%p, %p)", a, b);
+ }
+ grpc_error* error = GRPC_ERROR_NONE;
+ static const char* err_desc = "pollset_set_add_fd";
+ for (;;) {
+ if (a == b) {
+ // pollset ancestors are the same: nothing to do
+ return;
+ }
+ if (a > b) {
+ GPR_SWAP(grpc_pollset_set*, a, b);
+ }
+ gpr_mu* a_mu = &a->mu;
+ gpr_mu* b_mu = &b->mu;
+ gpr_mu_lock(a_mu);
+ gpr_mu_lock(b_mu);
+ if (a->parent != nullptr) {
+ a = a->parent;
+ } else if (b->parent != nullptr) {
+ b = b->parent;
+ } else {
+ break; // exit loop, both pollsets locked
+ }
+ gpr_mu_unlock(a_mu);
+ gpr_mu_unlock(b_mu);
+ }
+ // try to do the least copying possible
// TODO(sreek): there's probably a better heuristic here
- const size_t a_size = a->fd_count + a->pollset_count;
- const size_t b_size = b->fd_count + b->pollset_count;
- if (b_size > a_size) {
- GPR_SWAP(grpc_pollset_set*, a, b);
- }
+ const size_t a_size = a->fd_count + a->pollset_count;
+ const size_t b_size = b->fd_count + b->pollset_count;
+ if (b_size > a_size) {
+ GPR_SWAP(grpc_pollset_set*, a, b);
+ }
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "PSS: parent %p to %p", b, a);
- }
+ gpr_log(GPR_INFO, "PSS: parent %p to %p", b, a);
+ }
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);
- a->fds = static_cast<grpc_fd**>(
- gpr_realloc(a->fds, a->fd_capacity * sizeof(*a->fds)));
- }
- size_t initial_a_fd_count = a->fd_count;
- a->fd_count = 0;
- append_error(
- &error,
- add_fds_to_pollsets(a->fds, initial_a_fd_count, b->pollsets,
- b->pollset_count, "merge_a2b", a->fds, &a->fd_count),
- err_desc);
- append_error(
- &error,
- add_fds_to_pollsets(b->fds, b->fd_count, a->pollsets, a->pollset_count,
- "merge_b2a", a->fds, &a->fd_count),
- err_desc);
- if (a->pollset_capacity < a->pollset_count + b->pollset_count) {
- a->pollset_capacity =
- GPR_MAX(2 * a->pollset_capacity, a->pollset_count + b->pollset_count);
- a->pollsets = static_cast<grpc_pollset**>(
- gpr_realloc(a->pollsets, a->pollset_capacity * sizeof(*a->pollsets)));
- }
- if (b->pollset_count > 0) {
- memcpy(a->pollsets + a->pollset_count, b->pollsets,
- b->pollset_count * sizeof(*b->pollsets));
- }
- a->pollset_count += b->pollset_count;
- gpr_free(b->fds);
- gpr_free(b->pollsets);
- b->fds = nullptr;
- b->pollsets = nullptr;
- b->fd_count = b->fd_capacity = b->pollset_count = b->pollset_capacity = 0;
- gpr_mu_unlock(&a->mu);
- gpr_mu_unlock(&b->mu);
-}
-
+ 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);
+ a->fds = static_cast<grpc_fd**>(
+ gpr_realloc(a->fds, a->fd_capacity * sizeof(*a->fds)));
+ }
+ size_t initial_a_fd_count = a->fd_count;
+ a->fd_count = 0;
+ append_error(
+ &error,
+ add_fds_to_pollsets(a->fds, initial_a_fd_count, b->pollsets,
+ b->pollset_count, "merge_a2b", a->fds, &a->fd_count),
+ err_desc);
+ append_error(
+ &error,
+ add_fds_to_pollsets(b->fds, b->fd_count, a->pollsets, a->pollset_count,
+ "merge_b2a", a->fds, &a->fd_count),
+ err_desc);
+ if (a->pollset_capacity < a->pollset_count + b->pollset_count) {
+ a->pollset_capacity =
+ GPR_MAX(2 * a->pollset_capacity, a->pollset_count + b->pollset_count);
+ a->pollsets = static_cast<grpc_pollset**>(
+ gpr_realloc(a->pollsets, a->pollset_capacity * sizeof(*a->pollsets)));
+ }
+ if (b->pollset_count > 0) {
+ memcpy(a->pollsets + a->pollset_count, b->pollsets,
+ b->pollset_count * sizeof(*b->pollsets));
+ }
+ a->pollset_count += b->pollset_count;
+ gpr_free(b->fds);
+ gpr_free(b->pollsets);
+ b->fds = nullptr;
+ b->pollsets = nullptr;
+ b->fd_count = b->fd_capacity = b->pollset_count = b->pollset_capacity = 0;
+ gpr_mu_unlock(&a->mu);
+ gpr_mu_unlock(&b->mu);
+}
+
static void pollset_set_del_pollset_set(grpc_pollset_set* /*bag*/,
grpc_pollset_set* /*item*/) {}
-
-/*******************************************************************************
- * Event engine binding
- */
-
+
+/*******************************************************************************
+ * Event engine binding
+ */
+
static bool is_any_background_poller_thread(void) { return false; }
static void shutdown_background_closure(void) {}
@@ -1569,82 +1569,82 @@ static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
return false;
}
-static void shutdown_engine(void) {
- fd_global_shutdown();
- pollset_global_shutdown();
-}
-
-static const grpc_event_engine_vtable vtable = {
- sizeof(grpc_pollset),
+static void shutdown_engine(void) {
+ fd_global_shutdown();
+ pollset_global_shutdown();
+}
+
+static const grpc_event_engine_vtable vtable = {
+ sizeof(grpc_pollset),
true,
false,
-
- fd_create,
- fd_wrapped_fd,
- fd_orphan,
- fd_shutdown,
- fd_notify_on_read,
- fd_notify_on_write,
+
+ fd_create,
+ fd_wrapped_fd,
+ fd_orphan,
+ fd_shutdown,
+ fd_notify_on_read,
+ fd_notify_on_write,
fd_notify_on_error,
fd_become_readable,
fd_become_writable,
fd_has_errors,
- fd_is_shutdown,
-
- pollset_init,
- pollset_shutdown,
- pollset_destroy,
- pollset_work,
- pollset_kick,
- pollset_add_fd,
-
- pollset_set_create,
- pollset_set_unref, // destroy ==> unref 1 public ref
- pollset_set_add_pollset,
- pollset_set_del_pollset,
- pollset_set_add_pollset_set,
- pollset_set_del_pollset_set,
- pollset_set_add_fd,
- pollset_set_del_fd,
-
+ fd_is_shutdown,
+
+ pollset_init,
+ pollset_shutdown,
+ pollset_destroy,
+ pollset_work,
+ pollset_kick,
+ pollset_add_fd,
+
+ pollset_set_create,
+ pollset_set_unref, // destroy ==> unref 1 public ref
+ pollset_set_add_pollset,
+ pollset_set_del_pollset,
+ pollset_set_add_pollset_set,
+ pollset_set_del_pollset_set,
+ pollset_set_add_fd,
+ pollset_set_del_fd,
+
is_any_background_poller_thread,
shutdown_background_closure,
- shutdown_engine,
+ shutdown_engine,
add_closure_to_background_poller,
-};
-
-const grpc_event_engine_vtable* grpc_init_epollex_linux(
+};
+
+const grpc_event_engine_vtable* grpc_init_epollex_linux(
bool /*explicitly_requested*/) {
- if (!grpc_has_wakeup_fd()) {
- gpr_log(GPR_ERROR, "Skipping epollex because of no wakeup fd.");
- return nullptr;
- }
-
- if (!grpc_is_epollexclusive_available()) {
- gpr_log(GPR_INFO, "Skipping epollex because it is not supported.");
- return nullptr;
- }
-
- fd_global_init();
-
- if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
- pollset_global_shutdown();
- fd_global_shutdown();
- return nullptr;
- }
-
- return &vtable;
-}
-
-#else /* defined(GRPC_LINUX_EPOLL_CREATE1) */
+ if (!grpc_has_wakeup_fd()) {
+ gpr_log(GPR_ERROR, "Skipping epollex because of no wakeup fd.");
+ return nullptr;
+ }
+
+ if (!grpc_is_epollexclusive_available()) {
+ gpr_log(GPR_INFO, "Skipping epollex because it is not supported.");
+ return nullptr;
+ }
+
+ fd_global_init();
+
+ if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
+ pollset_global_shutdown();
+ fd_global_shutdown();
+ return nullptr;
+ }
+
+ return &vtable;
+}
+
+#else /* defined(GRPC_LINUX_EPOLL_CREATE1) */
#if defined(GRPC_POSIX_SOCKET_EV_EPOLLEX)
-#include "src/core/lib/iomgr/ev_epollex_linux.h"
-/* 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(
+#include "src/core/lib/iomgr/ev_epollex_linux.h"
+/* 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*/) {
- return nullptr;
-}
+ return nullptr;
+}
#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLLEX) */
-
-#endif /* !defined(GRPC_LINUX_EPOLL_CREATE1) */
+
+#endif /* !defined(GRPC_LINUX_EPOLL_CREATE1) */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.h b/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.h
index e70ba72a7db..8e424285f9c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.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_CORE_LIB_IOMGR_EV_EPOLLEX_LINUX_H
-#define GRPC_CORE_LIB_IOMGR_EV_EPOLLEX_LINUX_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/port.h"
-
-const grpc_event_engine_vtable* grpc_init_epollex_linux(
- bool explicitly_requested);
-
-#endif /* GRPC_CORE_LIB_IOMGR_EV_EPOLLEX_LINUX_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_IOMGR_EV_EPOLLEX_LINUX_H
+#define GRPC_CORE_LIB_IOMGR_EV_EPOLLEX_LINUX_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/port.h"
+
+const grpc_event_engine_vtable* grpc_init_epollex_linux(
+ bool explicitly_requested);
+
+#endif /* GRPC_CORE_LIB_IOMGR_EV_EPOLLEX_LINUX_H */
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 a46ab7ea0dd..d6c6266eeca 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
@@ -1,67 +1,67 @@
-/*
- *
- * 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"
-
+/*
+ *
+ * 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"
+
#ifdef GRPC_POSIX_SOCKET_EV_POLL
-
-#include "src/core/lib/iomgr/ev_poll_posix.h"
-
-#include <assert.h>
-#include <errno.h>
-#include <limits.h>
-#include <poll.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
+
+#include "src/core/lib/iomgr/ev_poll_posix.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <poll.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gpr/murmur_hash.h"
-#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/thd.h"
-#include "src/core/lib/iomgr/block_annotate.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-#include "src/core/lib/profiling/timers.h"
-
-#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker*)1)
-
-/*******************************************************************************
- * FD declarations
- */
-typedef struct grpc_fd_watcher {
- struct grpc_fd_watcher* next;
- struct grpc_fd_watcher* prev;
- grpc_pollset* pollset;
- grpc_pollset_worker* worker;
- grpc_fd* fd;
-} grpc_fd_watcher;
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gpr/murmur_hash.h"
+#include "src/core/lib/gpr/tls.h"
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/block_annotate.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+#include "src/core/lib/profiling/timers.h"
+
+#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker*)1)
+
+/*******************************************************************************
+ * FD declarations
+ */
+typedef struct grpc_fd_watcher {
+ struct grpc_fd_watcher* next;
+ struct grpc_fd_watcher* prev;
+ grpc_pollset* pollset;
+ grpc_pollset_worker* worker;
+ grpc_fd* fd;
+} grpc_fd_watcher;
+
typedef struct grpc_cached_wakeup_fd grpc_cached_wakeup_fd;
/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */
@@ -75,59 +75,59 @@ struct grpc_fork_fd_list {
grpc_fork_fd_list* prev;
};
-struct grpc_fd {
- int fd;
- /* refst format:
- bit0: 1=active/0=orphaned
- bit1-n: refcount
- meaning that mostly we ref by two to avoid altering the orphaned bit,
- and just unref by 1 when we're ready to flag the object as orphaned */
- gpr_atm refst;
-
- gpr_mu mu;
- int shutdown;
- int closed;
- int released;
- gpr_atm pollhup;
- grpc_error* shutdown_error;
-
- /* The watcher list.
-
- The following watcher related fields are protected by watcher_mu.
-
- An fd_watcher is an ephemeral object created when an fd wants to
- begin polling, and destroyed after the poll.
-
- It denotes the fd's interest in whether to read poll or write poll
- or both or neither on this fd.
-
- If a watcher is asked to poll for reads or writes, the read_watcher
- or write_watcher fields are set respectively. A watcher may be asked
- to poll for both, in which case both fields will be set.
-
- read_watcher and write_watcher may be NULL if no watcher has been
- asked to poll for reads or writes.
-
- If an fd_watcher is not asked to poll for reads or writes, it's added
- to a linked list of inactive watchers, rooted at inactive_watcher_root.
- If at a later time there becomes need of a poller to poll, one of
- the inactive pollers may be kicked out of their poll loops to take
- that responsibility. */
- grpc_fd_watcher inactive_watcher_root;
- grpc_fd_watcher* read_watcher;
- grpc_fd_watcher* write_watcher;
-
- grpc_closure* read_closure;
- grpc_closure* write_closure;
-
- grpc_closure* on_done_closure;
-
- grpc_iomgr_object iomgr_object;
-
+struct grpc_fd {
+ int fd;
+ /* refst format:
+ bit0: 1=active/0=orphaned
+ bit1-n: refcount
+ meaning that mostly we ref by two to avoid altering the orphaned bit,
+ and just unref by 1 when we're ready to flag the object as orphaned */
+ gpr_atm refst;
+
+ gpr_mu mu;
+ int shutdown;
+ int closed;
+ int released;
+ gpr_atm pollhup;
+ grpc_error* shutdown_error;
+
+ /* The watcher list.
+
+ The following watcher related fields are protected by watcher_mu.
+
+ An fd_watcher is an ephemeral object created when an fd wants to
+ begin polling, and destroyed after the poll.
+
+ It denotes the fd's interest in whether to read poll or write poll
+ or both or neither on this fd.
+
+ If a watcher is asked to poll for reads or writes, the read_watcher
+ or write_watcher fields are set respectively. A watcher may be asked
+ to poll for both, in which case both fields will be set.
+
+ read_watcher and write_watcher may be NULL if no watcher has been
+ asked to poll for reads or writes.
+
+ If an fd_watcher is not asked to poll for reads or writes, it's added
+ to a linked list of inactive watchers, rooted at inactive_watcher_root.
+ If at a later time there becomes need of a poller to poll, one of
+ the inactive pollers may be kicked out of their poll loops to take
+ that responsibility. */
+ grpc_fd_watcher inactive_watcher_root;
+ grpc_fd_watcher* read_watcher;
+ grpc_fd_watcher* write_watcher;
+
+ grpc_closure* read_closure;
+ grpc_closure* write_closure;
+
+ grpc_closure* on_done_closure;
+
+ grpc_iomgr_object iomgr_object;
+
/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */
grpc_fork_fd_list* fork_fd_list;
-};
-
+};
+
/* True when GRPC_ENABLE_FORK_SUPPORT=1. */
static bool track_fds_for_fork = false;
@@ -135,133 +135,133 @@ static bool track_fds_for_fork = false;
static grpc_fork_fd_list* fork_fd_list_head = nullptr;
static gpr_mu fork_fd_list_mu;
-/* Begin polling on an fd.
- Registers that the given pollset is interested in this fd - so that if read
- or writability interest changes, the pollset can be kicked to pick up that
- new interest.
- Return value is:
- (fd_needs_read? read_mask : 0) | (fd_needs_write? write_mask : 0)
- i.e. a combination of read_mask and write_mask determined by the fd's current
- interest in said events.
- Polling strategies that do not need to alter their behavior depending on the
- fd's current interest (such as epoll) do not need to call this function.
- MUST NOT be called with a pollset lock taken */
-static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset,
- grpc_pollset_worker* worker, uint32_t read_mask,
- uint32_t write_mask, grpc_fd_watcher* rec);
-/* Complete polling previously started with fd_begin_poll
- MUST NOT be called with a pollset lock taken
- if got_read or got_write are 1, also does the become_{readable,writable} as
- appropriate. */
+/* Begin polling on an fd.
+ Registers that the given pollset is interested in this fd - so that if read
+ or writability interest changes, the pollset can be kicked to pick up that
+ new interest.
+ Return value is:
+ (fd_needs_read? read_mask : 0) | (fd_needs_write? write_mask : 0)
+ i.e. a combination of read_mask and write_mask determined by the fd's current
+ interest in said events.
+ Polling strategies that do not need to alter their behavior depending on the
+ fd's current interest (such as epoll) do not need to call this function.
+ MUST NOT be called with a pollset lock taken */
+static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset,
+ grpc_pollset_worker* worker, uint32_t read_mask,
+ uint32_t write_mask, grpc_fd_watcher* rec);
+/* Complete polling previously started with fd_begin_poll
+ MUST NOT be called with a pollset lock taken
+ if got_read or got_write are 1, also does the become_{readable,writable} as
+ appropriate. */
static void fd_end_poll(grpc_fd_watcher* rec, int got_read, int got_write);
-
-/* Return 1 if this fd is orphaned, 0 otherwise */
-static bool fd_is_orphaned(grpc_fd* fd);
-
-#ifndef NDEBUG
-static void fd_ref(grpc_fd* fd, const char* reason, const char* file, int line);
-static void fd_unref(grpc_fd* fd, const char* reason, const char* file,
- int line);
-#define GRPC_FD_REF(fd, reason) fd_ref(fd, reason, __FILE__, __LINE__)
-#define GRPC_FD_UNREF(fd, reason) fd_unref(fd, reason, __FILE__, __LINE__)
-#else
-static void fd_ref(grpc_fd* fd);
-static void fd_unref(grpc_fd* fd);
-#define GRPC_FD_REF(fd, reason) fd_ref(fd)
-#define GRPC_FD_UNREF(fd, reason) fd_unref(fd)
-#endif
-
-#define CLOSURE_NOT_READY ((grpc_closure*)0)
-#define CLOSURE_READY ((grpc_closure*)1)
-
-/*******************************************************************************
- * pollset declarations
- */
-
-typedef struct grpc_cached_wakeup_fd {
- grpc_wakeup_fd fd;
- struct grpc_cached_wakeup_fd* next;
+
+/* Return 1 if this fd is orphaned, 0 otherwise */
+static bool fd_is_orphaned(grpc_fd* fd);
+
+#ifndef NDEBUG
+static void fd_ref(grpc_fd* fd, const char* reason, const char* file, int line);
+static void fd_unref(grpc_fd* fd, const char* reason, const char* file,
+ int line);
+#define GRPC_FD_REF(fd, reason) fd_ref(fd, reason, __FILE__, __LINE__)
+#define GRPC_FD_UNREF(fd, reason) fd_unref(fd, reason, __FILE__, __LINE__)
+#else
+static void fd_ref(grpc_fd* fd);
+static void fd_unref(grpc_fd* fd);
+#define GRPC_FD_REF(fd, reason) fd_ref(fd)
+#define GRPC_FD_UNREF(fd, reason) fd_unref(fd)
+#endif
+
+#define CLOSURE_NOT_READY ((grpc_closure*)0)
+#define CLOSURE_READY ((grpc_closure*)1)
+
+/*******************************************************************************
+ * pollset declarations
+ */
+
+typedef struct grpc_cached_wakeup_fd {
+ grpc_wakeup_fd fd;
+ struct grpc_cached_wakeup_fd* next;
/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */
grpc_fork_fd_list* fork_fd_list;
-} grpc_cached_wakeup_fd;
-
-struct grpc_pollset_worker {
- grpc_cached_wakeup_fd* wakeup_fd;
- int reevaluate_polling_on_wakeup;
- int kicked_specifically;
- struct grpc_pollset_worker* next;
- struct grpc_pollset_worker* prev;
-};
-
-struct grpc_pollset {
- gpr_mu mu;
- grpc_pollset_worker root_worker;
- int shutting_down;
- int called_shutdown;
- int kicked_without_pollers;
- grpc_closure* shutdown_done;
- int pollset_set_count;
- /* all polled fds */
- size_t fd_count;
- size_t fd_capacity;
- grpc_fd** fds;
- /* Local cache of eventfds for workers */
- grpc_cached_wakeup_fd* local_wakeup_cache;
-};
-
-/* Add an fd to a pollset */
-static void pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd);
-
-static void pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd);
-
-/* Convert a timespec to milliseconds:
- - very small or negative poll times are clamped to zero to do a
- non-blocking poll (which becomes spin polling)
- - other small values are rounded up to one millisecond
- - longer than a millisecond polls are rounded up to the next nearest
- millisecond to avoid spinning
- - infinite timeouts are converted to -1 */
-static int poll_deadline_to_millis_timeout(grpc_millis deadline);
-
-/* Allow kick to wakeup the currently polling worker */
-#define GRPC_POLLSET_CAN_KICK_SELF 1
-/* Force the wakee to repoll when awoken */
-#define GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP 2
-/* As per pollset_kick, with an extended set of flags (defined above)
- -- mostly for fd_posix's use. */
-static grpc_error* pollset_kick_ext(grpc_pollset* p,
- grpc_pollset_worker* specific_worker,
- uint32_t flags) GRPC_MUST_USE_RESULT;
-
-/* Return 1 if the pollset has active threads in pollset_work (pollset must
- * be locked) */
-static bool pollset_has_workers(grpc_pollset* pollset);
-
-/*******************************************************************************
- * pollset_set definitions
- */
-
-struct grpc_pollset_set {
- gpr_mu mu;
-
- size_t pollset_count;
- size_t pollset_capacity;
- grpc_pollset** pollsets;
-
- size_t pollset_set_count;
- size_t pollset_set_capacity;
- struct grpc_pollset_set** pollset_sets;
-
- size_t fd_count;
- size_t fd_capacity;
- grpc_fd** fds;
-};
-
-/*******************************************************************************
+} grpc_cached_wakeup_fd;
+
+struct grpc_pollset_worker {
+ grpc_cached_wakeup_fd* wakeup_fd;
+ int reevaluate_polling_on_wakeup;
+ int kicked_specifically;
+ struct grpc_pollset_worker* next;
+ struct grpc_pollset_worker* prev;
+};
+
+struct grpc_pollset {
+ gpr_mu mu;
+ grpc_pollset_worker root_worker;
+ int shutting_down;
+ int called_shutdown;
+ int kicked_without_pollers;
+ grpc_closure* shutdown_done;
+ int pollset_set_count;
+ /* all polled fds */
+ size_t fd_count;
+ size_t fd_capacity;
+ grpc_fd** fds;
+ /* Local cache of eventfds for workers */
+ grpc_cached_wakeup_fd* local_wakeup_cache;
+};
+
+/* Add an fd to a pollset */
+static void pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd);
+
+static void pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd);
+
+/* Convert a timespec to milliseconds:
+ - very small or negative poll times are clamped to zero to do a
+ non-blocking poll (which becomes spin polling)
+ - other small values are rounded up to one millisecond
+ - longer than a millisecond polls are rounded up to the next nearest
+ millisecond to avoid spinning
+ - infinite timeouts are converted to -1 */
+static int poll_deadline_to_millis_timeout(grpc_millis deadline);
+
+/* Allow kick to wakeup the currently polling worker */
+#define GRPC_POLLSET_CAN_KICK_SELF 1
+/* Force the wakee to repoll when awoken */
+#define GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP 2
+/* As per pollset_kick, with an extended set of flags (defined above)
+ -- mostly for fd_posix's use. */
+static grpc_error* pollset_kick_ext(grpc_pollset* p,
+ grpc_pollset_worker* specific_worker,
+ uint32_t flags) GRPC_MUST_USE_RESULT;
+
+/* Return 1 if the pollset has active threads in pollset_work (pollset must
+ * be locked) */
+static bool pollset_has_workers(grpc_pollset* pollset);
+
+/*******************************************************************************
+ * pollset_set definitions
+ */
+
+struct grpc_pollset_set {
+ gpr_mu mu;
+
+ size_t pollset_count;
+ size_t pollset_capacity;
+ grpc_pollset** pollsets;
+
+ size_t pollset_set_count;
+ size_t pollset_set_capacity;
+ struct grpc_pollset_set** pollset_sets;
+
+ size_t fd_count;
+ size_t fd_capacity;
+ grpc_fd** fds;
+};
+
+/*******************************************************************************
* functions to track opened fds. No-ops unless track_fds_for_fork is true.
- */
-
+ */
+
static void fork_fd_list_remove_node(grpc_fork_fd_list* node) {
if (track_fds_for_fork) {
gpr_mu_lock(&fork_fd_list_mu);
@@ -314,18 +314,18 @@ static void fork_fd_list_add_wakeup_fd(grpc_cached_wakeup_fd* fd) {
* fd_posix.c
*/
-#ifndef NDEBUG
-#define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__)
-#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) {
+#ifndef NDEBUG
+#define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__)
+#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)) {
- 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
+ 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); \
@@ -336,242 +336,242 @@ static void ref_by(grpc_fd* fd, int n, const char* reason, const char* file,
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);
-}
-
-#ifndef NDEBUG
-static void unref_by(grpc_fd* fd, int n, const char* reason, const char* file,
- int line) {
+static void ref_by(grpc_fd* fd, int n) {
+#endif
+ GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0);
+}
+
+#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)) {
- 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),
- gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line);
- }
-#else
-static void unref_by(grpc_fd* fd, int n) {
-#endif
- gpr_atm old = gpr_atm_full_fetch_add(&fd->refst, -n);
- if (old == n) {
- gpr_mu_destroy(&fd->mu);
- grpc_iomgr_unregister_object(&fd->iomgr_object);
+ 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),
+ gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line);
+ }
+#else
+static void unref_by(grpc_fd* fd, int n) {
+#endif
+ gpr_atm old = gpr_atm_full_fetch_add(&fd->refst, -n);
+ if (old == n) {
+ gpr_mu_destroy(&fd->mu);
+ grpc_iomgr_unregister_object(&fd->iomgr_object);
fork_fd_list_remove_node(fd->fork_fd_list);
- if (fd->shutdown) GRPC_ERROR_UNREF(fd->shutdown_error);
- gpr_free(fd);
- } else {
- GPR_ASSERT(old > n);
- }
-}
-
+ if (fd->shutdown) GRPC_ERROR_UNREF(fd->shutdown_error);
+ gpr_free(fd);
+ } else {
+ GPR_ASSERT(old > 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;
GPR_DEBUG_ASSERT(track_err == false);
- grpc_fd* r = static_cast<grpc_fd*>(gpr_malloc(sizeof(*r)));
- gpr_mu_init(&r->mu);
- gpr_atm_rel_store(&r->refst, 1);
- r->shutdown = 0;
- r->read_closure = CLOSURE_NOT_READY;
- r->write_closure = CLOSURE_NOT_READY;
- r->fd = fd;
- r->inactive_watcher_root.next = r->inactive_watcher_root.prev =
- &r->inactive_watcher_root;
- r->read_watcher = r->write_watcher = nullptr;
- r->on_done_closure = nullptr;
- r->closed = 0;
- r->released = 0;
- gpr_atm_no_barrier_store(&r->pollhup, 0);
-
+ grpc_fd* r = static_cast<grpc_fd*>(gpr_malloc(sizeof(*r)));
+ gpr_mu_init(&r->mu);
+ gpr_atm_rel_store(&r->refst, 1);
+ r->shutdown = 0;
+ r->read_closure = CLOSURE_NOT_READY;
+ r->write_closure = CLOSURE_NOT_READY;
+ r->fd = fd;
+ r->inactive_watcher_root.next = r->inactive_watcher_root.prev =
+ &r->inactive_watcher_root;
+ r->read_watcher = r->write_watcher = nullptr;
+ r->on_done_closure = nullptr;
+ r->closed = 0;
+ r->released = 0;
+ gpr_atm_no_barrier_store(&r->pollhup, 0);
+
TString name2 = y_absl::StrCat(name, " fd=", fd);
grpc_iomgr_register_object(&r->iomgr_object, name2.c_str());
fork_fd_list_add_grpc_fd(r);
- return r;
-}
-
-static bool fd_is_orphaned(grpc_fd* fd) {
- return (gpr_atm_acq_load(&fd->refst) & 1) == 0;
-}
-
-static grpc_error* pollset_kick_locked(grpc_fd_watcher* watcher) {
- gpr_mu_lock(&watcher->pollset->mu);
- GPR_ASSERT(watcher->worker);
- grpc_error* err = pollset_kick_ext(watcher->pollset, watcher->worker,
- GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP);
- gpr_mu_unlock(&watcher->pollset->mu);
- return err;
-}
-
-static void maybe_wake_one_watcher_locked(grpc_fd* fd) {
- if (fd->inactive_watcher_root.next != &fd->inactive_watcher_root) {
- pollset_kick_locked(fd->inactive_watcher_root.next);
- } else if (fd->read_watcher) {
- pollset_kick_locked(fd->read_watcher);
- } else if (fd->write_watcher) {
- pollset_kick_locked(fd->write_watcher);
- }
-}
-
-static void wake_all_watchers_locked(grpc_fd* fd) {
- grpc_fd_watcher* watcher;
- for (watcher = fd->inactive_watcher_root.next;
- watcher != &fd->inactive_watcher_root; watcher = watcher->next) {
- pollset_kick_locked(watcher);
- }
- if (fd->read_watcher) {
- pollset_kick_locked(fd->read_watcher);
- }
- if (fd->write_watcher && fd->write_watcher != fd->read_watcher) {
- pollset_kick_locked(fd->write_watcher);
- }
-}
-
-static int has_watchers(grpc_fd* fd) {
- return fd->read_watcher != nullptr || fd->write_watcher != nullptr ||
- fd->inactive_watcher_root.next != &fd->inactive_watcher_root;
-}
-
-static void close_fd_locked(grpc_fd* fd) {
- fd->closed = 1;
- if (!fd->released) {
- close(fd->fd);
- }
+ return r;
+}
+
+static bool fd_is_orphaned(grpc_fd* fd) {
+ return (gpr_atm_acq_load(&fd->refst) & 1) == 0;
+}
+
+static grpc_error* pollset_kick_locked(grpc_fd_watcher* watcher) {
+ gpr_mu_lock(&watcher->pollset->mu);
+ GPR_ASSERT(watcher->worker);
+ grpc_error* err = pollset_kick_ext(watcher->pollset, watcher->worker,
+ GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP);
+ gpr_mu_unlock(&watcher->pollset->mu);
+ return err;
+}
+
+static void maybe_wake_one_watcher_locked(grpc_fd* fd) {
+ if (fd->inactive_watcher_root.next != &fd->inactive_watcher_root) {
+ pollset_kick_locked(fd->inactive_watcher_root.next);
+ } else if (fd->read_watcher) {
+ pollset_kick_locked(fd->read_watcher);
+ } else if (fd->write_watcher) {
+ pollset_kick_locked(fd->write_watcher);
+ }
+}
+
+static void wake_all_watchers_locked(grpc_fd* fd) {
+ grpc_fd_watcher* watcher;
+ for (watcher = fd->inactive_watcher_root.next;
+ watcher != &fd->inactive_watcher_root; watcher = watcher->next) {
+ pollset_kick_locked(watcher);
+ }
+ if (fd->read_watcher) {
+ pollset_kick_locked(fd->read_watcher);
+ }
+ if (fd->write_watcher && fd->write_watcher != fd->read_watcher) {
+ pollset_kick_locked(fd->write_watcher);
+ }
+}
+
+static int has_watchers(grpc_fd* fd) {
+ return fd->read_watcher != nullptr || fd->write_watcher != nullptr ||
+ fd->inactive_watcher_root.next != &fd->inactive_watcher_root;
+}
+
+static void close_fd_locked(grpc_fd* fd) {
+ fd->closed = 1;
+ if (!fd->released) {
+ close(fd->fd);
+ }
grpc_core::ExecCtx::Run(DEBUG_LOCATION, fd->on_done_closure, GRPC_ERROR_NONE);
-}
-
-static int fd_wrapped_fd(grpc_fd* fd) {
- if (fd->released || fd->closed) {
- return -1;
- } else {
- return fd->fd;
- }
-}
-
-static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
+}
+
+static int fd_wrapped_fd(grpc_fd* fd) {
+ if (fd->released || fd->closed) {
+ return -1;
+ } else {
+ return fd->fd;
+ }
+}
+
+static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
const char* reason) {
- fd->on_done_closure = on_done;
- fd->released = release_fd != nullptr;
- if (release_fd != nullptr) {
- *release_fd = fd->fd;
- fd->released = true;
- }
- gpr_mu_lock(&fd->mu);
- REF_BY(fd, 1, reason); /* remove active status, but keep referenced */
- if (!has_watchers(fd)) {
- close_fd_locked(fd);
- } else {
- wake_all_watchers_locked(fd);
- }
- gpr_mu_unlock(&fd->mu);
- UNREF_BY(fd, 2, reason); /* drop the reference */
-}
-
-/* increment refcount by two to avoid changing the orphan bit */
-#ifndef NDEBUG
-static void fd_ref(grpc_fd* fd, const char* reason, const char* file,
- int line) {
- ref_by(fd, 2, reason, file, line);
-}
-
-static void fd_unref(grpc_fd* fd, const char* reason, const char* file,
- int line) {
- unref_by(fd, 2, reason, file, line);
-}
-#else
-static void fd_ref(grpc_fd* fd) { ref_by(fd, 2); }
-
-static void fd_unref(grpc_fd* fd) { unref_by(fd, 2); }
-#endif
-
-static grpc_error* fd_shutdown_error(grpc_fd* fd) {
- if (!fd->shutdown) {
- return GRPC_ERROR_NONE;
- } else {
- return grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "FD shutdown", &fd->shutdown_error, 1),
- GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_UNAVAILABLE);
- }
-}
-
-static void notify_on_locked(grpc_fd* fd, grpc_closure** st,
- grpc_closure* closure) {
- if (fd->shutdown || gpr_atm_no_barrier_load(&fd->pollhup)) {
+ fd->on_done_closure = on_done;
+ fd->released = release_fd != nullptr;
+ if (release_fd != nullptr) {
+ *release_fd = fd->fd;
+ fd->released = true;
+ }
+ gpr_mu_lock(&fd->mu);
+ REF_BY(fd, 1, reason); /* remove active status, but keep referenced */
+ if (!has_watchers(fd)) {
+ close_fd_locked(fd);
+ } else {
+ wake_all_watchers_locked(fd);
+ }
+ gpr_mu_unlock(&fd->mu);
+ UNREF_BY(fd, 2, reason); /* drop the reference */
+}
+
+/* increment refcount by two to avoid changing the orphan bit */
+#ifndef NDEBUG
+static void fd_ref(grpc_fd* fd, const char* reason, const char* file,
+ int line) {
+ ref_by(fd, 2, reason, file, line);
+}
+
+static void fd_unref(grpc_fd* fd, const char* reason, const char* file,
+ int line) {
+ unref_by(fd, 2, reason, file, line);
+}
+#else
+static void fd_ref(grpc_fd* fd) { ref_by(fd, 2); }
+
+static void fd_unref(grpc_fd* fd) { unref_by(fd, 2); }
+#endif
+
+static grpc_error* fd_shutdown_error(grpc_fd* fd) {
+ if (!fd->shutdown) {
+ return GRPC_ERROR_NONE;
+ } else {
+ return grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "FD shutdown", &fd->shutdown_error, 1),
+ GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_UNAVAILABLE);
+ }
+}
+
+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));
- } 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;
+ } 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));
- maybe_wake_one_watcher_locked(fd);
- } else {
- /* upcallptr was set to a different closure. This is an error! */
- gpr_log(GPR_ERROR,
- "User called a notify_on function with a previous callback still "
- "pending");
- abort();
- }
-}
-
-/* returns 1 if state becomes not ready */
-static int set_ready_locked(grpc_fd* fd, grpc_closure** st) {
- if (*st == CLOSURE_READY) {
- /* duplicate ready ==> ignore */
- return 0;
- } else if (*st == CLOSURE_NOT_READY) {
- /* not ready, and not waiting ==> flag ready */
- *st = CLOSURE_READY;
- return 0;
- } else {
- /* waiting ==> queue closure */
+ maybe_wake_one_watcher_locked(fd);
+ } else {
+ /* upcallptr was set to a different closure. This is an error! */
+ gpr_log(GPR_ERROR,
+ "User called a notify_on function with a previous callback still "
+ "pending");
+ abort();
+ }
+}
+
+/* returns 1 if state becomes not ready */
+static int set_ready_locked(grpc_fd* fd, grpc_closure** st) {
+ if (*st == CLOSURE_READY) {
+ /* duplicate ready ==> ignore */
+ return 0;
+ } else if (*st == CLOSURE_NOT_READY) {
+ /* not ready, and not waiting ==> flag ready */
+ *st = CLOSURE_READY;
+ return 0;
+ } else {
+ /* waiting ==> queue closure */
grpc_core::ExecCtx::Run(DEBUG_LOCATION, *st, fd_shutdown_error(fd));
- *st = CLOSURE_NOT_READY;
- return 1;
- }
-}
-
-static void fd_shutdown(grpc_fd* fd, grpc_error* why) {
- gpr_mu_lock(&fd->mu);
- /* only shutdown once */
- if (!fd->shutdown) {
- fd->shutdown = 1;
- fd->shutdown_error = why;
- /* signal read/write closed to OS so that future operations fail */
- shutdown(fd->fd, SHUT_RDWR);
- set_ready_locked(fd, &fd->read_closure);
- set_ready_locked(fd, &fd->write_closure);
- } else {
- GRPC_ERROR_UNREF(why);
- }
- gpr_mu_unlock(&fd->mu);
-}
-
-static bool fd_is_shutdown(grpc_fd* fd) {
- gpr_mu_lock(&fd->mu);
- bool r = fd->shutdown;
- gpr_mu_unlock(&fd->mu);
- return r;
-}
-
-static void fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
- gpr_mu_lock(&fd->mu);
- notify_on_locked(fd, &fd->read_closure, closure);
- gpr_mu_unlock(&fd->mu);
-}
-
-static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
- gpr_mu_lock(&fd->mu);
- notify_on_locked(fd, &fd->write_closure, closure);
- gpr_mu_unlock(&fd->mu);
-}
-
+ *st = CLOSURE_NOT_READY;
+ return 1;
+ }
+}
+
+static void fd_shutdown(grpc_fd* fd, grpc_error* why) {
+ gpr_mu_lock(&fd->mu);
+ /* only shutdown once */
+ if (!fd->shutdown) {
+ fd->shutdown = 1;
+ fd->shutdown_error = why;
+ /* signal read/write closed to OS so that future operations fail */
+ shutdown(fd->fd, SHUT_RDWR);
+ set_ready_locked(fd, &fd->read_closure);
+ set_ready_locked(fd, &fd->write_closure);
+ } else {
+ GRPC_ERROR_UNREF(why);
+ }
+ gpr_mu_unlock(&fd->mu);
+}
+
+static bool fd_is_shutdown(grpc_fd* fd) {
+ gpr_mu_lock(&fd->mu);
+ bool r = fd->shutdown;
+ gpr_mu_unlock(&fd->mu);
+ return r;
+}
+
+static void fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
+ gpr_mu_lock(&fd->mu);
+ notify_on_locked(fd, &fd->read_closure, closure);
+ gpr_mu_unlock(&fd->mu);
+}
+
+static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
+ gpr_mu_lock(&fd->mu);
+ notify_on_locked(fd, &fd->write_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)) {
gpr_log(GPR_ERROR, "Polling engine does not support tracking errors.");
@@ -597,738 +597,738 @@ static void fd_set_error(grpc_fd* /*fd*/) {
}
}
-static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset,
- grpc_pollset_worker* worker, uint32_t read_mask,
- uint32_t write_mask, grpc_fd_watcher* watcher) {
- uint32_t mask = 0;
- grpc_closure* cur;
- int requested;
- /* keep track of pollers that have requested our events, in case they change
- */
- GRPC_FD_REF(fd, "poll");
-
- gpr_mu_lock(&fd->mu);
-
- /* if we are shutdown, then don't add to the watcher set */
- if (fd->shutdown) {
- watcher->fd = nullptr;
- watcher->pollset = nullptr;
- watcher->worker = nullptr;
- gpr_mu_unlock(&fd->mu);
- GRPC_FD_UNREF(fd, "poll");
- return 0;
- }
-
- /* if there is nobody polling for read, but we need to, then start doing so */
- cur = fd->read_closure;
- requested = cur != CLOSURE_READY;
- if (read_mask && fd->read_watcher == nullptr && requested) {
- fd->read_watcher = watcher;
- mask |= read_mask;
- }
- /* if there is nobody polling for write, but we need to, then start doing so
- */
- cur = fd->write_closure;
- requested = cur != CLOSURE_READY;
- if (write_mask && fd->write_watcher == nullptr && requested) {
- fd->write_watcher = watcher;
- mask |= write_mask;
- }
- /* if not polling, remember this watcher in case we need someone to later */
- if (mask == 0 && worker != nullptr) {
- watcher->next = &fd->inactive_watcher_root;
- watcher->prev = watcher->next->prev;
- watcher->next->prev = watcher->prev->next = watcher;
- }
- watcher->pollset = pollset;
- watcher->worker = worker;
- watcher->fd = fd;
- gpr_mu_unlock(&fd->mu);
-
- return mask;
-}
-
+static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset,
+ grpc_pollset_worker* worker, uint32_t read_mask,
+ uint32_t write_mask, grpc_fd_watcher* watcher) {
+ uint32_t mask = 0;
+ grpc_closure* cur;
+ int requested;
+ /* keep track of pollers that have requested our events, in case they change
+ */
+ GRPC_FD_REF(fd, "poll");
+
+ gpr_mu_lock(&fd->mu);
+
+ /* if we are shutdown, then don't add to the watcher set */
+ if (fd->shutdown) {
+ watcher->fd = nullptr;
+ watcher->pollset = nullptr;
+ watcher->worker = nullptr;
+ gpr_mu_unlock(&fd->mu);
+ GRPC_FD_UNREF(fd, "poll");
+ return 0;
+ }
+
+ /* if there is nobody polling for read, but we need to, then start doing so */
+ cur = fd->read_closure;
+ requested = cur != CLOSURE_READY;
+ if (read_mask && fd->read_watcher == nullptr && requested) {
+ fd->read_watcher = watcher;
+ mask |= read_mask;
+ }
+ /* if there is nobody polling for write, but we need to, then start doing so
+ */
+ cur = fd->write_closure;
+ requested = cur != CLOSURE_READY;
+ if (write_mask && fd->write_watcher == nullptr && requested) {
+ fd->write_watcher = watcher;
+ mask |= write_mask;
+ }
+ /* if not polling, remember this watcher in case we need someone to later */
+ if (mask == 0 && worker != nullptr) {
+ watcher->next = &fd->inactive_watcher_root;
+ watcher->prev = watcher->next->prev;
+ watcher->next->prev = watcher->prev->next = watcher;
+ }
+ watcher->pollset = pollset;
+ watcher->worker = worker;
+ watcher->fd = fd;
+ gpr_mu_unlock(&fd->mu);
+
+ return mask;
+}
+
static void fd_end_poll(grpc_fd_watcher* watcher, int got_read, int got_write) {
- int was_polling = 0;
- int kick = 0;
- grpc_fd* fd = watcher->fd;
-
- if (fd == nullptr) {
- return;
- }
-
- gpr_mu_lock(&fd->mu);
-
- if (watcher == fd->read_watcher) {
- /* remove read watcher, kick if we still need a read */
- was_polling = 1;
- if (!got_read) {
- kick = 1;
- }
- fd->read_watcher = nullptr;
- }
- if (watcher == fd->write_watcher) {
- /* remove write watcher, kick if we still need a write */
- was_polling = 1;
- if (!got_write) {
- kick = 1;
- }
- fd->write_watcher = nullptr;
- }
- if (!was_polling && watcher->worker != nullptr) {
- /* remove from inactive list */
- watcher->next->prev = watcher->prev;
- watcher->prev->next = watcher->next;
- }
- if (got_read) {
- if (set_ready_locked(fd, &fd->read_closure)) {
- kick = 1;
- }
- }
- if (got_write) {
- if (set_ready_locked(fd, &fd->write_closure)) {
- kick = 1;
- }
- }
- if (kick) {
- maybe_wake_one_watcher_locked(fd);
- }
- if (fd_is_orphaned(fd) && !has_watchers(fd) && !fd->closed) {
- close_fd_locked(fd);
- }
- gpr_mu_unlock(&fd->mu);
-
- GRPC_FD_UNREF(fd, "poll");
-}
-
-/*******************************************************************************
- * pollset_posix.c
- */
-
-GPR_TLS_DECL(g_current_thread_poller);
-GPR_TLS_DECL(g_current_thread_worker);
-
+ int was_polling = 0;
+ int kick = 0;
+ grpc_fd* fd = watcher->fd;
+
+ if (fd == nullptr) {
+ return;
+ }
+
+ gpr_mu_lock(&fd->mu);
+
+ if (watcher == fd->read_watcher) {
+ /* remove read watcher, kick if we still need a read */
+ was_polling = 1;
+ if (!got_read) {
+ kick = 1;
+ }
+ fd->read_watcher = nullptr;
+ }
+ if (watcher == fd->write_watcher) {
+ /* remove write watcher, kick if we still need a write */
+ was_polling = 1;
+ if (!got_write) {
+ kick = 1;
+ }
+ fd->write_watcher = nullptr;
+ }
+ if (!was_polling && watcher->worker != nullptr) {
+ /* remove from inactive list */
+ watcher->next->prev = watcher->prev;
+ watcher->prev->next = watcher->next;
+ }
+ if (got_read) {
+ if (set_ready_locked(fd, &fd->read_closure)) {
+ kick = 1;
+ }
+ }
+ if (got_write) {
+ if (set_ready_locked(fd, &fd->write_closure)) {
+ kick = 1;
+ }
+ }
+ if (kick) {
+ maybe_wake_one_watcher_locked(fd);
+ }
+ if (fd_is_orphaned(fd) && !has_watchers(fd) && !fd->closed) {
+ close_fd_locked(fd);
+ }
+ gpr_mu_unlock(&fd->mu);
+
+ GRPC_FD_UNREF(fd, "poll");
+}
+
+/*******************************************************************************
+ * pollset_posix.c
+ */
+
+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) {
- worker->prev->next = worker->next;
- worker->next->prev = worker->prev;
-}
-
-static bool pollset_has_workers(grpc_pollset* p) {
- return p->root_worker.next != &p->root_worker;
-}
-
-static bool pollset_in_pollset_sets(grpc_pollset* p) {
- return p->pollset_set_count;
-}
-
-static bool pollset_has_observers(grpc_pollset* p) {
- return pollset_has_workers(p) || pollset_in_pollset_sets(p);
-}
-
-static grpc_pollset_worker* pop_front_worker(grpc_pollset* p) {
- if (pollset_has_workers(p)) {
- grpc_pollset_worker* w = p->root_worker.next;
- remove_worker(p, w);
- return w;
- } else {
- return nullptr;
- }
-}
-
-static void push_back_worker(grpc_pollset* p, grpc_pollset_worker* worker) {
- worker->next = &p->root_worker;
- worker->prev = worker->next->prev;
- worker->prev->next = worker->next->prev = worker;
-}
-
-static void push_front_worker(grpc_pollset* p, grpc_pollset_worker* worker) {
- worker->prev = &p->root_worker;
- worker->next = worker->prev->next;
- worker->prev->next = worker->next->prev = worker;
-}
-
-static void kick_append_error(grpc_error** composite, grpc_error* error) {
- if (error == GRPC_ERROR_NONE) return;
- if (*composite == GRPC_ERROR_NONE) {
- *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Kick Failure");
- }
- *composite = grpc_error_add_child(*composite, error);
-}
-
-static grpc_error* pollset_kick_ext(grpc_pollset* p,
- grpc_pollset_worker* specific_worker,
- uint32_t flags) {
- GPR_TIMER_SCOPE("pollset_kick_ext", 0);
- grpc_error* error = GRPC_ERROR_NONE;
- GRPC_STATS_INC_POLLSET_KICK();
-
- /* pollset->mu already held */
- if (specific_worker != nullptr) {
- if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
- GPR_TIMER_SCOPE("pollset_kick_ext.broadcast", 0);
- GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0);
- for (specific_worker = p->root_worker.next;
- specific_worker != &p->root_worker;
- specific_worker = specific_worker->next) {
- kick_append_error(
- &error, grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
- }
- p->kicked_without_pollers = true;
- } else if (gpr_tls_get(&g_current_thread_worker) !=
- (intptr_t)specific_worker) {
- GPR_TIMER_MARK("different_thread_worker", 0);
- if ((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) != 0) {
- specific_worker->reevaluate_polling_on_wakeup = true;
- }
- specific_worker->kicked_specifically = true;
- kick_append_error(&error,
- grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
- } else if ((flags & GRPC_POLLSET_CAN_KICK_SELF) != 0) {
- GPR_TIMER_MARK("kick_yoself", 0);
- if ((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) != 0) {
- specific_worker->reevaluate_polling_on_wakeup = true;
- }
- specific_worker->kicked_specifically = true;
- kick_append_error(&error,
- grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
- }
- } else if (gpr_tls_get(&g_current_thread_poller) != (intptr_t)p) {
- GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0);
- GPR_TIMER_MARK("kick_anonymous", 0);
- specific_worker = pop_front_worker(p);
- if (specific_worker != nullptr) {
- if (gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) {
- GPR_TIMER_MARK("kick_anonymous_not_self", 0);
- push_back_worker(p, specific_worker);
- specific_worker = pop_front_worker(p);
- if ((flags & GRPC_POLLSET_CAN_KICK_SELF) == 0 &&
- gpr_tls_get(&g_current_thread_worker) ==
- (intptr_t)specific_worker) {
- push_back_worker(p, specific_worker);
- specific_worker = nullptr;
- }
- }
- if (specific_worker != nullptr) {
- GPR_TIMER_MARK("finally_kick", 0);
- push_back_worker(p, specific_worker);
- kick_append_error(
- &error, grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
- }
- } else {
- GPR_TIMER_MARK("kicked_no_pollers", 0);
- p->kicked_without_pollers = true;
- }
- }
-
- GRPC_LOG_IF_ERROR("pollset_kick_ext", GRPC_ERROR_REF(error));
- return error;
-}
-
-static grpc_error* pollset_kick(grpc_pollset* p,
- grpc_pollset_worker* specific_worker) {
- return pollset_kick_ext(p, specific_worker, 0);
-}
-
-/* global state management */
-
-static grpc_error* pollset_global_init(void) {
- gpr_tls_init(&g_current_thread_poller);
- gpr_tls_init(&g_current_thread_worker);
- return GRPC_ERROR_NONE;
-}
-
-static void pollset_global_shutdown(void) {
- gpr_tls_destroy(&g_current_thread_poller);
- gpr_tls_destroy(&g_current_thread_worker);
-}
-
-/* main interface */
-
-static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
- gpr_mu_init(&pollset->mu);
- *mu = &pollset->mu;
- pollset->root_worker.next = pollset->root_worker.prev = &pollset->root_worker;
- pollset->shutting_down = 0;
- pollset->called_shutdown = 0;
- pollset->kicked_without_pollers = 0;
- pollset->local_wakeup_cache = nullptr;
- pollset->kicked_without_pollers = 0;
- pollset->fd_count = 0;
- pollset->fd_capacity = 0;
- pollset->fds = nullptr;
- pollset->pollset_set_count = 0;
-}
-
-static void pollset_destroy(grpc_pollset* pollset) {
- GPR_ASSERT(!pollset_has_workers(pollset));
- while (pollset->local_wakeup_cache) {
- grpc_cached_wakeup_fd* next = pollset->local_wakeup_cache->next;
+ worker->prev->next = worker->next;
+ worker->next->prev = worker->prev;
+}
+
+static bool pollset_has_workers(grpc_pollset* p) {
+ return p->root_worker.next != &p->root_worker;
+}
+
+static bool pollset_in_pollset_sets(grpc_pollset* p) {
+ return p->pollset_set_count;
+}
+
+static bool pollset_has_observers(grpc_pollset* p) {
+ return pollset_has_workers(p) || pollset_in_pollset_sets(p);
+}
+
+static grpc_pollset_worker* pop_front_worker(grpc_pollset* p) {
+ if (pollset_has_workers(p)) {
+ grpc_pollset_worker* w = p->root_worker.next;
+ remove_worker(p, w);
+ return w;
+ } else {
+ return nullptr;
+ }
+}
+
+static void push_back_worker(grpc_pollset* p, grpc_pollset_worker* worker) {
+ worker->next = &p->root_worker;
+ worker->prev = worker->next->prev;
+ worker->prev->next = worker->next->prev = worker;
+}
+
+static void push_front_worker(grpc_pollset* p, grpc_pollset_worker* worker) {
+ worker->prev = &p->root_worker;
+ worker->next = worker->prev->next;
+ worker->prev->next = worker->next->prev = worker;
+}
+
+static void kick_append_error(grpc_error** composite, grpc_error* error) {
+ if (error == GRPC_ERROR_NONE) return;
+ if (*composite == GRPC_ERROR_NONE) {
+ *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Kick Failure");
+ }
+ *composite = grpc_error_add_child(*composite, error);
+}
+
+static grpc_error* pollset_kick_ext(grpc_pollset* p,
+ grpc_pollset_worker* specific_worker,
+ uint32_t flags) {
+ GPR_TIMER_SCOPE("pollset_kick_ext", 0);
+ grpc_error* error = GRPC_ERROR_NONE;
+ GRPC_STATS_INC_POLLSET_KICK();
+
+ /* pollset->mu already held */
+ if (specific_worker != nullptr) {
+ if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
+ GPR_TIMER_SCOPE("pollset_kick_ext.broadcast", 0);
+ GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0);
+ for (specific_worker = p->root_worker.next;
+ specific_worker != &p->root_worker;
+ specific_worker = specific_worker->next) {
+ kick_append_error(
+ &error, grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
+ }
+ p->kicked_without_pollers = true;
+ } else if (gpr_tls_get(&g_current_thread_worker) !=
+ (intptr_t)specific_worker) {
+ GPR_TIMER_MARK("different_thread_worker", 0);
+ if ((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) != 0) {
+ specific_worker->reevaluate_polling_on_wakeup = true;
+ }
+ specific_worker->kicked_specifically = true;
+ kick_append_error(&error,
+ grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
+ } else if ((flags & GRPC_POLLSET_CAN_KICK_SELF) != 0) {
+ GPR_TIMER_MARK("kick_yoself", 0);
+ if ((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) != 0) {
+ specific_worker->reevaluate_polling_on_wakeup = true;
+ }
+ specific_worker->kicked_specifically = true;
+ kick_append_error(&error,
+ grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
+ }
+ } else if (gpr_tls_get(&g_current_thread_poller) != (intptr_t)p) {
+ GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0);
+ GPR_TIMER_MARK("kick_anonymous", 0);
+ specific_worker = pop_front_worker(p);
+ if (specific_worker != nullptr) {
+ if (gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) {
+ GPR_TIMER_MARK("kick_anonymous_not_self", 0);
+ push_back_worker(p, specific_worker);
+ specific_worker = pop_front_worker(p);
+ if ((flags & GRPC_POLLSET_CAN_KICK_SELF) == 0 &&
+ gpr_tls_get(&g_current_thread_worker) ==
+ (intptr_t)specific_worker) {
+ push_back_worker(p, specific_worker);
+ specific_worker = nullptr;
+ }
+ }
+ if (specific_worker != nullptr) {
+ GPR_TIMER_MARK("finally_kick", 0);
+ push_back_worker(p, specific_worker);
+ kick_append_error(
+ &error, grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
+ }
+ } else {
+ GPR_TIMER_MARK("kicked_no_pollers", 0);
+ p->kicked_without_pollers = true;
+ }
+ }
+
+ GRPC_LOG_IF_ERROR("pollset_kick_ext", GRPC_ERROR_REF(error));
+ return error;
+}
+
+static grpc_error* pollset_kick(grpc_pollset* p,
+ grpc_pollset_worker* specific_worker) {
+ return pollset_kick_ext(p, specific_worker, 0);
+}
+
+/* global state management */
+
+static grpc_error* pollset_global_init(void) {
+ gpr_tls_init(&g_current_thread_poller);
+ gpr_tls_init(&g_current_thread_worker);
+ return GRPC_ERROR_NONE;
+}
+
+static void pollset_global_shutdown(void) {
+ gpr_tls_destroy(&g_current_thread_poller);
+ gpr_tls_destroy(&g_current_thread_worker);
+}
+
+/* main interface */
+
+static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
+ gpr_mu_init(&pollset->mu);
+ *mu = &pollset->mu;
+ pollset->root_worker.next = pollset->root_worker.prev = &pollset->root_worker;
+ pollset->shutting_down = 0;
+ pollset->called_shutdown = 0;
+ pollset->kicked_without_pollers = 0;
+ pollset->local_wakeup_cache = nullptr;
+ pollset->kicked_without_pollers = 0;
+ pollset->fd_count = 0;
+ pollset->fd_capacity = 0;
+ pollset->fds = nullptr;
+ pollset->pollset_set_count = 0;
+}
+
+static void pollset_destroy(grpc_pollset* pollset) {
+ GPR_ASSERT(!pollset_has_workers(pollset));
+ while (pollset->local_wakeup_cache) {
+ grpc_cached_wakeup_fd* next = pollset->local_wakeup_cache->next;
fork_fd_list_remove_node(pollset->local_wakeup_cache->fork_fd_list);
- grpc_wakeup_fd_destroy(&pollset->local_wakeup_cache->fd);
- gpr_free(pollset->local_wakeup_cache);
- pollset->local_wakeup_cache = next;
- }
- gpr_free(pollset->fds);
- gpr_mu_destroy(&pollset->mu);
-}
-
-static void pollset_add_fd(grpc_pollset* pollset, grpc_fd* fd) {
- gpr_mu_lock(&pollset->mu);
- size_t i;
- /* TODO(ctiller): this is O(num_fds^2); maybe switch to a hash set here */
- for (i = 0; i < pollset->fd_count; i++) {
- if (pollset->fds[i] == fd) goto exit;
- }
- if (pollset->fd_count == pollset->fd_capacity) {
- pollset->fd_capacity =
- GPR_MAX(pollset->fd_capacity + 8, pollset->fd_count * 3 / 2);
- pollset->fds = static_cast<grpc_fd**>(
- gpr_realloc(pollset->fds, sizeof(grpc_fd*) * pollset->fd_capacity));
- }
- pollset->fds[pollset->fd_count++] = fd;
- GRPC_FD_REF(fd, "multipoller");
- pollset_kick(pollset, nullptr);
-exit:
- gpr_mu_unlock(&pollset->mu);
-}
-
-static void finish_shutdown(grpc_pollset* pollset) {
- size_t i;
- for (i = 0; i < pollset->fd_count; i++) {
- GRPC_FD_UNREF(pollset->fds[i], "multipoller");
- }
- pollset->fd_count = 0;
+ grpc_wakeup_fd_destroy(&pollset->local_wakeup_cache->fd);
+ gpr_free(pollset->local_wakeup_cache);
+ pollset->local_wakeup_cache = next;
+ }
+ gpr_free(pollset->fds);
+ gpr_mu_destroy(&pollset->mu);
+}
+
+static void pollset_add_fd(grpc_pollset* pollset, grpc_fd* fd) {
+ gpr_mu_lock(&pollset->mu);
+ size_t i;
+ /* TODO(ctiller): this is O(num_fds^2); maybe switch to a hash set here */
+ for (i = 0; i < pollset->fd_count; i++) {
+ if (pollset->fds[i] == fd) goto exit;
+ }
+ if (pollset->fd_count == pollset->fd_capacity) {
+ pollset->fd_capacity =
+ GPR_MAX(pollset->fd_capacity + 8, pollset->fd_count * 3 / 2);
+ pollset->fds = static_cast<grpc_fd**>(
+ gpr_realloc(pollset->fds, sizeof(grpc_fd*) * pollset->fd_capacity));
+ }
+ pollset->fds[pollset->fd_count++] = fd;
+ GRPC_FD_REF(fd, "multipoller");
+ pollset_kick(pollset, nullptr);
+exit:
+ gpr_mu_unlock(&pollset->mu);
+}
+
+static void finish_shutdown(grpc_pollset* pollset) {
+ size_t i;
+ for (i = 0; i < pollset->fd_count; i++) {
+ GRPC_FD_UNREF(pollset->fds[i], "multipoller");
+ }
+ pollset->fd_count = 0;
grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->shutdown_done,
GRPC_ERROR_NONE);
-}
-
-static void work_combine_error(grpc_error** composite, grpc_error* error) {
- if (error == GRPC_ERROR_NONE) return;
- if (*composite == GRPC_ERROR_NONE) {
- *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("pollset_work");
- }
- *composite = grpc_error_add_child(*composite, error);
-}
-
-static grpc_error* pollset_work(grpc_pollset* pollset,
- grpc_pollset_worker** worker_hdl,
- grpc_millis deadline) {
- GPR_TIMER_SCOPE("pollset_work", 0);
- grpc_pollset_worker worker;
- if (worker_hdl) *worker_hdl = &worker;
- grpc_error* error = GRPC_ERROR_NONE;
-
- /* Avoid malloc for small number of elements. */
- enum { inline_elements = 96 };
- struct pollfd pollfd_space[inline_elements];
- struct grpc_fd_watcher watcher_space[inline_elements];
-
- /* pollset->mu already held */
- int added_worker = 0;
- int locked = 1;
- int queued_work = 0;
- int keep_polling = 0;
- /* this must happen before we (potentially) drop pollset->mu */
- worker.next = worker.prev = nullptr;
- worker.reevaluate_polling_on_wakeup = 0;
- if (pollset->local_wakeup_cache != nullptr) {
- worker.wakeup_fd = pollset->local_wakeup_cache;
- pollset->local_wakeup_cache = worker.wakeup_fd->next;
- } else {
- worker.wakeup_fd = static_cast<grpc_cached_wakeup_fd*>(
- gpr_malloc(sizeof(*worker.wakeup_fd)));
- error = grpc_wakeup_fd_init(&worker.wakeup_fd->fd);
+}
+
+static void work_combine_error(grpc_error** composite, grpc_error* error) {
+ if (error == GRPC_ERROR_NONE) return;
+ if (*composite == GRPC_ERROR_NONE) {
+ *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("pollset_work");
+ }
+ *composite = grpc_error_add_child(*composite, error);
+}
+
+static grpc_error* pollset_work(grpc_pollset* pollset,
+ grpc_pollset_worker** worker_hdl,
+ grpc_millis deadline) {
+ GPR_TIMER_SCOPE("pollset_work", 0);
+ grpc_pollset_worker worker;
+ if (worker_hdl) *worker_hdl = &worker;
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ /* Avoid malloc for small number of elements. */
+ enum { inline_elements = 96 };
+ struct pollfd pollfd_space[inline_elements];
+ struct grpc_fd_watcher watcher_space[inline_elements];
+
+ /* pollset->mu already held */
+ int added_worker = 0;
+ int locked = 1;
+ int queued_work = 0;
+ int keep_polling = 0;
+ /* this must happen before we (potentially) drop pollset->mu */
+ worker.next = worker.prev = nullptr;
+ worker.reevaluate_polling_on_wakeup = 0;
+ if (pollset->local_wakeup_cache != nullptr) {
+ worker.wakeup_fd = pollset->local_wakeup_cache;
+ pollset->local_wakeup_cache = worker.wakeup_fd->next;
+ } else {
+ worker.wakeup_fd = static_cast<grpc_cached_wakeup_fd*>(
+ gpr_malloc(sizeof(*worker.wakeup_fd)));
+ error = grpc_wakeup_fd_init(&worker.wakeup_fd->fd);
fork_fd_list_add_wakeup_fd(worker.wakeup_fd);
- if (error != GRPC_ERROR_NONE) {
- GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error));
- return error;
- }
- }
- worker.kicked_specifically = 0;
- /* If we're shutting down then we don't execute any extended work */
- if (pollset->shutting_down) {
- GPR_TIMER_MARK("pollset_work.shutting_down", 0);
- goto done;
- }
- /* Start polling, and keep doing so while we're being asked to
- re-evaluate our pollers (this allows poll() based pollers to
- ensure they don't miss wakeups) */
- keep_polling = 1;
- gpr_tls_set(&g_current_thread_poller, (intptr_t)pollset);
- while (keep_polling) {
- keep_polling = 0;
- if (!pollset->kicked_without_pollers ||
- deadline <= grpc_core::ExecCtx::Get()->Now()) {
- if (!added_worker) {
- push_front_worker(pollset, &worker);
- added_worker = 1;
- gpr_tls_set(&g_current_thread_worker, (intptr_t)&worker);
- }
- GPR_TIMER_SCOPE("maybe_work_and_unlock", 0);
-#define POLLOUT_CHECK (POLLOUT | POLLHUP | POLLERR)
-#define POLLIN_CHECK (POLLIN | POLLHUP | POLLERR)
-
- int timeout;
- int r;
- size_t i, fd_count;
- nfds_t pfd_count;
- grpc_fd_watcher* watchers;
- struct pollfd* pfds;
-
- timeout = poll_deadline_to_millis_timeout(deadline);
-
- if (pollset->fd_count + 2 <= inline_elements) {
- pfds = pollfd_space;
- watchers = watcher_space;
- } else {
- /* Allocate one buffer to hold both pfds and watchers arrays */
- const size_t pfd_size = sizeof(*pfds) * (pollset->fd_count + 2);
- const size_t watch_size = sizeof(*watchers) * (pollset->fd_count + 2);
- void* buf = gpr_malloc(pfd_size + watch_size);
- pfds = static_cast<struct pollfd*>(buf);
- watchers = static_cast<grpc_fd_watcher*>(
- (void*)(static_cast<char*>(buf) + pfd_size));
- }
-
- fd_count = 0;
- pfd_count = 1;
- pfds[0].fd = GRPC_WAKEUP_FD_GET_READ_FD(&worker.wakeup_fd->fd);
- pfds[0].events = POLLIN;
- pfds[0].revents = 0;
- for (i = 0; i < pollset->fd_count; i++) {
- if (fd_is_orphaned(pollset->fds[i]) ||
- gpr_atm_no_barrier_load(&pollset->fds[i]->pollhup) == 1) {
- GRPC_FD_UNREF(pollset->fds[i], "multipoller");
- } else {
- pollset->fds[fd_count++] = pollset->fds[i];
- watchers[pfd_count].fd = pollset->fds[i];
- GRPC_FD_REF(watchers[pfd_count].fd, "multipoller_start");
- pfds[pfd_count].fd = pollset->fds[i]->fd;
- pfds[pfd_count].revents = 0;
- pfd_count++;
- }
- }
- pollset->fd_count = fd_count;
- gpr_mu_unlock(&pollset->mu);
-
- for (i = 1; i < pfd_count; i++) {
- grpc_fd* fd = watchers[i].fd;
- pfds[i].events = static_cast<short>(
- fd_begin_poll(fd, pollset, &worker, POLLIN, POLLOUT, &watchers[i]));
- GRPC_FD_UNREF(fd, "multipoller_start");
- }
-
- /* TODO(vpai): Consider first doing a 0 timeout poll here to avoid
- even going into the blocking annotation if possible */
- GRPC_SCHEDULING_START_BLOCKING_REGION;
- GRPC_STATS_INC_SYSCALL_POLL();
- r = grpc_poll_function(pfds, pfd_count, timeout);
- GRPC_SCHEDULING_END_BLOCKING_REGION;
-
+ if (error != GRPC_ERROR_NONE) {
+ GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error));
+ return error;
+ }
+ }
+ worker.kicked_specifically = 0;
+ /* If we're shutting down then we don't execute any extended work */
+ if (pollset->shutting_down) {
+ GPR_TIMER_MARK("pollset_work.shutting_down", 0);
+ goto done;
+ }
+ /* Start polling, and keep doing so while we're being asked to
+ re-evaluate our pollers (this allows poll() based pollers to
+ ensure they don't miss wakeups) */
+ keep_polling = 1;
+ gpr_tls_set(&g_current_thread_poller, (intptr_t)pollset);
+ while (keep_polling) {
+ keep_polling = 0;
+ if (!pollset->kicked_without_pollers ||
+ deadline <= grpc_core::ExecCtx::Get()->Now()) {
+ if (!added_worker) {
+ push_front_worker(pollset, &worker);
+ added_worker = 1;
+ gpr_tls_set(&g_current_thread_worker, (intptr_t)&worker);
+ }
+ GPR_TIMER_SCOPE("maybe_work_and_unlock", 0);
+#define POLLOUT_CHECK (POLLOUT | POLLHUP | POLLERR)
+#define POLLIN_CHECK (POLLIN | POLLHUP | POLLERR)
+
+ int timeout;
+ int r;
+ size_t i, fd_count;
+ nfds_t pfd_count;
+ grpc_fd_watcher* watchers;
+ struct pollfd* pfds;
+
+ timeout = poll_deadline_to_millis_timeout(deadline);
+
+ if (pollset->fd_count + 2 <= inline_elements) {
+ pfds = pollfd_space;
+ watchers = watcher_space;
+ } else {
+ /* Allocate one buffer to hold both pfds and watchers arrays */
+ const size_t pfd_size = sizeof(*pfds) * (pollset->fd_count + 2);
+ const size_t watch_size = sizeof(*watchers) * (pollset->fd_count + 2);
+ void* buf = gpr_malloc(pfd_size + watch_size);
+ pfds = static_cast<struct pollfd*>(buf);
+ watchers = static_cast<grpc_fd_watcher*>(
+ (void*)(static_cast<char*>(buf) + pfd_size));
+ }
+
+ fd_count = 0;
+ pfd_count = 1;
+ pfds[0].fd = GRPC_WAKEUP_FD_GET_READ_FD(&worker.wakeup_fd->fd);
+ pfds[0].events = POLLIN;
+ pfds[0].revents = 0;
+ for (i = 0; i < pollset->fd_count; i++) {
+ if (fd_is_orphaned(pollset->fds[i]) ||
+ gpr_atm_no_barrier_load(&pollset->fds[i]->pollhup) == 1) {
+ GRPC_FD_UNREF(pollset->fds[i], "multipoller");
+ } else {
+ pollset->fds[fd_count++] = pollset->fds[i];
+ watchers[pfd_count].fd = pollset->fds[i];
+ GRPC_FD_REF(watchers[pfd_count].fd, "multipoller_start");
+ pfds[pfd_count].fd = pollset->fds[i]->fd;
+ pfds[pfd_count].revents = 0;
+ pfd_count++;
+ }
+ }
+ pollset->fd_count = fd_count;
+ gpr_mu_unlock(&pollset->mu);
+
+ for (i = 1; i < pfd_count; i++) {
+ grpc_fd* fd = watchers[i].fd;
+ pfds[i].events = static_cast<short>(
+ fd_begin_poll(fd, pollset, &worker, POLLIN, POLLOUT, &watchers[i]));
+ GRPC_FD_UNREF(fd, "multipoller_start");
+ }
+
+ /* TODO(vpai): Consider first doing a 0 timeout poll here to avoid
+ even going into the blocking annotation if possible */
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
+ GRPC_STATS_INC_SYSCALL_POLL();
+ r = grpc_poll_function(pfds, pfd_count, timeout);
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "%p poll=%d", pollset, r);
- }
-
- if (r < 0) {
- if (errno != EINTR) {
- work_combine_error(&error, GRPC_OS_ERROR(errno, "poll"));
- }
-
- for (i = 1; i < pfd_count; i++) {
- if (watchers[i].fd == nullptr) {
+ gpr_log(GPR_INFO, "%p poll=%d", pollset, r);
+ }
+
+ if (r < 0) {
+ if (errno != EINTR) {
+ work_combine_error(&error, GRPC_OS_ERROR(errno, "poll"));
+ }
+
+ for (i = 1; i < pfd_count; i++) {
+ if (watchers[i].fd == nullptr) {
fd_end_poll(&watchers[i], 0, 0);
- } else {
- // Wake up all the file descriptors, if we have an invalid one
- // we can identify it on the next pollset_work()
+ } else {
+ // Wake up all the file descriptors, if we have an invalid one
+ // we can identify it on the next pollset_work()
fd_end_poll(&watchers[i], 1, 1);
- }
- }
- } else if (r == 0) {
- for (i = 1; i < pfd_count; i++) {
+ }
+ }
+ } else if (r == 0) {
+ for (i = 1; i < pfd_count; i++) {
fd_end_poll(&watchers[i], 0, 0);
- }
- } else {
- if (pfds[0].revents & POLLIN_CHECK) {
+ }
+ } else {
+ if (pfds[0].revents & POLLIN_CHECK) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
- gpr_log(GPR_INFO, "%p: got_wakeup", pollset);
- }
- work_combine_error(
- &error, grpc_wakeup_fd_consume_wakeup(&worker.wakeup_fd->fd));
- }
- for (i = 1; i < pfd_count; i++) {
- if (watchers[i].fd == nullptr) {
+ gpr_log(GPR_INFO, "%p: got_wakeup", pollset);
+ }
+ work_combine_error(
+ &error, grpc_wakeup_fd_consume_wakeup(&worker.wakeup_fd->fd));
+ }
+ for (i = 1; i < pfd_count; i++) {
+ if (watchers[i].fd == nullptr) {
fd_end_poll(&watchers[i], 0, 0);
- } else {
+ } else {
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);
- }
- /* This is a mitigation to prevent poll() from spinning on a
- ** POLLHUP https://github.com/grpc/grpc/pull/13665
- */
- if (pfds[i].revents & POLLHUP) {
- gpr_atm_no_barrier_store(&watchers[i].fd->pollhup, 1);
- }
- fd_end_poll(&watchers[i], pfds[i].revents & POLLIN_CHECK,
+ 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);
+ }
+ /* This is a mitigation to prevent poll() from spinning on a
+ ** POLLHUP https://github.com/grpc/grpc/pull/13665
+ */
+ if (pfds[i].revents & POLLHUP) {
+ gpr_atm_no_barrier_store(&watchers[i].fd->pollhup, 1);
+ }
+ fd_end_poll(&watchers[i], pfds[i].revents & POLLIN_CHECK,
pfds[i].revents & POLLOUT_CHECK);
- }
- }
- }
-
- if (pfds != pollfd_space) {
- /* pfds and watchers are in the same memory block pointed to by pfds */
- gpr_free(pfds);
- }
-
- locked = 0;
- } else {
- GPR_TIMER_MARK("pollset_work.kicked_without_pollers", 0);
- pollset->kicked_without_pollers = 0;
- }
- /* Finished execution - start cleaning up.
- Note that we may arrive here from outside the enclosing while() loop.
- In that case we won't loop though as we haven't added worker to the
- worker list, which means nobody could ask us to re-evaluate polling). */
- done:
- if (!locked) {
- queued_work |= grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(&pollset->mu);
- locked = 1;
- }
- /* If we're forced to re-evaluate polling (via pollset_kick with
- GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) then we land here and force
- a loop */
- if (worker.reevaluate_polling_on_wakeup && error == GRPC_ERROR_NONE) {
- worker.reevaluate_polling_on_wakeup = 0;
- pollset->kicked_without_pollers = 0;
- if (queued_work || worker.kicked_specifically) {
- /* If there's queued work on the list, then set the deadline to be
- immediate so we get back out of the polling loop quickly */
- deadline = 0;
- }
- keep_polling = 1;
- }
- }
- gpr_tls_set(&g_current_thread_poller, 0);
- if (added_worker) {
- remove_worker(pollset, &worker);
- gpr_tls_set(&g_current_thread_worker, 0);
- }
- /* release wakeup fd to the local pool */
- worker.wakeup_fd->next = pollset->local_wakeup_cache;
- pollset->local_wakeup_cache = worker.wakeup_fd;
- /* check shutdown conditions */
- if (pollset->shutting_down) {
- if (pollset_has_workers(pollset)) {
- pollset_kick(pollset, nullptr);
- } else if (!pollset->called_shutdown && !pollset_has_observers(pollset)) {
- pollset->called_shutdown = 1;
- gpr_mu_unlock(&pollset->mu);
- finish_shutdown(pollset);
- grpc_core::ExecCtx::Get()->Flush();
- /* Continuing to access pollset here is safe -- it is the caller's
- * responsibility to not destroy when it has outstanding calls to
- * pollset_work.
- * TODO(dklempner): Can we refactor the shutdown logic to avoid this? */
- gpr_mu_lock(&pollset->mu);
- }
- }
- if (worker_hdl) *worker_hdl = nullptr;
- GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error));
- return error;
-}
-
-static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
- GPR_ASSERT(!pollset->shutting_down);
- pollset->shutting_down = 1;
- pollset->shutdown_done = closure;
- pollset_kick(pollset, GRPC_POLLSET_KICK_BROADCAST);
- if (!pollset->called_shutdown && !pollset_has_observers(pollset)) {
- pollset->called_shutdown = 1;
- finish_shutdown(pollset);
- }
-}
-
-static int poll_deadline_to_millis_timeout(grpc_millis deadline) {
- if (deadline == GRPC_MILLIS_INF_FUTURE) return -1;
- if (deadline == 0) return 0;
- grpc_millis n = deadline - grpc_core::ExecCtx::Get()->Now();
- if (n < 0) return 0;
- if (n > INT_MAX) return -1;
- return static_cast<int>(n);
-}
-
-/*******************************************************************************
- * pollset_set_posix.c
- */
-
-static grpc_pollset_set* pollset_set_create(void) {
- grpc_pollset_set* pollset_set =
- static_cast<grpc_pollset_set*>(gpr_zalloc(sizeof(*pollset_set)));
- gpr_mu_init(&pollset_set->mu);
- return pollset_set;
-}
-
-static void pollset_set_destroy(grpc_pollset_set* pollset_set) {
- size_t i;
- gpr_mu_destroy(&pollset_set->mu);
- for (i = 0; i < pollset_set->fd_count; i++) {
- GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
- }
- for (i = 0; i < pollset_set->pollset_count; i++) {
- grpc_pollset* pollset = pollset_set->pollsets[i];
- gpr_mu_lock(&pollset->mu);
- pollset->pollset_set_count--;
- /* check shutdown */
- if (pollset->shutting_down && !pollset->called_shutdown &&
- !pollset_has_observers(pollset)) {
- pollset->called_shutdown = 1;
- gpr_mu_unlock(&pollset->mu);
- finish_shutdown(pollset);
- } else {
- gpr_mu_unlock(&pollset->mu);
- }
- }
- gpr_free(pollset_set->pollsets);
- gpr_free(pollset_set->pollset_sets);
- gpr_free(pollset_set->fds);
- gpr_free(pollset_set);
-}
-
-static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {
- size_t i, j;
- gpr_mu_lock(&pollset->mu);
- pollset->pollset_set_count++;
- gpr_mu_unlock(&pollset->mu);
- gpr_mu_lock(&pollset_set->mu);
- if (pollset_set->pollset_count == pollset_set->pollset_capacity) {
- pollset_set->pollset_capacity =
- GPR_MAX(8, 2 * pollset_set->pollset_capacity);
- pollset_set->pollsets = static_cast<grpc_pollset**>(gpr_realloc(
- pollset_set->pollsets,
- pollset_set->pollset_capacity * sizeof(*pollset_set->pollsets)));
- }
- pollset_set->pollsets[pollset_set->pollset_count++] = pollset;
- for (i = 0, j = 0; i < pollset_set->fd_count; i++) {
- if (fd_is_orphaned(pollset_set->fds[i])) {
- GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
- } else {
- pollset_add_fd(pollset, pollset_set->fds[i]);
- pollset_set->fds[j++] = pollset_set->fds[i];
- }
- }
- pollset_set->fd_count = j;
- gpr_mu_unlock(&pollset_set->mu);
-}
-
-static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {
- size_t i;
- gpr_mu_lock(&pollset_set->mu);
- for (i = 0; i < pollset_set->pollset_count; i++) {
- if (pollset_set->pollsets[i] == pollset) {
- pollset_set->pollset_count--;
- GPR_SWAP(grpc_pollset*, pollset_set->pollsets[i],
- pollset_set->pollsets[pollset_set->pollset_count]);
- break;
- }
- }
- gpr_mu_unlock(&pollset_set->mu);
- gpr_mu_lock(&pollset->mu);
- pollset->pollset_set_count--;
- /* check shutdown */
- if (pollset->shutting_down && !pollset->called_shutdown &&
- !pollset_has_observers(pollset)) {
- pollset->called_shutdown = 1;
- gpr_mu_unlock(&pollset->mu);
- finish_shutdown(pollset);
- } else {
- gpr_mu_unlock(&pollset->mu);
- }
-}
-
-static void pollset_set_add_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item) {
- size_t i, j;
- gpr_mu_lock(&bag->mu);
- if (bag->pollset_set_count == bag->pollset_set_capacity) {
- bag->pollset_set_capacity = GPR_MAX(8, 2 * bag->pollset_set_capacity);
- bag->pollset_sets = static_cast<grpc_pollset_set**>(
- gpr_realloc(bag->pollset_sets,
- bag->pollset_set_capacity * sizeof(*bag->pollset_sets)));
- }
- bag->pollset_sets[bag->pollset_set_count++] = item;
- for (i = 0, j = 0; i < bag->fd_count; i++) {
- if (fd_is_orphaned(bag->fds[i])) {
- GRPC_FD_UNREF(bag->fds[i], "pollset_set");
- } else {
- pollset_set_add_fd(item, bag->fds[i]);
- bag->fds[j++] = bag->fds[i];
- }
- }
- bag->fd_count = j;
- gpr_mu_unlock(&bag->mu);
-}
-
-static void pollset_set_del_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item) {
- size_t i;
- gpr_mu_lock(&bag->mu);
- for (i = 0; i < bag->pollset_set_count; i++) {
- if (bag->pollset_sets[i] == item) {
- bag->pollset_set_count--;
- GPR_SWAP(grpc_pollset_set*, bag->pollset_sets[i],
- bag->pollset_sets[bag->pollset_set_count]);
- break;
- }
- }
- gpr_mu_unlock(&bag->mu);
-}
-
-static void pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
- size_t i;
- gpr_mu_lock(&pollset_set->mu);
- if (pollset_set->fd_count == pollset_set->fd_capacity) {
- pollset_set->fd_capacity = GPR_MAX(8, 2 * pollset_set->fd_capacity);
- pollset_set->fds = static_cast<grpc_fd**>(
- gpr_realloc(pollset_set->fds,
- pollset_set->fd_capacity * sizeof(*pollset_set->fds)));
- }
- GRPC_FD_REF(fd, "pollset_set");
- pollset_set->fds[pollset_set->fd_count++] = fd;
- for (i = 0; i < pollset_set->pollset_count; i++) {
- pollset_add_fd(pollset_set->pollsets[i], fd);
- }
- for (i = 0; i < pollset_set->pollset_set_count; i++) {
- pollset_set_add_fd(pollset_set->pollset_sets[i], fd);
- }
- gpr_mu_unlock(&pollset_set->mu);
-}
-
-static void pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
- size_t i;
- gpr_mu_lock(&pollset_set->mu);
- for (i = 0; i < pollset_set->fd_count; i++) {
- if (pollset_set->fds[i] == fd) {
- pollset_set->fd_count--;
- GPR_SWAP(grpc_fd*, pollset_set->fds[i],
- pollset_set->fds[pollset_set->fd_count]);
- GRPC_FD_UNREF(fd, "pollset_set");
- break;
- }
- }
- for (i = 0; i < pollset_set->pollset_set_count; i++) {
- pollset_set_del_fd(pollset_set->pollset_sets[i], fd);
- }
- gpr_mu_unlock(&pollset_set->mu);
-}
-
-/*******************************************************************************
- * event engine binding
- */
-
+ }
+ }
+ }
+
+ if (pfds != pollfd_space) {
+ /* pfds and watchers are in the same memory block pointed to by pfds */
+ gpr_free(pfds);
+ }
+
+ locked = 0;
+ } else {
+ GPR_TIMER_MARK("pollset_work.kicked_without_pollers", 0);
+ pollset->kicked_without_pollers = 0;
+ }
+ /* Finished execution - start cleaning up.
+ Note that we may arrive here from outside the enclosing while() loop.
+ In that case we won't loop though as we haven't added worker to the
+ worker list, which means nobody could ask us to re-evaluate polling). */
+ done:
+ if (!locked) {
+ queued_work |= grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(&pollset->mu);
+ locked = 1;
+ }
+ /* If we're forced to re-evaluate polling (via pollset_kick with
+ GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) then we land here and force
+ a loop */
+ if (worker.reevaluate_polling_on_wakeup && error == GRPC_ERROR_NONE) {
+ worker.reevaluate_polling_on_wakeup = 0;
+ pollset->kicked_without_pollers = 0;
+ if (queued_work || worker.kicked_specifically) {
+ /* If there's queued work on the list, then set the deadline to be
+ immediate so we get back out of the polling loop quickly */
+ deadline = 0;
+ }
+ keep_polling = 1;
+ }
+ }
+ gpr_tls_set(&g_current_thread_poller, 0);
+ if (added_worker) {
+ remove_worker(pollset, &worker);
+ gpr_tls_set(&g_current_thread_worker, 0);
+ }
+ /* release wakeup fd to the local pool */
+ worker.wakeup_fd->next = pollset->local_wakeup_cache;
+ pollset->local_wakeup_cache = worker.wakeup_fd;
+ /* check shutdown conditions */
+ if (pollset->shutting_down) {
+ if (pollset_has_workers(pollset)) {
+ pollset_kick(pollset, nullptr);
+ } else if (!pollset->called_shutdown && !pollset_has_observers(pollset)) {
+ pollset->called_shutdown = 1;
+ gpr_mu_unlock(&pollset->mu);
+ finish_shutdown(pollset);
+ grpc_core::ExecCtx::Get()->Flush();
+ /* Continuing to access pollset here is safe -- it is the caller's
+ * responsibility to not destroy when it has outstanding calls to
+ * pollset_work.
+ * TODO(dklempner): Can we refactor the shutdown logic to avoid this? */
+ gpr_mu_lock(&pollset->mu);
+ }
+ }
+ if (worker_hdl) *worker_hdl = nullptr;
+ GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error));
+ return error;
+}
+
+static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
+ GPR_ASSERT(!pollset->shutting_down);
+ pollset->shutting_down = 1;
+ pollset->shutdown_done = closure;
+ pollset_kick(pollset, GRPC_POLLSET_KICK_BROADCAST);
+ if (!pollset->called_shutdown && !pollset_has_observers(pollset)) {
+ pollset->called_shutdown = 1;
+ finish_shutdown(pollset);
+ }
+}
+
+static int poll_deadline_to_millis_timeout(grpc_millis deadline) {
+ if (deadline == GRPC_MILLIS_INF_FUTURE) return -1;
+ if (deadline == 0) return 0;
+ grpc_millis n = deadline - grpc_core::ExecCtx::Get()->Now();
+ if (n < 0) return 0;
+ if (n > INT_MAX) return -1;
+ return static_cast<int>(n);
+}
+
+/*******************************************************************************
+ * pollset_set_posix.c
+ */
+
+static grpc_pollset_set* pollset_set_create(void) {
+ grpc_pollset_set* pollset_set =
+ static_cast<grpc_pollset_set*>(gpr_zalloc(sizeof(*pollset_set)));
+ gpr_mu_init(&pollset_set->mu);
+ return pollset_set;
+}
+
+static void pollset_set_destroy(grpc_pollset_set* pollset_set) {
+ size_t i;
+ gpr_mu_destroy(&pollset_set->mu);
+ for (i = 0; i < pollset_set->fd_count; i++) {
+ GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
+ }
+ for (i = 0; i < pollset_set->pollset_count; i++) {
+ grpc_pollset* pollset = pollset_set->pollsets[i];
+ gpr_mu_lock(&pollset->mu);
+ pollset->pollset_set_count--;
+ /* check shutdown */
+ if (pollset->shutting_down && !pollset->called_shutdown &&
+ !pollset_has_observers(pollset)) {
+ pollset->called_shutdown = 1;
+ gpr_mu_unlock(&pollset->mu);
+ finish_shutdown(pollset);
+ } else {
+ gpr_mu_unlock(&pollset->mu);
+ }
+ }
+ gpr_free(pollset_set->pollsets);
+ gpr_free(pollset_set->pollset_sets);
+ gpr_free(pollset_set->fds);
+ gpr_free(pollset_set);
+}
+
+static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {
+ size_t i, j;
+ gpr_mu_lock(&pollset->mu);
+ pollset->pollset_set_count++;
+ gpr_mu_unlock(&pollset->mu);
+ gpr_mu_lock(&pollset_set->mu);
+ if (pollset_set->pollset_count == pollset_set->pollset_capacity) {
+ pollset_set->pollset_capacity =
+ GPR_MAX(8, 2 * pollset_set->pollset_capacity);
+ pollset_set->pollsets = static_cast<grpc_pollset**>(gpr_realloc(
+ pollset_set->pollsets,
+ pollset_set->pollset_capacity * sizeof(*pollset_set->pollsets)));
+ }
+ pollset_set->pollsets[pollset_set->pollset_count++] = pollset;
+ for (i = 0, j = 0; i < pollset_set->fd_count; i++) {
+ if (fd_is_orphaned(pollset_set->fds[i])) {
+ GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
+ } else {
+ pollset_add_fd(pollset, pollset_set->fds[i]);
+ pollset_set->fds[j++] = pollset_set->fds[i];
+ }
+ }
+ pollset_set->fd_count = j;
+ gpr_mu_unlock(&pollset_set->mu);
+}
+
+static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {
+ size_t i;
+ gpr_mu_lock(&pollset_set->mu);
+ for (i = 0; i < pollset_set->pollset_count; i++) {
+ if (pollset_set->pollsets[i] == pollset) {
+ pollset_set->pollset_count--;
+ GPR_SWAP(grpc_pollset*, pollset_set->pollsets[i],
+ pollset_set->pollsets[pollset_set->pollset_count]);
+ break;
+ }
+ }
+ gpr_mu_unlock(&pollset_set->mu);
+ gpr_mu_lock(&pollset->mu);
+ pollset->pollset_set_count--;
+ /* check shutdown */
+ if (pollset->shutting_down && !pollset->called_shutdown &&
+ !pollset_has_observers(pollset)) {
+ pollset->called_shutdown = 1;
+ gpr_mu_unlock(&pollset->mu);
+ finish_shutdown(pollset);
+ } else {
+ gpr_mu_unlock(&pollset->mu);
+ }
+}
+
+static void pollset_set_add_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item) {
+ size_t i, j;
+ gpr_mu_lock(&bag->mu);
+ if (bag->pollset_set_count == bag->pollset_set_capacity) {
+ bag->pollset_set_capacity = GPR_MAX(8, 2 * bag->pollset_set_capacity);
+ bag->pollset_sets = static_cast<grpc_pollset_set**>(
+ gpr_realloc(bag->pollset_sets,
+ bag->pollset_set_capacity * sizeof(*bag->pollset_sets)));
+ }
+ bag->pollset_sets[bag->pollset_set_count++] = item;
+ for (i = 0, j = 0; i < bag->fd_count; i++) {
+ if (fd_is_orphaned(bag->fds[i])) {
+ GRPC_FD_UNREF(bag->fds[i], "pollset_set");
+ } else {
+ pollset_set_add_fd(item, bag->fds[i]);
+ bag->fds[j++] = bag->fds[i];
+ }
+ }
+ bag->fd_count = j;
+ gpr_mu_unlock(&bag->mu);
+}
+
+static void pollset_set_del_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item) {
+ size_t i;
+ gpr_mu_lock(&bag->mu);
+ for (i = 0; i < bag->pollset_set_count; i++) {
+ if (bag->pollset_sets[i] == item) {
+ bag->pollset_set_count--;
+ GPR_SWAP(grpc_pollset_set*, bag->pollset_sets[i],
+ bag->pollset_sets[bag->pollset_set_count]);
+ break;
+ }
+ }
+ gpr_mu_unlock(&bag->mu);
+}
+
+static void pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
+ size_t i;
+ gpr_mu_lock(&pollset_set->mu);
+ if (pollset_set->fd_count == pollset_set->fd_capacity) {
+ pollset_set->fd_capacity = GPR_MAX(8, 2 * pollset_set->fd_capacity);
+ pollset_set->fds = static_cast<grpc_fd**>(
+ gpr_realloc(pollset_set->fds,
+ pollset_set->fd_capacity * sizeof(*pollset_set->fds)));
+ }
+ GRPC_FD_REF(fd, "pollset_set");
+ pollset_set->fds[pollset_set->fd_count++] = fd;
+ for (i = 0; i < pollset_set->pollset_count; i++) {
+ pollset_add_fd(pollset_set->pollsets[i], fd);
+ }
+ for (i = 0; i < pollset_set->pollset_set_count; i++) {
+ pollset_set_add_fd(pollset_set->pollset_sets[i], fd);
+ }
+ gpr_mu_unlock(&pollset_set->mu);
+}
+
+static void pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
+ size_t i;
+ gpr_mu_lock(&pollset_set->mu);
+ for (i = 0; i < pollset_set->fd_count; i++) {
+ if (pollset_set->fds[i] == fd) {
+ pollset_set->fd_count--;
+ GPR_SWAP(grpc_fd*, pollset_set->fds[i],
+ pollset_set->fds[pollset_set->fd_count]);
+ GRPC_FD_UNREF(fd, "pollset_set");
+ break;
+ }
+ }
+ for (i = 0; i < pollset_set->pollset_set_count; i++) {
+ pollset_set_del_fd(pollset_set->pollset_sets[i], fd);
+ }
+ gpr_mu_unlock(&pollset_set->mu);
+}
+
+/*******************************************************************************
+ * event engine binding
+ */
+
static bool is_any_background_poller_thread(void) { return false; }
static void shutdown_background_closure(void) {}
@@ -1338,53 +1338,53 @@ static bool add_closure_to_background_poller(grpc_closure* /*closure*/,
return false;
}
-static void shutdown_engine(void) {
- pollset_global_shutdown();
+static void shutdown_engine(void) {
+ pollset_global_shutdown();
if (track_fds_for_fork) {
gpr_mu_destroy(&fork_fd_list_mu);
grpc_core::Fork::SetResetChildPollingEngineFunc(nullptr);
}
-}
-
-static const grpc_event_engine_vtable vtable = {
- sizeof(grpc_pollset),
+}
+
+static const grpc_event_engine_vtable vtable = {
+ sizeof(grpc_pollset),
false,
false,
-
- fd_create,
- fd_wrapped_fd,
- fd_orphan,
- fd_shutdown,
- fd_notify_on_read,
- fd_notify_on_write,
+
+ fd_create,
+ fd_wrapped_fd,
+ fd_orphan,
+ fd_shutdown,
+ fd_notify_on_read,
+ fd_notify_on_write,
fd_notify_on_error,
fd_set_readable,
fd_set_writable,
fd_set_error,
- fd_is_shutdown,
-
- pollset_init,
- pollset_shutdown,
- pollset_destroy,
- pollset_work,
- pollset_kick,
- pollset_add_fd,
-
- pollset_set_create,
- pollset_set_destroy,
- pollset_set_add_pollset,
- pollset_set_del_pollset,
- pollset_set_add_pollset_set,
- pollset_set_del_pollset_set,
- pollset_set_add_fd,
- pollset_set_del_fd,
-
+ fd_is_shutdown,
+
+ pollset_init,
+ pollset_shutdown,
+ pollset_destroy,
+ pollset_work,
+ pollset_kick,
+ pollset_add_fd,
+
+ pollset_set_create,
+ pollset_set_destroy,
+ pollset_set_add_pollset,
+ pollset_set_del_pollset,
+ pollset_set_add_pollset_set,
+ pollset_set_del_pollset_set,
+ pollset_set_add_fd,
+ pollset_set_del_fd,
+
is_any_background_poller_thread,
shutdown_background_closure,
- shutdown_engine,
+ shutdown_engine,
add_closure_to_background_poller,
-};
-
+};
+
/* Called by the child process's post-fork handler to close open fds, including
* worker wakeup fds. This allows gRPC to shutdown in the child process without
* interfering with connections or RPCs ongoing in the parent. */
@@ -1409,20 +1409,20 @@ static void reset_event_manager_on_fork() {
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;
- }
- if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
- return nullptr;
- }
+ if (!grpc_has_wakeup_fd()) {
+ gpr_log(GPR_ERROR, "Skipping poll because of no wakeup fd.");
+ return nullptr;
+ }
+ if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
+ return nullptr;
+ }
if (grpc_core::Fork::Enabled()) {
track_fds_for_fork = true;
gpr_mu_init(&fork_fd_list_mu);
grpc_core::Fork::SetResetChildPollingEngineFunc(
reset_event_manager_on_fork);
}
- return &vtable;
-}
-
+ return &vtable;
+}
+
#endif /* GRPC_POSIX_SOCKET_EV_POLL */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.h
index ab3cd9029e6..ca88fed359b 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.h
@@ -1,29 +1,29 @@
/*
*
- * Copyright 2015-2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_EV_POLL_POSIX_H
#define GRPC_CORE_LIB_IOMGR_EV_POLL_POSIX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/ev_posix.h"
-const grpc_event_engine_vtable* grpc_init_poll_posix(bool explicit_request);
-const grpc_event_engine_vtable* grpc_init_poll_cv_posix(bool explicit_request);
+const grpc_event_engine_vtable* grpc_init_poll_posix(bool explicit_request);
+const grpc_event_engine_vtable* grpc_init_poll_cv_posix(bool explicit_request);
#endif /* GRPC_CORE_LIB_IOMGR_EV_POLL_POSIX_H */
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 3d32359be46..4d481ffdcef 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/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/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_EV
-
-#include "src/core/lib/iomgr/ev_posix.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gpr/useful.h"
+
+#include "src/core/lib/iomgr/ev_posix.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#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/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/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. "
@@ -49,69 +49,69 @@ grpc_core::DebugOnlyTraceFlag grpc_polling_trace(
/* Traces fd create/close operations */
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");
-
+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
-#ifndef NDEBUG
-#define GRPC_POLLING_API_TRACE(format, ...) \
+#ifndef NDEBUG
+#define GRPC_POLLING_API_TRACE(format, ...) \
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_api_trace)) { \
- gpr_log(GPR_INFO, "(polling-api) " format, __VA_ARGS__); \
- }
-#else
-#define GRPC_POLLING_API_TRACE(...)
+ gpr_log(GPR_INFO, "(polling-api) " format, __VA_ARGS__); \
+ }
+#else
+#define GRPC_POLLING_API_TRACE(...)
#endif // NDEBUG
-
-/** Default poll() function - a pointer so that it can be overridden by some
- * tests */
+
+/** Default poll() function - a pointer so that it can be overridden by some
+ * tests */
#ifndef GPR_AIX
-grpc_poll_function_type grpc_poll_function = poll;
+grpc_poll_function_type grpc_poll_function = poll;
#else
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
-
-grpc_wakeup_fd grpc_global_wakeup_fd;
-
-static const grpc_event_engine_vtable* g_event_engine = nullptr;
-static const char* g_poll_strategy_name = nullptr;
-
-typedef const grpc_event_engine_vtable* (*event_engine_factory_fn)(
- bool explicit_request);
-
+
+grpc_wakeup_fd grpc_global_wakeup_fd;
+
+static const grpc_event_engine_vtable* g_event_engine = nullptr;
+static const char* g_poll_strategy_name = nullptr;
+
+typedef const grpc_event_engine_vtable* (*event_engine_factory_fn)(
+ bool explicit_request);
+
struct event_engine_factory {
- const char* name;
- event_engine_factory_fn factory;
+ const char* name;
+ event_engine_factory_fn factory;
};
-namespace {
-
-grpc_poll_function_type real_poll_function;
-
-int dummy_poll(struct pollfd fds[], nfds_t nfds, int timeout) {
- if (timeout == 0) {
- return real_poll_function(fds, nfds, 0);
- } else {
- gpr_log(GPR_ERROR, "Attempted a blocking poll when declared non-polling.");
- GPR_ASSERT(false);
- return -1;
- }
-}
-
-const grpc_event_engine_vtable* init_non_polling(bool explicit_request) {
- if (!explicit_request) {
- return nullptr;
- }
- // return the simplest engine as a dummy but also override the poller
- auto ret = grpc_init_poll_posix(explicit_request);
- real_poll_function = grpc_poll_function;
- grpc_poll_function = dummy_poll;
-
- return ret;
-}
-} // namespace
-
+namespace {
+
+grpc_poll_function_type real_poll_function;
+
+int dummy_poll(struct pollfd fds[], nfds_t nfds, int timeout) {
+ if (timeout == 0) {
+ return real_poll_function(fds, nfds, 0);
+ } else {
+ gpr_log(GPR_ERROR, "Attempted a blocking poll when declared non-polling.");
+ GPR_ASSERT(false);
+ return -1;
+ }
+}
+
+const grpc_event_engine_vtable* init_non_polling(bool explicit_request) {
+ if (!explicit_request) {
+ return nullptr;
+ }
+ // return the simplest engine as a dummy but also override the poller
+ auto ret = grpc_init_poll_posix(explicit_request);
+ real_poll_function = grpc_poll_function;
+ grpc_poll_function = dummy_poll;
+
+ return ret;
+}
+} // namespace
+
#define ENGINE_HEAD_CUSTOM "head_custom"
#define ENGINE_TAIL_CUSTOM "tail_custom"
@@ -133,57 +133,57 @@ static event_engine_factory g_factories[] = {
{"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) {
- size_t n = *ns;
- size_t np = n + 1;
- char* s;
- size_t len;
- GPR_ASSERT(end >= beg);
- len = static_cast<size_t>(end - beg);
- s = static_cast<char*>(gpr_malloc(len + 1));
- memcpy(s, beg, len);
- s[len] = 0;
- *ss = static_cast<char**>(gpr_realloc(*ss, sizeof(char**) * np));
- (*ss)[n] = s;
- *ns = np;
-}
-
-static void split(const char* s, char*** ss, size_t* ns) {
- const char* c = strchr(s, ',');
- if (c == nullptr) {
- add(s, s + strlen(s), ss, ns);
- } else {
- add(s, c, ss, ns);
- split(c + 1, ss, ns);
- }
-}
-
-static bool is(const char* want, const char* have) {
- return 0 == strcmp(want, "all") || 0 == strcmp(want, have);
-}
-
-static void try_engine(const char* engine) {
- for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
+};
+
+static void add(const char* beg, const char* end, char*** ss, size_t* ns) {
+ size_t n = *ns;
+ size_t np = n + 1;
+ char* s;
+ size_t len;
+ GPR_ASSERT(end >= beg);
+ len = static_cast<size_t>(end - beg);
+ s = static_cast<char*>(gpr_malloc(len + 1));
+ memcpy(s, beg, len);
+ s[len] = 0;
+ *ss = static_cast<char**>(gpr_realloc(*ss, sizeof(char**) * np));
+ (*ss)[n] = s;
+ *ns = np;
+}
+
+static void split(const char* s, char*** ss, size_t* ns) {
+ const char* c = strchr(s, ',');
+ if (c == nullptr) {
+ add(s, s + strlen(s), ss, ns);
+ } else {
+ add(s, c, ss, ns);
+ split(c + 1, ss, ns);
+ }
+}
+
+static bool is(const char* want, const char* have) {
+ return 0 == strcmp(want, "all") || 0 == strcmp(want, have);
+}
+
+static void try_engine(const char* engine) {
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
if (g_factories[i].factory != nullptr && is(engine, g_factories[i].name)) {
- if ((g_event_engine = g_factories[i].factory(
- 0 == strcmp(engine, g_factories[i].name)))) {
- g_poll_strategy_name = g_factories[i].name;
- gpr_log(GPR_DEBUG, "Using polling engine: %s", g_factories[i].name);
- return;
- }
- }
- }
-}
-
+ if ((g_event_engine = g_factories[i].factory(
+ 0 == strcmp(engine, g_factories[i].name)))) {
+ g_poll_strategy_name = g_factories[i].name;
+ gpr_log(GPR_DEBUG, "Using polling engine: %s", g_factories[i].name);
+ return;
+ }
+ }
+ }
+}
+
/* Call this before calling grpc_event_engine_init() */
void grpc_register_event_engine_factory(const char* name,
event_engine_factory_fn factory,
bool add_at_head) {
const char* custom_match =
add_at_head ? ENGINE_HEAD_CUSTOM : ENGINE_TAIL_CUSTOM;
-
+
// Overwrite an existing registration if already registered
for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
if (0 == strcmp(name, g_factories[i].name)) {
@@ -203,48 +203,48 @@ void grpc_register_event_engine_factory(const char* name,
// Otherwise fail
GPR_ASSERT(false);
-}
-
+}
+
/*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) {
+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);
-
- char** strings = nullptr;
- size_t nstrings = 0;
+
+ char** strings = nullptr;
+ size_t nstrings = 0;
split(value.get(), &strings, &nstrings);
-
- for (size_t i = 0; g_event_engine == nullptr && i < nstrings; i++) {
- try_engine(strings[i]);
- }
-
- for (size_t i = 0; i < nstrings; i++) {
- gpr_free(strings[i]);
- }
- gpr_free(strings);
-
- if (g_event_engine == nullptr) {
+
+ for (size_t i = 0; g_event_engine == nullptr && i < nstrings; i++) {
+ try_engine(strings[i]);
+ }
+
+ for (size_t i = 0; i < nstrings; i++) {
+ gpr_free(strings[i]);
+ }
+ gpr_free(strings);
+
+ if (g_event_engine == nullptr) {
gpr_log(GPR_ERROR, "No event engine could be initialized from %s",
value.get());
- abort();
- }
-}
-
-void grpc_event_engine_shutdown(void) {
- g_event_engine->shutdown_engine();
- g_event_engine = nullptr;
-}
-
+ abort();
+ }
+}
+
+void grpc_event_engine_shutdown(void) {
+ g_event_engine->shutdown_engine();
+ g_event_engine = nullptr;
+}
+
bool grpc_event_engine_can_track_errors(void) {
/* Only track errors if platform supports errqueue. */
if (grpc_core::kernel_supports_errqueue()) {
return g_event_engine->can_track_err;
}
return false;
-}
-
+}
+
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;
@@ -257,37 +257,37 @@ grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err) {
fd, name, track_err && grpc_event_engine_can_track_errors());
}
-int grpc_fd_wrapped_fd(grpc_fd* fd) {
- return g_event_engine->fd_wrapped_fd(fd);
-}
-
-void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
+int grpc_fd_wrapped_fd(grpc_fd* fd) {
+ return g_event_engine->fd_wrapped_fd(fd);
+}
+
+void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
const char* reason) {
GRPC_POLLING_API_TRACE("fd_orphan(%d, %p, %p, %s)", grpc_fd_wrapped_fd(fd),
on_done, release_fd, reason);
GRPC_FD_TRACE("grpc_fd_orphan, fd:%d closed", grpc_fd_wrapped_fd(fd));
g_event_engine->fd_orphan(fd, on_done, release_fd, reason);
-}
-
-void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why) {
- GRPC_POLLING_API_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd));
+}
+
+void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why) {
+ GRPC_POLLING_API_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd));
GRPC_FD_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd));
- g_event_engine->fd_shutdown(fd, why);
-}
-
-bool grpc_fd_is_shutdown(grpc_fd* fd) {
- return g_event_engine->fd_is_shutdown(fd);
-}
-
-void grpc_fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
- g_event_engine->fd_notify_on_read(fd, closure);
-}
-
-void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
- g_event_engine->fd_notify_on_write(fd, closure);
-}
-
+ g_event_engine->fd_shutdown(fd, why);
+}
+
+bool grpc_fd_is_shutdown(grpc_fd* fd) {
+ return g_event_engine->fd_is_shutdown(fd);
+}
+
+void grpc_fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
+ g_event_engine->fd_notify_on_read(fd, closure);
+}
+
+void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
+ g_event_engine->fd_notify_on_write(fd, closure);
+}
+
void grpc_fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) {
g_event_engine->fd_notify_on_error(fd, closure);
}
@@ -298,109 +298,109 @@ void grpc_fd_set_writable(grpc_fd* fd) { g_event_engine->fd_set_writable(fd); }
void grpc_fd_set_error(grpc_fd* fd) { g_event_engine->fd_set_error(fd); }
-static size_t pollset_size(void) { return g_event_engine->pollset_size; }
-
-static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
- GRPC_POLLING_API_TRACE("pollset_init(%p)", pollset);
- g_event_engine->pollset_init(pollset, mu);
-}
-
-static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
- GRPC_POLLING_API_TRACE("pollset_shutdown(%p)", pollset);
- g_event_engine->pollset_shutdown(pollset, closure);
-}
-
-static void pollset_destroy(grpc_pollset* pollset) {
- GRPC_POLLING_API_TRACE("pollset_destroy(%p)", pollset);
- g_event_engine->pollset_destroy(pollset);
-}
-
-static grpc_error* pollset_work(grpc_pollset* pollset,
- grpc_pollset_worker** worker,
- grpc_millis deadline) {
+static size_t pollset_size(void) { return g_event_engine->pollset_size; }
+
+static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
+ GRPC_POLLING_API_TRACE("pollset_init(%p)", pollset);
+ g_event_engine->pollset_init(pollset, mu);
+}
+
+static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
+ GRPC_POLLING_API_TRACE("pollset_shutdown(%p)", pollset);
+ g_event_engine->pollset_shutdown(pollset, closure);
+}
+
+static void pollset_destroy(grpc_pollset* pollset) {
+ GRPC_POLLING_API_TRACE("pollset_destroy(%p)", pollset);
+ g_event_engine->pollset_destroy(pollset);
+}
+
+static grpc_error* pollset_work(grpc_pollset* pollset,
+ grpc_pollset_worker** worker,
+ grpc_millis deadline) {
GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") begin", pollset,
- deadline);
- grpc_error* err = g_event_engine->pollset_work(pollset, worker, deadline);
+ deadline);
+ grpc_error* err = g_event_engine->pollset_work(pollset, worker, deadline);
GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") end", pollset,
- deadline);
- return err;
-}
-
-static grpc_error* pollset_kick(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker) {
- GRPC_POLLING_API_TRACE("pollset_kick(%p, %p)", pollset, specific_worker);
- return g_event_engine->pollset_kick(pollset, specific_worker);
-}
-
-void grpc_pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd) {
- GRPC_POLLING_API_TRACE("pollset_add_fd(%p, %d)", pollset,
- grpc_fd_wrapped_fd(fd));
- g_event_engine->pollset_add_fd(pollset, fd);
-}
-
-void pollset_global_init() {}
-void pollset_global_shutdown() {}
-
-grpc_pollset_vtable grpc_posix_pollset_vtable = {
- pollset_global_init, pollset_global_shutdown,
- pollset_init, pollset_shutdown,
- pollset_destroy, pollset_work,
- pollset_kick, pollset_size};
-
-static grpc_pollset_set* pollset_set_create(void) {
- grpc_pollset_set* pss = g_event_engine->pollset_set_create();
- GRPC_POLLING_API_TRACE("pollset_set_create(%p)", pss);
- return pss;
-}
-
-static void pollset_set_destroy(grpc_pollset_set* pollset_set) {
- GRPC_POLLING_API_TRACE("pollset_set_destroy(%p)", pollset_set);
- g_event_engine->pollset_set_destroy(pollset_set);
-}
-
-static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {
- GRPC_POLLING_API_TRACE("pollset_set_add_pollset(%p, %p)", pollset_set,
- pollset);
- g_event_engine->pollset_set_add_pollset(pollset_set, pollset);
-}
-
-static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {
- GRPC_POLLING_API_TRACE("pollset_set_del_pollset(%p, %p)", pollset_set,
- pollset);
- g_event_engine->pollset_set_del_pollset(pollset_set, pollset);
-}
-
-static void pollset_set_add_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item) {
- GRPC_POLLING_API_TRACE("pollset_set_add_pollset_set(%p, %p)", bag, item);
- g_event_engine->pollset_set_add_pollset_set(bag, item);
-}
-
-static void pollset_set_del_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item) {
- GRPC_POLLING_API_TRACE("pollset_set_del_pollset_set(%p, %p)", bag, item);
- g_event_engine->pollset_set_del_pollset_set(bag, item);
-}
-
-grpc_pollset_set_vtable grpc_posix_pollset_set_vtable = {
- pollset_set_create, pollset_set_destroy,
- pollset_set_add_pollset, pollset_set_del_pollset,
- pollset_set_add_pollset_set, pollset_set_del_pollset_set};
-
-void grpc_pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
- GRPC_POLLING_API_TRACE("pollset_set_add_fd(%p, %d)", pollset_set,
- grpc_fd_wrapped_fd(fd));
- g_event_engine->pollset_set_add_fd(pollset_set, fd);
-}
-
-void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
- GRPC_POLLING_API_TRACE("pollset_set_del_fd(%p, %d)", pollset_set,
- grpc_fd_wrapped_fd(fd));
- g_event_engine->pollset_set_del_fd(pollset_set, fd);
-}
-
+ deadline);
+ return err;
+}
+
+static grpc_error* pollset_kick(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker) {
+ GRPC_POLLING_API_TRACE("pollset_kick(%p, %p)", pollset, specific_worker);
+ return g_event_engine->pollset_kick(pollset, specific_worker);
+}
+
+void grpc_pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd) {
+ GRPC_POLLING_API_TRACE("pollset_add_fd(%p, %d)", pollset,
+ grpc_fd_wrapped_fd(fd));
+ g_event_engine->pollset_add_fd(pollset, fd);
+}
+
+void pollset_global_init() {}
+void pollset_global_shutdown() {}
+
+grpc_pollset_vtable grpc_posix_pollset_vtable = {
+ pollset_global_init, pollset_global_shutdown,
+ pollset_init, pollset_shutdown,
+ pollset_destroy, pollset_work,
+ pollset_kick, pollset_size};
+
+static grpc_pollset_set* pollset_set_create(void) {
+ grpc_pollset_set* pss = g_event_engine->pollset_set_create();
+ GRPC_POLLING_API_TRACE("pollset_set_create(%p)", pss);
+ return pss;
+}
+
+static void pollset_set_destroy(grpc_pollset_set* pollset_set) {
+ GRPC_POLLING_API_TRACE("pollset_set_destroy(%p)", pollset_set);
+ g_event_engine->pollset_set_destroy(pollset_set);
+}
+
+static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {
+ GRPC_POLLING_API_TRACE("pollset_set_add_pollset(%p, %p)", pollset_set,
+ pollset);
+ g_event_engine->pollset_set_add_pollset(pollset_set, pollset);
+}
+
+static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {
+ GRPC_POLLING_API_TRACE("pollset_set_del_pollset(%p, %p)", pollset_set,
+ pollset);
+ g_event_engine->pollset_set_del_pollset(pollset_set, pollset);
+}
+
+static void pollset_set_add_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item) {
+ GRPC_POLLING_API_TRACE("pollset_set_add_pollset_set(%p, %p)", bag, item);
+ g_event_engine->pollset_set_add_pollset_set(bag, item);
+}
+
+static void pollset_set_del_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item) {
+ GRPC_POLLING_API_TRACE("pollset_set_del_pollset_set(%p, %p)", bag, item);
+ g_event_engine->pollset_set_del_pollset_set(bag, item);
+}
+
+grpc_pollset_set_vtable grpc_posix_pollset_set_vtable = {
+ pollset_set_create, pollset_set_destroy,
+ pollset_set_add_pollset, pollset_set_del_pollset,
+ pollset_set_add_pollset_set, pollset_set_del_pollset_set};
+
+void grpc_pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
+ GRPC_POLLING_API_TRACE("pollset_set_add_fd(%p, %d)", pollset_set,
+ grpc_fd_wrapped_fd(fd));
+ g_event_engine->pollset_set_add_fd(pollset_set, fd);
+}
+
+void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
+ GRPC_POLLING_API_TRACE("pollset_set_del_fd(%p, %d)", pollset_set,
+ grpc_fd_wrapped_fd(fd));
+ g_event_engine->pollset_set_del_fd(pollset_set, fd);
+}
+
bool grpc_is_any_background_poller_thread(void) {
return g_event_engine->is_any_background_poller_thread();
}
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 84edabce71e..cf0c37aaf74 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h
@@ -1,29 +1,29 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_EV_POSIX_H
#define GRPC_CORE_LIB_IOMGR_EV_POSIX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <poll.h>
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/pollset.h"
@@ -31,7 +31,7 @@
#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 */
@@ -49,40 +49,40 @@ typedef struct grpc_event_engine_vtable {
bool run_in_background;
grpc_fd* (*fd_create)(int fd, const char* name, bool track_err);
- int (*fd_wrapped_fd)(grpc_fd* fd);
- void (*fd_orphan)(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
+ int (*fd_wrapped_fd)(grpc_fd* fd);
+ void (*fd_orphan)(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
const char* reason);
- void (*fd_shutdown)(grpc_fd* fd, grpc_error* why);
- void (*fd_notify_on_read)(grpc_fd* fd, grpc_closure* closure);
- void (*fd_notify_on_write)(grpc_fd* fd, grpc_closure* closure);
+ void (*fd_shutdown)(grpc_fd* fd, grpc_error* why);
+ void (*fd_notify_on_read)(grpc_fd* fd, grpc_closure* closure);
+ void (*fd_notify_on_write)(grpc_fd* fd, grpc_closure* closure);
void (*fd_notify_on_error)(grpc_fd* fd, grpc_closure* closure);
void (*fd_set_readable)(grpc_fd* fd);
void (*fd_set_writable)(grpc_fd* fd);
void (*fd_set_error)(grpc_fd* fd);
- bool (*fd_is_shutdown)(grpc_fd* fd);
-
- void (*pollset_init)(grpc_pollset* pollset, gpr_mu** mu);
- void (*pollset_shutdown)(grpc_pollset* pollset, grpc_closure* closure);
- void (*pollset_destroy)(grpc_pollset* pollset);
- grpc_error* (*pollset_work)(grpc_pollset* pollset,
- grpc_pollset_worker** worker,
- grpc_millis deadline);
- grpc_error* (*pollset_kick)(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker);
- void (*pollset_add_fd)(grpc_pollset* pollset, struct grpc_fd* fd);
-
- grpc_pollset_set* (*pollset_set_create)(void);
- void (*pollset_set_destroy)(grpc_pollset_set* pollset_set);
- void (*pollset_set_add_pollset)(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset);
- void (*pollset_set_del_pollset)(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset);
- void (*pollset_set_add_pollset_set)(grpc_pollset_set* bag,
- grpc_pollset_set* item);
- void (*pollset_set_del_pollset_set)(grpc_pollset_set* bag,
- grpc_pollset_set* item);
- void (*pollset_set_add_fd)(grpc_pollset_set* pollset_set, grpc_fd* fd);
- void (*pollset_set_del_fd)(grpc_pollset_set* pollset_set, grpc_fd* fd);
+ bool (*fd_is_shutdown)(grpc_fd* fd);
+
+ void (*pollset_init)(grpc_pollset* pollset, gpr_mu** mu);
+ void (*pollset_shutdown)(grpc_pollset* pollset, grpc_closure* closure);
+ void (*pollset_destroy)(grpc_pollset* pollset);
+ grpc_error* (*pollset_work)(grpc_pollset* pollset,
+ grpc_pollset_worker** worker,
+ grpc_millis deadline);
+ grpc_error* (*pollset_kick)(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker);
+ void (*pollset_add_fd)(grpc_pollset* pollset, struct grpc_fd* fd);
+
+ grpc_pollset_set* (*pollset_set_create)(void);
+ void (*pollset_set_destroy)(grpc_pollset_set* pollset_set);
+ void (*pollset_set_add_pollset)(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset);
+ void (*pollset_set_del_pollset)(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset);
+ void (*pollset_set_add_pollset_set)(grpc_pollset_set* bag,
+ grpc_pollset_set* item);
+ void (*pollset_set_del_pollset_set)(grpc_pollset_set* bag,
+ grpc_pollset_set* item);
+ void (*pollset_set_add_fd)(grpc_pollset_set* pollset_set, grpc_fd* fd);
+ void (*pollset_set_del_fd)(grpc_pollset_set* pollset_set, grpc_fd* fd);
bool (*is_any_background_poller_thread)(void);
void (*shutdown_background_closure)(void);
@@ -100,7 +100,7 @@ void grpc_event_engine_init(void);
void grpc_event_engine_shutdown(void);
/* Return the name of the poll strategy */
-const char* grpc_get_poll_strategy_name();
+const char* grpc_get_poll_strategy_name();
/* Returns true if polling engine can track errors separately, false otherwise.
* If this is true, fd can be created with track_err set. After this, error
@@ -123,7 +123,7 @@ bool grpc_event_engine_run_in_background();
grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err);
/* Return the wrapped fd, or -1 if it has been released or closed. */
-int grpc_fd_wrapped_fd(grpc_fd* fd);
+int grpc_fd_wrapped_fd(grpc_fd* fd);
/* Releases fd to be asynchronously destroyed.
on_done is called when the underlying file descriptor is definitely close()d.
@@ -132,14 +132,14 @@ int grpc_fd_wrapped_fd(grpc_fd* fd);
Requires: *fd initialized; no outstanding notify_on_read or
notify_on_write.
MUST NOT be called with a pollset lock taken */
-void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
+void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
const char* reason);
/* Has grpc_fd_shutdown been called on an fd? */
-bool grpc_fd_is_shutdown(grpc_fd* fd);
+bool grpc_fd_is_shutdown(grpc_fd* fd);
/* Cause any current and future callbacks to fail. */
-void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why);
+void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why);
/* Register read interest, causing read_cb to be called once when fd becomes
readable, on deadline specified by deadline, or on shutdown triggered by
@@ -154,10 +154,10 @@ void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why);
underlying platform. This means that users must drain fd in read_cb before
calling notify_on_read again. Users are also expected to handle spurious
events, i.e read_cb is called while nothing can be readable from fd */
-void grpc_fd_notify_on_read(grpc_fd* fd, grpc_closure* closure);
+void grpc_fd_notify_on_read(grpc_fd* fd, grpc_closure* closure);
/* Exactly the same semantics as above, except based on writable events. */
-void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure);
+void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure);
/* Exactly the same semantics as above, except based on error events. track_err
* needs to have been set on grpc_fd_create */
@@ -181,12 +181,12 @@ void grpc_fd_set_error(grpc_fd* fd);
/* pollset_posix functions */
/* Add an fd to a pollset */
-void grpc_pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd);
+void grpc_pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd);
/* pollset_set_posix functions */
-void grpc_pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd);
-void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd);
+void grpc_pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd);
+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();
@@ -201,7 +201,7 @@ bool grpc_add_closure_to_background_poller(grpc_closure* closure,
void grpc_shutdown_background_closure();
/* override to allow tests to hook poll() usage */
-typedef int (*grpc_poll_function_type)(struct pollfd*, nfds_t, int);
+typedef int (*grpc_poll_function_type)(struct pollfd*, nfds_t, int);
extern grpc_poll_function_type grpc_poll_function;
#endif /* GRPC_CORE_LIB_IOMGR_EV_POSIX_H */
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 e3f5715a873..9420dd27dcf 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_windows.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include "src/core/lib/debug/trace.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/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/debug/trace.h"
+
grpc_core::DebugOnlyTraceFlag grpc_polling_trace(
false, "polling"); /* Disabled by default */
-
-#endif // GRPC_WINSOCK_SOCKET
+
+#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 e392a9960b1..6bccf4331fe 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc
@@ -1,174 +1,174 @@
-/*
- *
- * 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/iomgr/exec_ctx.h"
-
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/gprpp/thd.h"
-#include "src/core/lib/iomgr/combiner.h"
-#include "src/core/lib/profiling/timers.h"
-
-static void exec_ctx_run(grpc_closure* closure, grpc_error* error) {
-#ifndef NDEBUG
- closure->scheduled = false;
- if (grpc_trace_closure.enabled()) {
- gpr_log(GPR_DEBUG, "running closure %p: created [%s:%d]: %s [%s:%d]",
- closure, closure->file_created, closure->line_created,
- closure->run ? "run" : "scheduled", closure->file_initiated,
- closure->line_initiated);
- }
-#endif
- closure->cb(closure->cb_arg, error);
-#ifndef NDEBUG
- if (grpc_trace_closure.enabled()) {
- gpr_log(GPR_DEBUG, "closure %p finished", closure);
- }
-#endif
- GRPC_ERROR_UNREF(error);
-}
-
-static void exec_ctx_sched(grpc_closure* closure, grpc_error* error) {
- grpc_closure_list_append(grpc_core::ExecCtx::Get()->closure_list(), closure,
- error);
-}
-
-static gpr_timespec g_start_time;
+/*
+ *
+ * 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/iomgr/exec_ctx.h"
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/combiner.h"
+#include "src/core/lib/profiling/timers.h"
+
+static void exec_ctx_run(grpc_closure* closure, grpc_error* error) {
+#ifndef NDEBUG
+ closure->scheduled = false;
+ if (grpc_trace_closure.enabled()) {
+ gpr_log(GPR_DEBUG, "running closure %p: created [%s:%d]: %s [%s:%d]",
+ closure, closure->file_created, closure->line_created,
+ closure->run ? "run" : "scheduled", closure->file_initiated,
+ closure->line_initiated);
+ }
+#endif
+ closure->cb(closure->cb_arg, error);
+#ifndef NDEBUG
+ if (grpc_trace_closure.enabled()) {
+ gpr_log(GPR_DEBUG, "closure %p finished", closure);
+ }
+#endif
+ GRPC_ERROR_UNREF(error);
+}
+
+static void exec_ctx_sched(grpc_closure* closure, grpc_error* error) {
+ grpc_closure_list_append(grpc_core::ExecCtx::Get()->closure_list(), closure,
+ error);
+}
+
+static gpr_timespec g_start_time;
static gpr_cycle_counter g_start_cycle;
-
+
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;
+ 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;
if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE;
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) {
- 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) /
- static_cast<double>(GPR_NS_PER_SEC);
- if (x < 0) return 0;
+ 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) /
+ static_cast<double>(GPR_NS_PER_SEC);
+ if (x < 0) return 0;
if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE;
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));
}
-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
- // while gpr_time_from_millis always takes an int64_t.
- if (millis == GRPC_MILLIS_INF_FUTURE) {
- return gpr_inf_future(clock_type);
- }
- if (millis == GRPC_MILLIS_INF_PAST) {
- return gpr_inf_past(clock_type);
- }
-
- if (clock_type == GPR_TIMESPAN) {
- return gpr_time_from_millis(millis, GPR_TIMESPAN);
- }
- return gpr_time_add(gpr_convert_clock_type(g_start_time, clock_type),
- gpr_time_from_millis(millis, GPR_TIMESPAN));
-}
-
-grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec ts) {
+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
+ // while gpr_time_from_millis always takes an int64_t.
+ if (millis == GRPC_MILLIS_INF_FUTURE) {
+ return gpr_inf_future(clock_type);
+ }
+ if (millis == GRPC_MILLIS_INF_PAST) {
+ return gpr_inf_past(clock_type);
+ }
+
+ if (clock_type == GPR_TIMESPAN) {
+ return gpr_time_from_millis(millis, GPR_TIMESPAN);
+ }
+ return gpr_time_add(gpr_convert_clock_type(g_start_time, clock_type),
+ gpr_time_from_millis(millis, GPR_TIMESPAN));
+}
+
+grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec ts) {
return timespec_to_millis_round_down(
- gpr_convert_clock_type(ts, g_start_time.clock_type));
-}
-
-grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec ts) {
+ gpr_convert_clock_type(ts, g_start_time.clock_type));
+}
+
+grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec ts) {
return timespec_to_millis_round_up(
- gpr_convert_clock_type(ts, g_start_time.clock_type));
-}
-
+ 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));
}
-namespace grpc_core {
-GPR_TLS_CLASS_DEF(ExecCtx::exec_ctx_);
+namespace grpc_core {
+GPR_TLS_CLASS_DEF(ExecCtx::exec_ctx_);
GPR_TLS_CLASS_DEF(ApplicationCallbackExecCtx::callback_exec_ctx_);
-
+
// WARNING: for testing purposes only!
void ExecCtx::TestOnlyGlobalInit(gpr_timespec new_val) {
g_start_time = new_val;
gpr_tls_init(&exec_ctx_);
}
-void ExecCtx::GlobalInit(void) {
+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();
- g_start_time = gpr_now(GPR_CLOCK_MONOTONIC);
+ 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;
- gpr_tls_init(&exec_ctx_);
-}
-
-bool ExecCtx::Flush() {
- bool did_something = 0;
- GPR_TIMER_SCOPE("grpc_exec_ctx_flush", 0);
- for (;;) {
- if (!grpc_closure_list_empty(closure_list_)) {
- grpc_closure* c = closure_list_.head;
- closure_list_.head = closure_list_.tail = nullptr;
- while (c != nullptr) {
- grpc_closure* next = c->next_data.next;
- grpc_error* error = c->error_data.error;
- did_something = true;
- exec_ctx_run(c, error);
- c = next;
- }
- } else if (!grpc_combiner_continue_exec_ctx()) {
- break;
- }
- }
- GPR_ASSERT(combiner_data_.active_combiner == nullptr);
- return did_something;
-}
-
-grpc_millis ExecCtx::Now() {
- if (!now_is_valid_) {
+ gpr_tls_init(&exec_ctx_);
+}
+
+bool ExecCtx::Flush() {
+ bool did_something = 0;
+ GPR_TIMER_SCOPE("grpc_exec_ctx_flush", 0);
+ for (;;) {
+ if (!grpc_closure_list_empty(closure_list_)) {
+ grpc_closure* c = closure_list_.head;
+ closure_list_.head = closure_list_.tail = nullptr;
+ while (c != nullptr) {
+ grpc_closure* next = c->next_data.next;
+ grpc_error* error = c->error_data.error;
+ did_something = true;
+ exec_ctx_run(c, error);
+ c = next;
+ }
+ } else if (!grpc_combiner_continue_exec_ctx()) {
+ break;
+ }
+ }
+ GPR_ASSERT(combiner_data_.active_combiner == nullptr);
+ return did_something;
+}
+
+grpc_millis ExecCtx::Now() {
+ if (!now_is_valid_) {
now_ = timespec_to_millis_round_down(gpr_now(GPR_CLOCK_MONOTONIC));
- now_is_valid_ = true;
- }
- return now_;
-}
-
+ now_is_valid_ = true;
+ }
+ return now_;
+}
+
void ExecCtx::Run(const DebugLocation& location, grpc_closure* closure,
grpc_error* error) {
(void)location;
@@ -221,4 +221,4 @@ void ExecCtx::RunList(const DebugLocation& location, grpc_closure_list* list) {
list->head = list->tail = nullptr;
}
-} // namespace grpc_core
+} // 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 6b4e184cad3..712511d6037 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h
@@ -1,35 +1,35 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_EXEC_CTX_H
#define GRPC_CORE_LIB_IOMGR_EXEC_CTX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <limits>
#include <grpc/impl/codegen/grpc_types.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/cpu.h>
-#include <grpc/support/log.h>
-
+#include <grpc/support/atm.h>
+#include <grpc/support/cpu.h>
+#include <grpc/support/log.h>
+
#include "src/core/lib/gpr/time_precise.h"
-#include "src/core/lib/gpr/tls.h"
+#include "src/core/lib/gpr/tls.h"
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/fork.h"
#include "src/core/lib/iomgr/closure.h"
@@ -38,58 +38,58 @@ typedef int64_t grpc_millis;
#define GRPC_MILLIS_INF_FUTURE INT64_MAX
#define GRPC_MILLIS_INF_PAST INT64_MIN
-
+
/** A combiner represents a list of work to be executed later.
Forward declared here to avoid a circular dependency with combiner.h. */
typedef struct grpc_combiner grpc_combiner;
-/* This exec_ctx is ready to return: either pre-populated, or cached as soon as
- the finish_check returns true */
-#define GRPC_EXEC_CTX_FLAG_IS_FINISHED 1
-/* The exec_ctx's thread is (potentially) owned by a call or channel: care
- should be given to not delete said call/channel from this exec_ctx */
-#define GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP 2
+/* This exec_ctx is ready to return: either pre-populated, or cached as soon as
+ the finish_check returns true */
+#define GRPC_EXEC_CTX_FLAG_IS_FINISHED 1
+/* The exec_ctx's thread is (potentially) owned by a call or channel: care
+ should be given to not delete said call/channel from this exec_ctx */
+#define GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP 2
/* This exec ctx was initialized by an internal thread, and should not
be counted by fork handlers */
#define GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD 4
-
+
/* This application callback exec ctx was initialized by an internal thread, and
should not be counted by fork handlers */
#define GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD 1
-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);
+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);
-
-namespace grpc_core {
+
+namespace grpc_core {
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
* stored internally as a thread-local variable.
*
- * Generally, to create an exec_ctx instance, add the following line at the top
- * of the public API entry point or at the start of a thread's work function :
- *
- * grpc_core::ExecCtx exec_ctx;
- *
- * Access the created ExecCtx instance using :
- * grpc_core::ExecCtx::Get()
- *
+ * Generally, to create an exec_ctx instance, add the following line at the top
+ * of the public API entry point or at the start of a thread's work function :
+ *
+ * grpc_core::ExecCtx exec_ctx;
+ *
+ * Access the created ExecCtx instance using :
+ * grpc_core::ExecCtx::Get()
+ *
* Specific responsibilities (this may grow in the future):
* - track a list of core work that needs to be delayed until the base of the
* call stack (this provides a convenient mechanism to run callbacks
* without worrying about locking issues)
- * - provide a decision maker (via IsReadyToFinish) that provides a
+ * - provide a decision maker (via IsReadyToFinish) that provides a
* signal as to whether a borrowed thread should continue to do work or
* should actively try to finish up and get this thread back to its owner
*
* CONVENTIONS:
* - Instance of this must ALWAYS be constructed on the stack, never
* heap allocated.
- * - Do not pass exec_ctx as a parameter to a function. Always access it using
+ * - Do not pass exec_ctx as a parameter to a function. Always access it using
* grpc_core::ExecCtx::Get().
* - NOTE: In the future, the convention is likely to change to allow only one
* ExecCtx on a thread's stack at the same time. The TODO below
@@ -103,16 +103,16 @@ class Combiner;
* since that implies a core re-entry outside of application
* callbacks.
*/
-class ExecCtx {
- public:
- /** Default Constructor */
+class ExecCtx {
+ public:
+ /** Default Constructor */
ExecCtx() : flags_(GRPC_EXEC_CTX_FLAG_IS_FINISHED) {
grpc_core::Fork::IncExecCtxCount();
Set(this);
}
- /** Parameterised Constructor */
+ /** Parameterised Constructor */
ExecCtx(uintptr_t fl) : flags_(fl) {
if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) {
grpc_core::Fork::IncExecCtxCount();
@@ -120,19 +120,19 @@ class ExecCtx {
Set(this);
}
- /** Destructor */
- virtual ~ExecCtx() {
- flags_ |= GRPC_EXEC_CTX_FLAG_IS_FINISHED;
- Flush();
- Set(last_exec_ctx_);
+ /** Destructor */
+ virtual ~ExecCtx() {
+ flags_ |= GRPC_EXEC_CTX_FLAG_IS_FINISHED;
+ Flush();
+ Set(last_exec_ctx_);
if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) {
grpc_core::Fork::DecExecCtxCount();
}
- }
+ }
- /** Disallow copy and assignment operators */
- ExecCtx(const ExecCtx&) = delete;
- ExecCtx& operator=(const ExecCtx&) = delete;
+ /** Disallow copy and assignment operators */
+ ExecCtx(const ExecCtx&) = delete;
+ ExecCtx& operator=(const ExecCtx&) = delete;
unsigned starting_cpu() {
if (starting_cpu_ == std::numeric_limits<unsigned>::max()) {
@@ -141,119 +141,119 @@ class ExecCtx {
return starting_cpu_;
}
- struct CombinerData {
- /* currently active combiner: updated only via combiner.c */
+ struct CombinerData {
+ /* currently active combiner: updated only via combiner.c */
Combiner* active_combiner;
- /* last active combiner in the active combiner list */
+ /* last active combiner in the active combiner list */
Combiner* last_combiner;
- };
-
- /** Only to be used by grpc-combiner code */
- CombinerData* combiner_data() { return &combiner_data_; }
-
- /** Return pointer to grpc_closure_list */
- grpc_closure_list* closure_list() { return &closure_list_; }
-
- /** Return flags */
- uintptr_t flags() { return flags_; }
-
- /** Checks if there is work to be done */
- bool HasWork() {
- return combiner_data_.active_combiner != nullptr ||
- !grpc_closure_list_empty(closure_list_);
- }
-
- /** Flush any work that has been enqueued onto this grpc_exec_ctx.
- * Caller must guarantee that no interfering locks are held.
+ };
+
+ /** Only to be used by grpc-combiner code */
+ CombinerData* combiner_data() { return &combiner_data_; }
+
+ /** Return pointer to grpc_closure_list */
+ grpc_closure_list* closure_list() { return &closure_list_; }
+
+ /** Return flags */
+ uintptr_t flags() { return flags_; }
+
+ /** Checks if there is work to be done */
+ bool HasWork() {
+ return combiner_data_.active_combiner != nullptr ||
+ !grpc_closure_list_empty(closure_list_);
+ }
+
+ /** Flush any work that has been enqueued onto this grpc_exec_ctx.
+ * Caller must guarantee that no interfering locks are held.
* Returns true if work was performed, false otherwise.
*/
- bool Flush();
-
- /** Returns true if we'd like to leave this execution context as soon as
+ bool Flush();
+
+ /** Returns true if we'd like to leave this execution context as soon as
* possible: useful for deciding whether to do something more or not
* depending on outside context.
*/
- bool IsReadyToFinish() {
- if ((flags_ & GRPC_EXEC_CTX_FLAG_IS_FINISHED) == 0) {
- if (CheckReadyToFinish()) {
- flags_ |= GRPC_EXEC_CTX_FLAG_IS_FINISHED;
- return true;
- }
- return false;
- } else {
- return true;
- }
- }
-
- /** Returns the stored current time relative to start if valid,
+ bool IsReadyToFinish() {
+ if ((flags_ & GRPC_EXEC_CTX_FLAG_IS_FINISHED) == 0) {
+ if (CheckReadyToFinish()) {
+ flags_ |= GRPC_EXEC_CTX_FLAG_IS_FINISHED;
+ return true;
+ }
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ /** Returns the stored current time relative to start if valid,
* otherwise refreshes the stored time, sets it valid and returns the new
* value.
*/
- grpc_millis Now();
-
- /** Invalidates the stored time value. A new time value will be set on calling
+ grpc_millis Now();
+
+ /** Invalidates the stored time value. A new time value will be set on calling
* Now().
*/
- void InvalidateNow() { now_is_valid_ = false; }
-
- /** To be used only by shutdown code in iomgr */
- void SetNowIomgrShutdown() {
- now_ = GRPC_MILLIS_INF_FUTURE;
- now_is_valid_ = true;
- }
-
- /** To be used only for testing.
+ void InvalidateNow() { now_is_valid_ = false; }
+
+ /** To be used only by shutdown code in iomgr */
+ void SetNowIomgrShutdown() {
+ now_ = GRPC_MILLIS_INF_FUTURE;
+ now_is_valid_ = true;
+ }
+
+ /** To be used only for testing.
* Sets the now value.
- */
- void TestOnlySetNow(grpc_millis new_val) {
- now_ = new_val;
- now_is_valid_ = true;
- }
-
+ */
+ void TestOnlySetNow(grpc_millis new_val) {
+ now_ = new_val;
+ now_is_valid_ = true;
+ }
+
static void TestOnlyGlobalInit(gpr_timespec new_val);
/** Global initialization for ExecCtx. Called by iomgr. */
- static void GlobalInit(void);
-
+ static void GlobalInit(void);
+
/** Global shutdown for ExecCtx. Called by iomgr. */
- static void GlobalShutdown(void) { gpr_tls_destroy(&exec_ctx_); }
-
+ static void GlobalShutdown(void) { gpr_tls_destroy(&exec_ctx_); }
+
/** Gets pointer to current exec_ctx. */
- static ExecCtx* Get() {
- return reinterpret_cast<ExecCtx*>(gpr_tls_get(&exec_ctx_));
- }
-
- static void Set(ExecCtx* exec_ctx) {
- gpr_tls_set(&exec_ctx_, reinterpret_cast<intptr_t>(exec_ctx));
- }
-
+ static ExecCtx* Get() {
+ return reinterpret_cast<ExecCtx*>(gpr_tls_get(&exec_ctx_));
+ }
+
+ static void Set(ExecCtx* exec_ctx) {
+ 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);
- protected:
+ protected:
/** Check if ready to finish. */
- virtual bool CheckReadyToFinish() { return false; }
-
+ virtual bool CheckReadyToFinish() { return false; }
+
/** Disallow delete on ExecCtx. */
static void operator delete(void* /* p */) { abort(); }
-
- private:
+
+ private:
/** Set exec_ctx_ to exec_ctx. */
-
- grpc_closure_list closure_list_ = GRPC_CLOSURE_LIST_INIT;
- CombinerData combiner_data_ = {nullptr, nullptr};
- uintptr_t flags_;
+
+ grpc_closure_list closure_list_ = GRPC_CLOSURE_LIST_INIT;
+ CombinerData combiner_data_ = {nullptr, nullptr};
+ uintptr_t flags_;
unsigned starting_cpu_ = std::numeric_limits<unsigned>::max();
-
- bool now_is_valid_ = false;
- grpc_millis now_ = 0;
-
- GPR_TLS_CLASS_DECL(exec_ctx_);
- ExecCtx* last_exec_ctx_ = Get();
-};
+
+ bool now_is_valid_ = false;
+ grpc_millis now_ = 0;
+
+ GPR_TLS_CLASS_DECL(exec_ctx_);
+ ExecCtx* last_exec_ctx_ = Get();
+};
/** Application-callback execution context.
* A bag of data that collects information along a callstack.
@@ -377,6 +377,6 @@ class ApplicationCallbackExecCtx {
grpc_experimental_completion_queue_functor* tail_{nullptr};
GPR_TLS_CLASS_DECL(callback_exec_ctx_);
};
-} // namespace grpc_core
-
+} // namespace grpc_core
+
#endif /* GRPC_CORE_LIB_IOMGR_EXEC_CTX_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor.cc b/contrib/libs/grpc/src/core/lib/iomgr/executor.cc
index 10b2f948ec7..d217ba2e0e7 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor.cc
@@ -1,67 +1,67 @@
-/*
- *
- * 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/iomgr/executor.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/cpu.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/gpr/useful.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/iomgr/executor.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/cpu.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gpr/tls.h"
+#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/exec_ctx.h"
#include "src/core/lib/iomgr/iomgr.h"
-
-#define MAX_DEPTH 2
-
+
+#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_TRACE0(str) \
do { \
if (GRPC_TRACE_FLAG_ENABLED(executor_trace)) { \
gpr_log(GPR_INFO, "EXECUTOR " str); \
} \
} while (0)
-
+
namespace grpc_core {
namespace {
-GPR_TLS_DECL(g_this_thread_state);
-
+GPR_TLS_DECL(g_this_thread_state);
+
Executor* executors[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)];
-
+
void default_enqueue_short(grpc_closure* closure, grpc_error* error) {
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue(
closure, error, true /* is_short */);
}
-
+
void default_enqueue_long(grpc_closure* closure, grpc_error* error) {
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue(
closure, error, false /* is_short */);
@@ -110,8 +110,8 @@ void Executor::Init() { SetThreading(true); }
size_t Executor::RunClosures(const char* executor_name,
grpc_closure_list list) {
- size_t n = 0;
-
+ size_t n = 0;
+
// In the executor, the ExecCtx for the thread is declared in the executor
// thread itself, but this is the point where we could start seeing
// application-level callbacks. No need to create a new ExecCtx, though,
@@ -123,36 +123,36 @@ size_t Executor::RunClosures(const char* executor_name,
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx(
GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD);
- grpc_closure* c = list.head;
- while (c != nullptr) {
- grpc_closure* next = c->next_data.next;
- grpc_error* error = c->error_data.error;
-#ifndef NDEBUG
+ grpc_closure* c = list.head;
+ while (c != nullptr) {
+ grpc_closure* next = c->next_data.next;
+ grpc_error* error = c->error_data.error;
+#ifndef NDEBUG
EXECUTOR_TRACE("(%s) run %p [created by %s:%d]", executor_name, c,
c->file_created, c->line_created);
c->scheduled = false;
-#else
+#else
EXECUTOR_TRACE("(%s) run %p", executor_name, c);
-#endif
- c->cb(c->cb_arg, error);
- GRPC_ERROR_UNREF(error);
- c = next;
- n++;
- grpc_core::ExecCtx::Get()->Flush();
- }
-
- return n;
-}
-
+#endif
+ c->cb(c->cb_arg, error);
+ GRPC_ERROR_UNREF(error);
+ c = next;
+ n++;
+ grpc_core::ExecCtx::Get()->Flush();
+ }
+
+ return n;
+}
+
bool Executor::IsThreaded() const {
return gpr_atm_acq_load(&num_threads_) > 0;
-}
-
+}
+
void Executor::SetThreading(bool threading) {
gpr_atm curr_num_threads = gpr_atm_acq_load(&num_threads_);
EXECUTOR_TRACE("(%s) SetThreading(%d) begin", name_, threading);
- if (threading) {
+ if (threading) {
if (curr_num_threads > 0) {
EXECUTOR_TRACE("(%s) SetThreading(true). curr_num_threads > 0", name_);
return;
@@ -170,8 +170,8 @@ void Executor::SetThreading(bool threading) {
thd_state_[i].name = name_;
thd_state_[i].thd = grpc_core::Thread();
thd_state_[i].elems = GRPC_CLOSURE_LIST_INIT;
- }
-
+ }
+
thd_state_[0].thd =
grpc_core::Thread(name_, &Executor::ThreadMain, &thd_state_[0]);
thd_state_[0].thd.Start();
@@ -179,14 +179,14 @@ void Executor::SetThreading(bool threading) {
if (curr_num_threads == 0) {
EXECUTOR_TRACE("(%s) SetThreading(false). curr_num_threads == 0", name_);
return;
- }
+ }
for (size_t i = 0; i < max_threads_; i++) {
gpr_mu_lock(&thd_state_[i].mu);
thd_state_[i].shutdown = true;
gpr_cv_signal(&thd_state_[i].cv);
gpr_mu_unlock(&thd_state_[i].mu);
- }
+ }
/* Ensure no thread is adding a new thread. Once this is past, then no
* thread will try to add a new one either (since shutdown is true) */
@@ -198,7 +198,7 @@ void Executor::SetThreading(bool threading) {
thd_state_[i].thd.Join();
EXECUTOR_TRACE("(%s) Thread %" PRIdPTR " of %" PRIdPTR " joined", name_,
i + 1, curr_num_threads);
- }
+ }
gpr_atm_rel_store(&num_threads_, 0);
for (size_t i = 0; i < max_threads_; i++) {
@@ -216,116 +216,116 @@ void Executor::SetThreading(bool threading) {
// 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);
-}
-
+}
+
void Executor::Shutdown() { SetThreading(false); }
-
+
void Executor::ThreadMain(void* arg) {
ThreadState* ts = static_cast<ThreadState*>(arg);
gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(ts));
-
+
grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD);
-
- size_t subtract_depth = 0;
- for (;;) {
+
+ size_t subtract_depth = 0;
+ for (;;) {
EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: step (sub_depth=%" PRIdPTR ")",
ts->name, ts->id, subtract_depth);
- gpr_mu_lock(&ts->mu);
- ts->depth -= subtract_depth;
+ gpr_mu_lock(&ts->mu);
+ ts->depth -= subtract_depth;
// Wait for closures to be enqueued or for the executor to be shutdown
- while (grpc_closure_list_empty(ts->elems) && !ts->shutdown) {
- ts->queued_long_job = false;
- gpr_cv_wait(&ts->cv, &ts->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
+ while (grpc_closure_list_empty(ts->elems) && !ts->shutdown) {
+ ts->queued_long_job = false;
+ gpr_cv_wait(&ts->cv, &ts->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
+ }
- if (ts->shutdown) {
+ if (ts->shutdown) {
EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: shutdown", ts->name, ts->id);
- gpr_mu_unlock(&ts->mu);
- break;
- }
+ gpr_mu_unlock(&ts->mu);
+ break;
+ }
- GRPC_STATS_INC_EXECUTOR_QUEUE_DRAINED();
+ GRPC_STATS_INC_EXECUTOR_QUEUE_DRAINED();
grpc_closure_list closures = ts->elems;
- ts->elems = GRPC_CLOSURE_LIST_INIT;
- gpr_mu_unlock(&ts->mu);
-
+ ts->elems = GRPC_CLOSURE_LIST_INIT;
+ gpr_mu_unlock(&ts->mu);
+
EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: execute", ts->name, ts->id);
- grpc_core::ExecCtx::Get()->InvalidateNow();
+ grpc_core::ExecCtx::Get()->InvalidateNow();
subtract_depth = RunClosures(ts->name, closures);
- }
+ }
gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(nullptr));
-}
-
+}
+
void Executor::Enqueue(grpc_closure* closure, grpc_error* error,
bool is_short) {
- bool retry_push;
- if (is_short) {
- GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS();
- } else {
- GRPC_STATS_INC_EXECUTOR_SCHEDULED_LONG_ITEMS();
- }
-
- do {
- retry_push = false;
- size_t cur_thread_count =
+ bool retry_push;
+ if (is_short) {
+ GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS();
+ } else {
+ GRPC_STATS_INC_EXECUTOR_SCHEDULED_LONG_ITEMS();
+ }
+
+ do {
+ retry_push = false;
+ size_t cur_thread_count =
static_cast<size_t>(gpr_atm_acq_load(&num_threads_));
// If the number of threads is zero(i.e either the executor is not threaded
// or already shutdown), then queue the closure on the exec context itself
- if (cur_thread_count == 0) {
-#ifndef NDEBUG
+ if (cur_thread_count == 0) {
+#ifndef NDEBUG
EXECUTOR_TRACE("(%s) schedule %p (created %s:%d) inline", name_, closure,
closure->file_created, closure->line_created);
-#else
+#else
EXECUTOR_TRACE("(%s) schedule %p inline", name_, closure);
-#endif
- grpc_closure_list_append(grpc_core::ExecCtx::Get()->closure_list(),
- closure, error);
- return;
- }
+#endif
+ grpc_closure_list_append(grpc_core::ExecCtx::Get()->closure_list(),
+ 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) {
+ if (ts == nullptr) {
ts = &thd_state_[GPR_HASH_POINTER(grpc_core::ExecCtx::Get(),
cur_thread_count)];
- } else {
- GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF();
- }
-
+ } else {
+ GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF();
+ }
+
ThreadState* orig_ts = ts;
bool try_new_thread = false;
- for (;;) {
-#ifndef NDEBUG
+ for (;;) {
+#ifndef NDEBUG
EXECUTOR_TRACE(
"(%s) try to schedule %p (%s) (created %s:%d) to thread "
"%" PRIdPTR,
name_, closure, is_short ? "short" : "long", closure->file_created,
closure->line_created, ts->id);
-#else
+#else
EXECUTOR_TRACE("(%s) try to schedule %p (%s) to thread %" PRIdPTR, name_,
closure, is_short ? "short" : "long", ts->id);
-#endif
+#endif
- gpr_mu_lock(&ts->mu);
- if (ts->queued_long_job) {
- // if there's a long job queued, we never queue anything else to this
- // queue (since long jobs can take 'infinite' time and we need to
+ gpr_mu_lock(&ts->mu);
+ if (ts->queued_long_job) {
+ // if there's a long job queued, we never queue anything else to this
+ // queue (since long jobs can take 'infinite' time and we need to
// guarantee no starvation). Spin through queues and try again
- gpr_mu_unlock(&ts->mu);
+ gpr_mu_unlock(&ts->mu);
size_t idx = ts->id;
ts = &thd_state_[(idx + 1) % cur_thread_count];
- if (ts == orig_ts) {
+ if (ts == orig_ts) {
// We cycled through all the threads. Retry enqueue again by creating
// a new thread
//
@@ -336,13 +336,13 @@ void Executor::Enqueue(grpc_closure* closure, grpc_error* error,
// (Fortunately, this is not an issue yet (as of july 2018) because
// there is only one instance of long job in gRPC and hence we will
// not hit this code path)
- retry_push = true;
- try_new_thread = true;
- break;
- }
+ retry_push = true;
+ try_new_thread = true;
+ break;
+ }
continue; // Try the next thread-state
- }
+ }
// == Found the thread state (i.e thread) to enqueue this closure! ==
@@ -351,25 +351,25 @@ void Executor::Enqueue(grpc_closure* closure, grpc_error* error,
// shutdown, it means that the thread must be waiting in ThreadMain()
// - Note that gpr_cv_signal() won't immediately wakeup the thread. That
// happens after we release the mutex &ts->mu a few lines below
- if (grpc_closure_list_empty(ts->elems) && !ts->shutdown) {
- GRPC_STATS_INC_EXECUTOR_WAKEUP_INITIATED();
- gpr_cv_signal(&ts->cv);
- }
+ if (grpc_closure_list_empty(ts->elems) && !ts->shutdown) {
+ GRPC_STATS_INC_EXECUTOR_WAKEUP_INITIATED();
+ gpr_cv_signal(&ts->cv);
+ }
- grpc_closure_list_append(&ts->elems, closure, error);
+ grpc_closure_list_append(&ts->elems, closure, error);
// If we already queued more than MAX_DEPTH number of closures on this
// thread, use this as a hint to create more threads
- ts->depth++;
- try_new_thread = ts->depth > MAX_DEPTH &&
+ ts->depth++;
+ try_new_thread = ts->depth > MAX_DEPTH &&
cur_thread_count < max_threads_ && !ts->shutdown;
ts->queued_long_job = !is_short;
- gpr_mu_unlock(&ts->mu);
- break;
- }
-
+ gpr_mu_unlock(&ts->mu);
+ break;
+ }
+
if (try_new_thread && gpr_spinlock_trylock(&adding_thread_lock_)) {
cur_thread_count = static_cast<size_t>(gpr_atm_acq_load(&num_threads_));
if (cur_thread_count < max_threads_) {
@@ -380,16 +380,16 @@ void Executor::Enqueue(grpc_closure* closure, grpc_error* error,
thd_state_[cur_thread_count].thd = grpc_core::Thread(
name_, &Executor::ThreadMain, &thd_state_[cur_thread_count]);
thd_state_[cur_thread_count].thd.Start();
- }
+ }
gpr_spinlock_unlock(&adding_thread_lock_);
- }
-
- if (retry_push) {
- GRPC_STATS_INC_EXECUTOR_PUSH_RETRIES();
- }
- } while (retry_push);
-}
-
+ }
+
+ if (retry_push) {
+ GRPC_STATS_INC_EXECUTOR_PUSH_RETRIES();
+ }
+ } while (retry_push);
+}
+
// Executor::InitAll() and Executor::ShutdownAll() functions are called in the
// the grpc_init() and grpc_shutdown() code paths which are protected by a
// global mutex. So it is okay to assume that these functions are thread-safe
@@ -412,17 +412,17 @@ void Executor::InitAll() {
executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Init();
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::ShutdownAll() {
EXECUTOR_TRACE0("Executor::ShutdownAll() enter");
-
+
// Return if Executor:SshutdownAll() is already called earlier
if (executors[static_cast<size_t>(ExecutorType::DEFAULT)] == nullptr) {
GPR_ASSERT(executors[static_cast<size_t>(ExecutorType::RESOLVER)] ==
@@ -451,7 +451,7 @@ void Executor::ShutdownAll() {
executors[static_cast<size_t>(ExecutorType::RESOLVER)] = nullptr;
EXECUTOR_TRACE0("Executor::ShutdownAll() done");
-}
+}
bool Executor::IsThreaded(ExecutorType executor_type) {
GPR_ASSERT(executor_type < ExecutorType::NUM_EXECUTORS);
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor.h b/contrib/libs/grpc/src/core/lib/iomgr/executor.h
index ae523ff212f..4d7518cd721 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/executor.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/executor.h
@@ -1,32 +1,32 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_H
#define GRPC_CORE_LIB_IOMGR_EXECUTOR_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/gpr/spinlock.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/closure.h"
namespace grpc_core {
-
+
struct ThreadState {
gpr_mu mu;
size_t id; // For debugging purposes
@@ -51,11 +51,11 @@ enum class ExecutorJobType {
LONG,
NUM_JOB_TYPES // Add new values above this
};
-
+
class Executor {
public:
Executor(const char* executor_name);
-
+
void Init();
/** Is the executor multi-threaded? */
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 82654b5a885..b8df3df9009 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc
@@ -1,55 +1,55 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_POSIX_FORK
-
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_POSIX_FORK
+
#ifdef GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK
#include <pthread.h>
#endif
-#include <string.h>
-
-#include <grpc/fork.h>
+#include <string.h>
+
+#include <grpc/fork.h>
#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-
+#include <grpc/support/log.h>
+
#include "src/core/lib/gprpp/fork.h"
-#include "src/core/lib/gprpp/thd.h"
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/iomgr/timer_manager.h"
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-
-/*
- * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK
- * AROUND VERY SPECIFIC USE CASES.
- */
-
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/timer_manager.h"
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+
+/*
+ * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK
+ * AROUND VERY SPECIFIC USE CASES.
+ */
+
namespace {
bool skipped_handler = true;
bool registered_handlers = false;
} // namespace
-void grpc_prefork() {
+void grpc_prefork() {
skipped_handler = true;
// This may be called after core shuts down, so verify initialized before
// instantiating an ExecCtx.
@@ -58,11 +58,11 @@ void grpc_prefork() {
}
grpc_core::ExecCtx exec_ctx;
if (!grpc_core::Fork::Enabled()) {
- gpr_log(GPR_ERROR,
- "Fork support not enabled; try running with the "
- "environment variable GRPC_ENABLE_FORK_SUPPORT=1");
- return;
- }
+ gpr_log(GPR_ERROR,
+ "Fork support not enabled; try running with the "
+ "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 &&
@@ -70,7 +70,7 @@ void grpc_prefork() {
gpr_log(GPR_INFO,
"Fork support is only compatible with the epoll1 and poll polling "
"strategies");
- }
+ }
if (!grpc_core::Fork::BlockExecCtx()) {
gpr_log(GPR_INFO,
"Other threads are currently calling into gRPC, skipping fork() "
@@ -82,18 +82,18 @@ void grpc_prefork() {
grpc_core::ExecCtx::Get()->Flush();
grpc_core::Fork::AwaitThreads();
skipped_handler = false;
-}
-
-void grpc_postfork_parent() {
+}
+
+void grpc_postfork_parent() {
if (!skipped_handler) {
grpc_core::Fork::AllowExecCtx();
grpc_core::ExecCtx exec_ctx;
- grpc_timer_manager_set_threading(true);
+ grpc_timer_manager_set_threading(true);
grpc_core::Executor::SetThreadingAll(true);
- }
-}
-
-void grpc_postfork_child() {
+ }
+}
+
+void grpc_postfork_child() {
if (!skipped_handler) {
grpc_core::Fork::AllowExecCtx();
grpc_core::ExecCtx exec_ctx;
@@ -102,18 +102,18 @@ void grpc_postfork_child() {
if (reset_polling_engine != nullptr) {
reset_polling_engine();
}
- grpc_timer_manager_set_threading(true);
+ grpc_timer_manager_set_threading(true);
grpc_core::Executor::SetThreadingAll(true);
- }
-}
-
-void grpc_fork_handlers_auto_register() {
+ }
+}
+
+void grpc_fork_handlers_auto_register() {
if (grpc_core::Fork::Enabled() & !registered_handlers) {
-#ifdef GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK
- pthread_atfork(grpc_prefork, grpc_postfork_parent, grpc_postfork_child);
+#ifdef GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK
+ pthread_atfork(grpc_prefork, grpc_postfork_parent, grpc_postfork_child);
registered_handlers = true;
-#endif // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK
- }
-}
-
-#endif // GRPC_POSIX_FORK
+#endif // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK
+ }
+}
+
+#endif // GRPC_POSIX_FORK
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/fork_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/fork_windows.cc
index 798f671bdff..ff9531e465f 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/fork_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/fork_windows.cc
@@ -1,41 +1,41 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifndef GRPC_POSIX_FORK
-
-#include <grpc/fork.h>
-#include <grpc/support/log.h>
-
-/*
- * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK
- * AROUND VERY SPECIFIC USE CASES.
- */
-
-void grpc_prefork() { gpr_log(GPR_ERROR, "Forking not supported on Windows"); }
-
-void grpc_postfork_parent() {}
-
-void grpc_postfork_child() {}
-
-void grpc_fork_handlers_auto_register() {}
-
-#endif // GRPC_POSIX_FORK
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifndef GRPC_POSIX_FORK
+
+#include <grpc/fork.h>
+#include <grpc/support/log.h>
+
+/*
+ * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK
+ * AROUND VERY SPECIFIC USE CASES.
+ */
+
+void grpc_prefork() { gpr_log(GPR_ERROR, "Forking not supported on Windows"); }
+
+void grpc_postfork_parent() {}
+
+void grpc_postfork_child() {}
+
+void grpc_fork_handlers_auto_register() {}
+
+#endif // GRPC_POSIX_FORK
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/gethostname.h b/contrib/libs/grpc/src/core/lib/iomgr/gethostname.h
index 9f10b4afa78..1169534343e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/gethostname.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/gethostname.h
@@ -1,26 +1,26 @@
-/*
- *
- * 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_IOMGR_GETHOSTNAME_H
-#define GRPC_CORE_LIB_IOMGR_GETHOSTNAME_H
-
-// Returns the hostname of the local machine.
-// Caller takes ownership of result.
-char* grpc_gethostname();
-
-#endif /* GRPC_CORE_LIB_IOMGR_GETHOSTNAME_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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_GETHOSTNAME_H
+#define GRPC_CORE_LIB_IOMGR_GETHOSTNAME_H
+
+// Returns the hostname of the local machine.
+// Caller takes ownership of result.
+char* grpc_gethostname();
+
+#endif /* GRPC_CORE_LIB_IOMGR_GETHOSTNAME_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/gethostname_fallback.cc b/contrib/libs/grpc/src/core/lib/iomgr/gethostname_fallback.cc
index 65ae818723a..ca21f3b1531 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/gethostname_fallback.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/gethostname_fallback.cc
@@ -1,30 +1,30 @@
-/*
- *
- * 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/iomgr/gethostname.h"
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_GETHOSTNAME_FALLBACK
-
-#include <stddef.h>
-
-char* grpc_gethostname() { return NULL; }
-
-#endif // GRPC_GETHOSTNAME_FALLBACK
+/*
+ *
+ * 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/iomgr/gethostname.h"
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_GETHOSTNAME_FALLBACK
+
+#include <stddef.h>
+
+char* grpc_gethostname() { return NULL; }
+
+#endif // GRPC_GETHOSTNAME_FALLBACK
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/gethostname_host_name_max.cc b/contrib/libs/grpc/src/core/lib/iomgr/gethostname_host_name_max.cc
index 79f5daa8f32..116f40df725 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/gethostname_host_name_max.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/gethostname_host_name_max.cc
@@ -1,40 +1,40 @@
-/*
- *
- * 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/iomgr/gethostname.h"
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_POSIX_HOST_NAME_MAX
-
-#include <limits.h>
-#include <unistd.h>
-
-#include <grpc/support/alloc.h>
-
-char* grpc_gethostname() {
- char* hostname = static_cast<char*>(gpr_malloc(HOST_NAME_MAX));
- if (gethostname(hostname, HOST_NAME_MAX) != 0) {
- gpr_free(hostname);
- return nullptr;
- }
- return hostname;
-}
-
-#endif // GRPC_POSIX_HOST_NAME_MAX
+/*
+ *
+ * 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/iomgr/gethostname.h"
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_POSIX_HOST_NAME_MAX
+
+#include <limits.h>
+#include <unistd.h>
+
+#include <grpc/support/alloc.h>
+
+char* grpc_gethostname() {
+ char* hostname = static_cast<char*>(gpr_malloc(HOST_NAME_MAX));
+ if (gethostname(hostname, HOST_NAME_MAX) != 0) {
+ gpr_free(hostname);
+ return nullptr;
+ }
+ return hostname;
+}
+
+#endif // GRPC_POSIX_HOST_NAME_MAX
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/gethostname_sysconf.cc b/contrib/libs/grpc/src/core/lib/iomgr/gethostname_sysconf.cc
index 92c5de3338e..24626fe0b64 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/gethostname_sysconf.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/gethostname_sysconf.cc
@@ -1,40 +1,40 @@
-/*
- *
- * 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/iomgr/gethostname.h"
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_POSIX_SYSCONF
-
-#include <unistd.h>
-
-#include <grpc/support/alloc.h>
-
-char* grpc_gethostname() {
- size_t host_name_max = (size_t)sysconf(_SC_HOST_NAME_MAX);
- char* hostname = (char*)gpr_malloc(host_name_max);
- if (gethostname(hostname, host_name_max) != 0) {
- gpr_free(hostname);
- return nullptr;
- }
- return hostname;
-}
-
-#endif // GRPC_POSIX_SYSCONF
+/*
+ *
+ * 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/iomgr/gethostname.h"
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_POSIX_SYSCONF
+
+#include <unistd.h>
+
+#include <grpc/support/alloc.h>
+
+char* grpc_gethostname() {
+ size_t host_name_max = (size_t)sysconf(_SC_HOST_NAME_MAX);
+ char* hostname = (char*)gpr_malloc(host_name_max);
+ if (gethostname(hostname, host_name_max) != 0) {
+ gpr_free(hostname);
+ return nullptr;
+ }
+ return hostname;
+}
+
+#endif // GRPC_POSIX_SYSCONF
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 29a05ee3099..b0f79c128ac 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc
@@ -1,94 +1,94 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include <winsock2.h>
-#include <limits>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/log_windows.h>
-
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/gprpp/thd.h"
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/socket_windows.h"
-#include "src/core/lib/iomgr/timer.h"
-
-static ULONG g_iocp_kick_token;
-static OVERLAPPED g_iocp_custom_overlap;
-
-static gpr_atm g_custom_events = 0;
-
-static HANDLE g_iocp;
-
-static DWORD deadline_to_millis_timeout(grpc_millis deadline) {
- if (deadline == GRPC_MILLIS_INF_FUTURE) {
- return INFINITE;
- }
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
- if (deadline < now) return 0;
- grpc_millis timeout = deadline - now;
- if (timeout > std::numeric_limits<DWORD>::max()) return INFINITE;
- return static_cast<DWORD>(deadline - now);
-}
-
-grpc_iocp_work_status grpc_iocp_work(grpc_millis deadline) {
- BOOL success;
- DWORD bytes = 0;
- DWORD flags = 0;
- ULONG_PTR completion_key;
- LPOVERLAPPED overlapped;
- grpc_winsocket* socket;
- grpc_winsocket_callback_info* info;
- GRPC_STATS_INC_SYSCALL_POLL();
- success =
- GetQueuedCompletionStatus(g_iocp, &bytes, &completion_key, &overlapped,
- deadline_to_millis_timeout(deadline));
- grpc_core::ExecCtx::Get()->InvalidateNow();
- if (success == 0 && overlapped == NULL) {
- return GRPC_IOCP_WORK_TIMEOUT;
- }
- GPR_ASSERT(completion_key && overlapped);
- if (overlapped == &g_iocp_custom_overlap) {
- gpr_atm_full_fetch_add(&g_custom_events, -1);
- if (completion_key == (ULONG_PTR)&g_iocp_kick_token) {
- /* We were awoken from a kick. */
- return GRPC_IOCP_WORK_KICK;
- }
- gpr_log(GPR_ERROR, "Unknown custom completion key.");
- abort();
- }
-
- socket = (grpc_winsocket*)completion_key;
- if (overlapped == &socket->write_info.overlapped) {
- info = &socket->write_info;
- } else if (overlapped == &socket->read_info.overlapped) {
- info = &socket->read_info;
- } else {
- abort();
- }
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include <winsock2.h>
+#include <limits>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_windows.h>
+
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/socket_windows.h"
+#include "src/core/lib/iomgr/timer.h"
+
+static ULONG g_iocp_kick_token;
+static OVERLAPPED g_iocp_custom_overlap;
+
+static gpr_atm g_custom_events = 0;
+
+static HANDLE g_iocp;
+
+static DWORD deadline_to_millis_timeout(grpc_millis deadline) {
+ if (deadline == GRPC_MILLIS_INF_FUTURE) {
+ return INFINITE;
+ }
+ grpc_millis now = grpc_core::ExecCtx::Get()->Now();
+ if (deadline < now) return 0;
+ grpc_millis timeout = deadline - now;
+ if (timeout > std::numeric_limits<DWORD>::max()) return INFINITE;
+ return static_cast<DWORD>(deadline - now);
+}
+
+grpc_iocp_work_status grpc_iocp_work(grpc_millis deadline) {
+ BOOL success;
+ DWORD bytes = 0;
+ DWORD flags = 0;
+ ULONG_PTR completion_key;
+ LPOVERLAPPED overlapped;
+ grpc_winsocket* socket;
+ grpc_winsocket_callback_info* info;
+ GRPC_STATS_INC_SYSCALL_POLL();
+ success =
+ GetQueuedCompletionStatus(g_iocp, &bytes, &completion_key, &overlapped,
+ deadline_to_millis_timeout(deadline));
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+ if (success == 0 && overlapped == NULL) {
+ return GRPC_IOCP_WORK_TIMEOUT;
+ }
+ GPR_ASSERT(completion_key && overlapped);
+ if (overlapped == &g_iocp_custom_overlap) {
+ gpr_atm_full_fetch_add(&g_custom_events, -1);
+ if (completion_key == (ULONG_PTR)&g_iocp_kick_token) {
+ /* We were awoken from a kick. */
+ return GRPC_IOCP_WORK_KICK;
+ }
+ gpr_log(GPR_ERROR, "Unknown custom completion key.");
+ abort();
+ }
+
+ socket = (grpc_winsocket*)completion_key;
+ if (overlapped == &socket->write_info.overlapped) {
+ info = &socket->write_info;
+ } else if (overlapped == &socket->read_info.overlapped) {
+ info = &socket->read_info;
+ } else {
+ abort();
+ }
if (socket->shutdown_called) {
info->bytes_transferred = 0;
info->wsa_error = WSA_OPERATION_ABORTED;
@@ -98,60 +98,60 @@ grpc_iocp_work_status grpc_iocp_work(grpc_millis deadline) {
info->bytes_transferred = bytes;
info->wsa_error = success ? 0 : WSAGetLastError();
}
- GPR_ASSERT(overlapped == &info->overlapped);
- grpc_socket_become_ready(socket, info);
- return GRPC_IOCP_WORK_WORK;
-}
-
-void grpc_iocp_init(void) {
- g_iocp =
- CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (ULONG_PTR)NULL, 0);
- GPR_ASSERT(g_iocp);
-}
-
-void grpc_iocp_kick(void) {
- BOOL success;
-
- gpr_atm_full_fetch_add(&g_custom_events, 1);
- success = PostQueuedCompletionStatus(g_iocp, 0, (ULONG_PTR)&g_iocp_kick_token,
- &g_iocp_custom_overlap);
- GPR_ASSERT(success);
-}
-
-void grpc_iocp_flush(void) {
- grpc_core::ExecCtx exec_ctx;
- grpc_iocp_work_status work_status;
-
- do {
- work_status = grpc_iocp_work(GRPC_MILLIS_INF_PAST);
- } while (work_status == GRPC_IOCP_WORK_KICK ||
- grpc_core::ExecCtx::Get()->Flush());
-}
-
-void grpc_iocp_shutdown(void) {
- grpc_core::ExecCtx exec_ctx;
- while (gpr_atm_acq_load(&g_custom_events)) {
- grpc_iocp_work(GRPC_MILLIS_INF_FUTURE);
- grpc_core::ExecCtx::Get()->Flush();
- }
-
- GPR_ASSERT(CloseHandle(g_iocp));
-}
-
-void grpc_iocp_add_socket(grpc_winsocket* socket) {
- HANDLE ret;
- if (socket->added_to_iocp) return;
- ret = CreateIoCompletionPort((HANDLE)socket->socket, g_iocp,
- (uintptr_t)socket, 0);
- if (!ret) {
- char* utf8_message = gpr_format_message(WSAGetLastError());
- gpr_log(GPR_ERROR, "Unable to add socket to iocp: %s", utf8_message);
- gpr_free(utf8_message);
- __debugbreak();
- abort();
- }
- socket->added_to_iocp = 1;
- GPR_ASSERT(ret == g_iocp);
-}
-
-#endif /* GRPC_WINSOCK_SOCKET */
+ GPR_ASSERT(overlapped == &info->overlapped);
+ grpc_socket_become_ready(socket, info);
+ return GRPC_IOCP_WORK_WORK;
+}
+
+void grpc_iocp_init(void) {
+ g_iocp =
+ CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (ULONG_PTR)NULL, 0);
+ GPR_ASSERT(g_iocp);
+}
+
+void grpc_iocp_kick(void) {
+ BOOL success;
+
+ gpr_atm_full_fetch_add(&g_custom_events, 1);
+ success = PostQueuedCompletionStatus(g_iocp, 0, (ULONG_PTR)&g_iocp_kick_token,
+ &g_iocp_custom_overlap);
+ GPR_ASSERT(success);
+}
+
+void grpc_iocp_flush(void) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_iocp_work_status work_status;
+
+ do {
+ work_status = grpc_iocp_work(GRPC_MILLIS_INF_PAST);
+ } while (work_status == GRPC_IOCP_WORK_KICK ||
+ grpc_core::ExecCtx::Get()->Flush());
+}
+
+void grpc_iocp_shutdown(void) {
+ grpc_core::ExecCtx exec_ctx;
+ while (gpr_atm_acq_load(&g_custom_events)) {
+ grpc_iocp_work(GRPC_MILLIS_INF_FUTURE);
+ grpc_core::ExecCtx::Get()->Flush();
+ }
+
+ GPR_ASSERT(CloseHandle(g_iocp));
+}
+
+void grpc_iocp_add_socket(grpc_winsocket* socket) {
+ HANDLE ret;
+ if (socket->added_to_iocp) return;
+ ret = CreateIoCompletionPort((HANDLE)socket->socket, g_iocp,
+ (uintptr_t)socket, 0);
+ if (!ret) {
+ char* utf8_message = gpr_format_message(WSAGetLastError());
+ gpr_log(GPR_ERROR, "Unable to add socket to iocp: %s", utf8_message);
+ gpr_free(utf8_message);
+ __debugbreak();
+ abort();
+ }
+ socket->added_to_iocp = 1;
+ GPR_ASSERT(ret == g_iocp);
+}
+
+#endif /* GRPC_WINSOCK_SOCKET */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.h
index 68d9de61582..2d02219e2f6 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.h
@@ -1,33 +1,33 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_IOCP_WINDOWS_H
#define GRPC_CORE_LIB_IOMGR_IOCP_WINDOWS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/support/sync.h>
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/socket_windows.h"
typedef enum {
@@ -36,13 +36,13 @@ typedef enum {
GRPC_IOCP_WORK_KICK
} grpc_iocp_work_status;
-grpc_iocp_work_status grpc_iocp_work(grpc_millis deadline);
+grpc_iocp_work_status grpc_iocp_work(grpc_millis deadline);
void grpc_iocp_init(void);
void grpc_iocp_kick(void);
void grpc_iocp_flush(void);
void grpc_iocp_shutdown(void);
-void grpc_iocp_add_socket(grpc_winsocket*);
-
-#endif
+void grpc_iocp_add_socket(grpc_winsocket*);
+#endif
+
#endif /* GRPC_CORE_LIB_IOMGR_IOCP_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc
index 802e3bdcb4d..98e1e4ed3f1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc
@@ -1,165 +1,165 @@
-/*
- *
- * 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/iomgr/iomgr.h"
-
-#include <inttypes.h>
-#include <stdlib.h>
-#include <string.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/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.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/iomgr/iomgr.h"
+
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.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/lib/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/global_config.h"
-#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/buffer_list.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/internal_errqueue.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/iomgr/timer_manager.h"
-
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#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()");
-static gpr_mu g_mu;
-static gpr_cv g_rcv;
-static int g_shutdown;
-static grpc_iomgr_object g_root_object;
+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;
-
-void grpc_iomgr_init() {
- grpc_core::ExecCtx exec_ctx;
- grpc_determine_iomgr_platform();
- g_shutdown = 0;
- gpr_mu_init(&g_mu);
- gpr_cv_init(&g_rcv);
+
+void grpc_iomgr_init() {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_determine_iomgr_platform();
+ g_shutdown = 0;
+ gpr_mu_init(&g_mu);
+ gpr_cv_init(&g_rcv);
grpc_core::Executor::InitAll();
- g_root_object.next = g_root_object.prev = &g_root_object;
- g_root_object.name = (char*)"root";
- grpc_iomgr_platform_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_core::grpc_errqueue_init();
g_grpc_abort_on_leaks = GPR_GLOBAL_CONFIG_GET(grpc_abort_on_leaks);
-}
-
-void grpc_iomgr_start() { grpc_timer_manager_init(); }
-
-static size_t count_objects(void) {
- grpc_iomgr_object* obj;
- size_t n = 0;
- for (obj = g_root_object.next; obj != &g_root_object; obj = obj->next) {
- n++;
- }
- return n;
-}
-
+}
+
+void grpc_iomgr_start() { grpc_timer_manager_init(); }
+
+static size_t count_objects(void) {
+ grpc_iomgr_object* obj;
+ size_t n = 0;
+ for (obj = g_root_object.next; obj != &g_root_object; obj = obj->next) {
+ n++;
+ }
+ return n;
+}
+
size_t grpc_iomgr_count_objects_for_testing(void) { return count_objects(); }
-static void dump_objects(const char* kind) {
- grpc_iomgr_object* obj;
- for (obj = g_root_object.next; obj != &g_root_object; obj = obj->next) {
- gpr_log(GPR_DEBUG, "%s OBJECT: %s %p", kind, obj->name, obj);
- }
-}
-
-void grpc_iomgr_shutdown() {
- gpr_timespec shutdown_deadline = gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(10, GPR_TIMESPAN));
- gpr_timespec last_warning_time = gpr_now(GPR_CLOCK_REALTIME);
-
- {
- grpc_timer_manager_shutdown();
- grpc_iomgr_platform_flush();
+static void dump_objects(const char* kind) {
+ grpc_iomgr_object* obj;
+ for (obj = g_root_object.next; obj != &g_root_object; obj = obj->next) {
+ gpr_log(GPR_DEBUG, "%s OBJECT: %s %p", kind, obj->name, obj);
+ }
+}
+
+void grpc_iomgr_shutdown() {
+ gpr_timespec shutdown_deadline = gpr_time_add(
+ gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(10, GPR_TIMESPAN));
+ gpr_timespec last_warning_time = gpr_now(GPR_CLOCK_REALTIME);
+
+ {
+ grpc_timer_manager_shutdown();
+ grpc_iomgr_platform_flush();
grpc_core::Executor::ShutdownAll();
-
- gpr_mu_lock(&g_mu);
- g_shutdown = 1;
- while (g_root_object.next != &g_root_object) {
- if (gpr_time_cmp(
- gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), last_warning_time),
- gpr_time_from_seconds(1, GPR_TIMESPAN)) >= 0) {
- if (g_root_object.next != &g_root_object) {
- gpr_log(GPR_DEBUG,
- "Waiting for %" PRIuPTR " iomgr objects to be destroyed",
- count_objects());
- }
- last_warning_time = gpr_now(GPR_CLOCK_REALTIME);
- }
- grpc_core::ExecCtx::Get()->SetNowIomgrShutdown();
- if (grpc_timer_check(nullptr) == GRPC_TIMERS_FIRED) {
- gpr_mu_unlock(&g_mu);
- grpc_core::ExecCtx::Get()->Flush();
- grpc_iomgr_platform_flush();
- gpr_mu_lock(&g_mu);
- continue;
- }
- if (g_root_object.next != &g_root_object) {
- if (grpc_iomgr_abort_on_leaks()) {
- gpr_log(GPR_DEBUG,
- "Failed to free %" PRIuPTR
- " iomgr objects before shutdown deadline: "
- "memory leaks are likely",
- count_objects());
- dump_objects("LEAKED");
- abort();
- }
- gpr_timespec short_deadline =
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_millis(100, GPR_TIMESPAN));
- if (gpr_cv_wait(&g_rcv, &g_mu, short_deadline)) {
- if (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), shutdown_deadline) >
- 0) {
- if (g_root_object.next != &g_root_object) {
- gpr_log(GPR_DEBUG,
- "Failed to free %" PRIuPTR
- " iomgr objects before shutdown deadline: "
- "memory leaks are likely",
- count_objects());
- dump_objects("LEAKED");
- }
- break;
- }
- }
- }
- }
- gpr_mu_unlock(&g_mu);
- grpc_timer_list_shutdown();
- grpc_core::ExecCtx::Get()->Flush();
- }
-
- /* ensure all threads have left g_mu */
- gpr_mu_lock(&g_mu);
- gpr_mu_unlock(&g_mu);
-
- grpc_iomgr_platform_shutdown();
- gpr_mu_destroy(&g_mu);
- gpr_cv_destroy(&g_rcv);
-}
-
+
+ gpr_mu_lock(&g_mu);
+ g_shutdown = 1;
+ while (g_root_object.next != &g_root_object) {
+ if (gpr_time_cmp(
+ gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), last_warning_time),
+ gpr_time_from_seconds(1, GPR_TIMESPAN)) >= 0) {
+ if (g_root_object.next != &g_root_object) {
+ gpr_log(GPR_DEBUG,
+ "Waiting for %" PRIuPTR " iomgr objects to be destroyed",
+ count_objects());
+ }
+ last_warning_time = gpr_now(GPR_CLOCK_REALTIME);
+ }
+ grpc_core::ExecCtx::Get()->SetNowIomgrShutdown();
+ if (grpc_timer_check(nullptr) == GRPC_TIMERS_FIRED) {
+ gpr_mu_unlock(&g_mu);
+ grpc_core::ExecCtx::Get()->Flush();
+ grpc_iomgr_platform_flush();
+ gpr_mu_lock(&g_mu);
+ continue;
+ }
+ if (g_root_object.next != &g_root_object) {
+ if (grpc_iomgr_abort_on_leaks()) {
+ gpr_log(GPR_DEBUG,
+ "Failed to free %" PRIuPTR
+ " iomgr objects before shutdown deadline: "
+ "memory leaks are likely",
+ count_objects());
+ dump_objects("LEAKED");
+ abort();
+ }
+ gpr_timespec short_deadline =
+ gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_millis(100, GPR_TIMESPAN));
+ if (gpr_cv_wait(&g_rcv, &g_mu, short_deadline)) {
+ if (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), shutdown_deadline) >
+ 0) {
+ if (g_root_object.next != &g_root_object) {
+ gpr_log(GPR_DEBUG,
+ "Failed to free %" PRIuPTR
+ " iomgr objects before shutdown deadline: "
+ "memory leaks are likely",
+ count_objects());
+ dump_objects("LEAKED");
+ }
+ break;
+ }
+ }
+ }
+ }
+ gpr_mu_unlock(&g_mu);
+ grpc_timer_list_shutdown();
+ grpc_core::ExecCtx::Get()->Flush();
+ }
+
+ /* ensure all threads have left g_mu */
+ gpr_mu_lock(&g_mu);
+ gpr_mu_unlock(&g_mu);
+
+ grpc_iomgr_platform_shutdown();
+ gpr_mu_destroy(&g_mu);
+ gpr_cv_destroy(&g_rcv);
+}
+
void grpc_iomgr_shutdown_background_closure() {
grpc_iomgr_platform_shutdown_background_closure();
}
@@ -173,22 +173,22 @@ bool grpc_iomgr_add_closure_to_background_poller(grpc_closure* closure,
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);
- obj->next = &g_root_object;
- obj->prev = g_root_object.prev;
- obj->next->prev = obj->prev->next = obj;
- gpr_mu_unlock(&g_mu);
-}
-
-void grpc_iomgr_unregister_object(grpc_iomgr_object* obj) {
- gpr_mu_lock(&g_mu);
- obj->next->prev = obj->prev;
- obj->prev->next = obj->next;
- gpr_cv_signal(&g_rcv);
- gpr_mu_unlock(&g_mu);
- gpr_free(obj->name);
-}
-
+void grpc_iomgr_register_object(grpc_iomgr_object* obj, const char* name) {
+ obj->name = gpr_strdup(name);
+ gpr_mu_lock(&g_mu);
+ obj->next = &g_root_object;
+ obj->prev = g_root_object.prev;
+ obj->next->prev = obj->prev->next = obj;
+ gpr_mu_unlock(&g_mu);
+}
+
+void grpc_iomgr_unregister_object(grpc_iomgr_object* obj) {
+ gpr_mu_lock(&g_mu);
+ obj->next->prev = obj->prev;
+ obj->prev->next = obj->next;
+ gpr_cv_signal(&g_rcv);
+ gpr_mu_unlock(&g_mu);
+ gpr_free(obj->name);
+}
+
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 e02f15e551c..77d44d10f39 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h
@@ -1,40 +1,40 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_IOMGR_H
#define GRPC_CORE_LIB_IOMGR_IOMGR_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/port.h"
#include <stdlib.h>
/** Initializes the iomgr. */
-void grpc_iomgr_init();
-
-/** Starts any background threads for iomgr. */
-void grpc_iomgr_start();
+void grpc_iomgr_init();
+/** Starts any background threads for iomgr. */
+void grpc_iomgr_start();
+
/** Signals the intention to shutdown the iomgr. Expects to be able to flush
* exec_ctx. */
-void grpc_iomgr_shutdown();
+void grpc_iomgr_shutdown();
/** Signals the intention to shutdown all the closures registered in the
* background poller. */
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 684044a5bbf..cf1c1898020 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc
@@ -1,45 +1,45 @@
-/*
- *
- * 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/lib/iomgr/port.h"
-
-#include <grpc/support/thd_id.h>
-
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/pollset_custom.h"
-#include "src/core/lib/iomgr/pollset_set_custom.h"
-#include "src/core/lib/iomgr/resolve_address_custom.h"
-
-gpr_thd_id g_init_thread;
-
-static void iomgr_platform_init(void) {
- grpc_core::ExecCtx exec_ctx;
+/*
+ *
+ * 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/lib/iomgr/port.h"
+
+#include <grpc/support/thd_id.h>
+
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/pollset_custom.h"
+#include "src/core/lib/iomgr/pollset_set_custom.h"
+#include "src/core/lib/iomgr/resolve_address_custom.h"
+
+gpr_thd_id g_init_thread;
+
+static void iomgr_platform_init(void) {
+ grpc_core::ExecCtx exec_ctx;
grpc_core::Executor::SetThreadingAll(false);
- g_init_thread = gpr_thd_currentid();
- grpc_pollset_global_init();
-}
-static void iomgr_platform_flush(void) {}
-static void iomgr_platform_shutdown(void) { grpc_pollset_global_shutdown(); }
+ g_init_thread = gpr_thd_currentid();
+ grpc_pollset_global_init();
+}
+static void iomgr_platform_flush(void) {}
+static void iomgr_platform_shutdown(void) { grpc_pollset_global_shutdown(); }
static void iomgr_platform_shutdown_background_closure(void) {}
static bool iomgr_platform_is_any_background_poller_thread(void) {
return false;
@@ -48,32 +48,32 @@ 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 = {
+static grpc_iomgr_platform_vtable vtable = {
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};
-
-void grpc_custom_iomgr_init(grpc_socket_vtable* socket,
- grpc_custom_resolver_vtable* resolver,
- grpc_custom_timer_vtable* timer,
- grpc_custom_poller_vtable* 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;
- grpc_custom_endpoint_init(socket);
- grpc_custom_timer_init(timer);
- grpc_custom_pollset_init(poller);
- grpc_custom_pollset_set_init();
- grpc_custom_resolver_init(resolver);
- grpc_set_iomgr_platform_vtable(&vtable);
-}
-
-#ifdef GRPC_CUSTOM_SOCKET
-grpc_iomgr_platform_vtable* grpc_default_iomgr_platform_vtable() {
- return &vtable;
-}
-#endif
+ grpc_custom_endpoint_init(socket);
+ grpc_custom_timer_init(timer);
+ grpc_custom_pollset_init(poller);
+ grpc_custom_pollset_set_init();
+ grpc_custom_resolver_init(resolver);
+ grpc_set_iomgr_platform_vtable(&vtable);
+}
+
+#ifdef GRPC_CUSTOM_SOCKET
+grpc_iomgr_platform_vtable* grpc_default_iomgr_platform_vtable() {
+ return &vtable;
+}
+#endif
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 e6a88843e5c..06760d4a8a4 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_IOMGR_CUSTOM_H
-#define GRPC_CORE_LIB_IOMGR_IOMGR_CUSTOM_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/pollset_custom.h"
-#include "src/core/lib/iomgr/resolve_address_custom.h"
-#include "src/core/lib/iomgr/tcp_custom.h"
-#include "src/core/lib/iomgr/timer_custom.h"
-
-#include <grpc/support/thd_id.h>
-
-/* The thread ID of the thread on which grpc was initialized. Used to verify
- * that all calls into the custom iomgr are made on that same thread */
-extern gpr_thd_id g_init_thread;
-
-#ifdef GRPC_CUSTOM_IOMGR_THREAD_CHECK
-#define GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD() \
- GPR_ASSERT(gpr_thd_currentid() == g_init_thread)
-#else
-#define GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD()
-#endif /* GRPC_CUSTOM_IOMGR_THREAD_CHECK */
-
+/*
+ *
+ * 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_IOMGR_IOMGR_CUSTOM_H
+#define GRPC_CORE_LIB_IOMGR_IOMGR_CUSTOM_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/pollset_custom.h"
+#include "src/core/lib/iomgr/resolve_address_custom.h"
+#include "src/core/lib/iomgr/tcp_custom.h"
+#include "src/core/lib/iomgr/timer_custom.h"
+
+#include <grpc/support/thd_id.h>
+
+/* The thread ID of the thread on which grpc was initialized. Used to verify
+ * that all calls into the custom iomgr are made on that same thread */
+extern gpr_thd_id g_init_thread;
+
+#ifdef GRPC_CUSTOM_IOMGR_THREAD_CHECK
+#define GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD() \
+ GPR_ASSERT(gpr_thd_currentid() == g_init_thread)
+#else
+#define GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD()
+#endif /* GRPC_CUSTOM_IOMGR_THREAD_CHECK */
+
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,
- grpc_custom_poller_vtable* poller);
-
-#endif /* GRPC_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);
+
+#endif /* GRPC_CORE_LIB_IOMGR_IOMGR_CUSTOM_H */
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 896d9fce67c..de471071fa5 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <stddef.h>
-
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/iomgr/timer_manager.h"
-
-static grpc_iomgr_platform_vtable* iomgr_platform_vtable = nullptr;
-
-void grpc_set_iomgr_platform_vtable(grpc_iomgr_platform_vtable* vtable) {
- iomgr_platform_vtable = vtable;
-}
-
-void grpc_determine_iomgr_platform() {
- if (iomgr_platform_vtable == nullptr) {
- grpc_set_default_iomgr_platform();
- }
-}
-
-void grpc_iomgr_platform_init() { iomgr_platform_vtable->init(); }
-
-void grpc_iomgr_platform_flush() { iomgr_platform_vtable->flush(); }
-
-void grpc_iomgr_platform_shutdown() { iomgr_platform_vtable->shutdown(); }
+/*
+ *
+ * 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 <stddef.h>
+
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/timer_manager.h"
+
+static grpc_iomgr_platform_vtable* iomgr_platform_vtable = nullptr;
+
+void grpc_set_iomgr_platform_vtable(grpc_iomgr_platform_vtable* vtable) {
+ iomgr_platform_vtable = vtable;
+}
+
+void grpc_determine_iomgr_platform() {
+ if (iomgr_platform_vtable == nullptr) {
+ grpc_set_default_iomgr_platform();
+ }
+}
+
+void grpc_iomgr_platform_init() { iomgr_platform_vtable->init(); }
+
+void grpc_iomgr_platform_flush() { iomgr_platform_vtable->flush(); }
+
+void grpc_iomgr_platform_shutdown() { iomgr_platform_vtable->shutdown(); }
void grpc_iomgr_platform_shutdown_background_closure() {
iomgr_platform_vtable->shutdown_background_closure();
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 17607f98f11..953759b9c24 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h
@@ -1,55 +1,55 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_IOMGR_INTERNAL_H
#define GRPC_CORE_LIB_IOMGR_IOMGR_INTERNAL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdbool.h>
#include "src/core/lib/iomgr/iomgr.h"
typedef struct grpc_iomgr_object {
- char* name;
- struct grpc_iomgr_object* next;
- struct grpc_iomgr_object* prev;
+ char* name;
+ struct grpc_iomgr_object* next;
+ struct grpc_iomgr_object* prev;
} grpc_iomgr_object;
-typedef struct grpc_iomgr_platform_vtable {
- void (*init)(void);
- void (*flush)(void);
- void (*shutdown)(void);
+typedef struct grpc_iomgr_platform_vtable {
+ void (*init)(void);
+ void (*flush)(void);
+ 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);
-} grpc_iomgr_platform_vtable;
-
-void grpc_iomgr_register_object(grpc_iomgr_object* obj, const char* name);
-void grpc_iomgr_unregister_object(grpc_iomgr_object* obj);
-
-void grpc_determine_iomgr_platform();
-
-void grpc_set_iomgr_platform_vtable(grpc_iomgr_platform_vtable* vtable);
-
-void grpc_set_default_iomgr_platform();
-
+} grpc_iomgr_platform_vtable;
+
+void grpc_iomgr_register_object(grpc_iomgr_object* obj, const char* name);
+void grpc_iomgr_unregister_object(grpc_iomgr_object* obj);
+
+void grpc_determine_iomgr_platform();
+
+void grpc_set_iomgr_platform_vtable(grpc_iomgr_platform_vtable* vtable);
+
+void grpc_set_default_iomgr_platform();
+
void grpc_iomgr_platform_init(void);
/** flush any globally queued work from iomgr */
void grpc_iomgr_platform_flush(void);
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 de22d20a639..fb9cf7194f6 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/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/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_IOMGR
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/iomgr_posix.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/iomgr/tcp_posix.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "src/core/lib/iomgr/timer.h"
-
-extern grpc_tcp_server_vtable grpc_posix_tcp_server_vtable;
-extern grpc_tcp_client_vtable grpc_posix_tcp_client_vtable;
-extern grpc_timer_vtable grpc_generic_timer_vtable;
-extern grpc_pollset_vtable grpc_posix_pollset_vtable;
-extern grpc_pollset_set_vtable grpc_posix_pollset_set_vtable;
-extern grpc_address_resolver_vtable grpc_posix_resolver_vtable;
-
-static void iomgr_platform_init(void) {
- grpc_wakeup_fd_global_init();
- grpc_event_engine_init();
-}
-
-static void iomgr_platform_flush(void) {}
-
-static void iomgr_platform_shutdown(void) {
- grpc_event_engine_shutdown();
- grpc_wakeup_fd_global_destroy();
-}
-
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/iomgr_posix.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/iomgr/tcp_posix.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "src/core/lib/iomgr/timer.h"
+
+extern grpc_tcp_server_vtable grpc_posix_tcp_server_vtable;
+extern grpc_tcp_client_vtable grpc_posix_tcp_client_vtable;
+extern grpc_timer_vtable grpc_generic_timer_vtable;
+extern grpc_pollset_vtable grpc_posix_pollset_vtable;
+extern grpc_pollset_set_vtable grpc_posix_pollset_set_vtable;
+extern grpc_address_resolver_vtable grpc_posix_resolver_vtable;
+
+static void iomgr_platform_init(void) {
+ grpc_wakeup_fd_global_init();
+ grpc_event_engine_init();
+}
+
+static void iomgr_platform_flush(void) {}
+
+static void iomgr_platform_shutdown(void) {
+ grpc_event_engine_shutdown();
+ grpc_wakeup_fd_global_destroy();
+}
+
static void iomgr_platform_shutdown_background_closure(void) {
grpc_shutdown_background_closure();
}
@@ -64,24 +64,24 @@ static bool iomgr_platform_add_closure_to_background_poller(
return grpc_add_closure_to_background_poller(closure, error);
}
-static grpc_iomgr_platform_vtable vtable = {
+static grpc_iomgr_platform_vtable vtable = {
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};
-
-void grpc_set_default_iomgr_platform() {
- grpc_set_tcp_client_impl(&grpc_posix_tcp_client_vtable);
- grpc_set_tcp_server_impl(&grpc_posix_tcp_server_vtable);
- grpc_set_timer_impl(&grpc_generic_timer_vtable);
- grpc_set_pollset_vtable(&grpc_posix_pollset_vtable);
- grpc_set_pollset_set_vtable(&grpc_posix_pollset_set_vtable);
- grpc_set_resolver_impl(&grpc_posix_resolver_vtable);
- grpc_set_iomgr_platform_vtable(&vtable);
-}
-
+
+void grpc_set_default_iomgr_platform() {
+ grpc_set_tcp_client_impl(&grpc_posix_tcp_client_vtable);
+ grpc_set_tcp_server_impl(&grpc_posix_tcp_server_vtable);
+ grpc_set_timer_impl(&grpc_generic_timer_vtable);
+ grpc_set_pollset_vtable(&grpc_posix_pollset_vtable);
+ grpc_set_pollset_set_vtable(&grpc_posix_pollset_set_vtable);
+ grpc_set_resolver_impl(&grpc_posix_resolver_vtable);
+ grpc_set_iomgr_platform_vtable(&vtable);
+}
+
bool grpc_iomgr_run_in_background() {
return grpc_event_engine_run_in_background();
}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.h
index 54ec46e1bb0..8c0f46ccf2f 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_IOMGR_POSIX_H
#define GRPC_CORE_LIB_IOMGR_IOMGR_POSIX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/iomgr_internal.h"
#endif /* GRPC_CORE_LIB_IOMGR_IOMGR_POSIX_H */
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 a617239678e..0ab7ef713da 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_uv.cc
@@ -1,43 +1,43 @@
-/*
- *
- * 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/lib/iomgr/port.h"
-
-#if defined(GRPC_CUSTOM_SOCKET) && defined(GRPC_UV)
-
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/pollset_custom.h"
-#include "src/core/lib/iomgr/tcp_custom.h"
-#include "src/core/lib/iomgr/timer_custom.h"
-
-extern grpc_socket_vtable grpc_uv_socket_vtable;
-extern grpc_custom_resolver_vtable uv_resolver_vtable;
-extern grpc_custom_timer_vtable uv_timer_vtable;
-extern grpc_custom_poller_vtable uv_pollset_vtable;
-
-void grpc_set_default_iomgr_platform() {
- grpc_custom_iomgr_init(&grpc_uv_socket_vtable, &uv_resolver_vtable,
- &uv_timer_vtable, &uv_pollset_vtable);
-}
+/*
+ *
+ * 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/lib/iomgr/port.h"
+
+#if defined(GRPC_CUSTOM_SOCKET) && defined(GRPC_UV)
+
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/pollset_custom.h"
+#include "src/core/lib/iomgr/tcp_custom.h"
+#include "src/core/lib/iomgr/timer_custom.h"
+
+extern grpc_socket_vtable grpc_uv_socket_vtable;
+extern grpc_custom_resolver_vtable uv_resolver_vtable;
+extern grpc_custom_timer_vtable uv_timer_vtable;
+extern grpc_custom_poller_vtable uv_pollset_vtable;
+
+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; }
-#endif
+#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 728d4040818..9e29db74f33 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc
@@ -1,77 +1,77 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include "src/core/lib/iomgr/sockaddr_windows.h"
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/iomgr/pollset_windows.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/socket_windows.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "src/core/lib/iomgr/timer.h"
-
-extern grpc_tcp_server_vtable grpc_windows_tcp_server_vtable;
-extern grpc_tcp_client_vtable grpc_windows_tcp_client_vtable;
-extern grpc_timer_vtable grpc_generic_timer_vtable;
-extern grpc_pollset_vtable grpc_windows_pollset_vtable;
-extern grpc_pollset_set_vtable grpc_windows_pollset_set_vtable;
-extern grpc_address_resolver_vtable grpc_windows_resolver_vtable;
-
-/* Windows' io manager is going to be fully designed using IO completion
- ports. All of what we're doing here is basically make sure that
- Windows sockets are initialized in and out. */
-
-static void winsock_init(void) {
- WSADATA wsaData;
- int status = WSAStartup(MAKEWORD(2, 0), &wsaData);
- GPR_ASSERT(status == 0);
-}
-
-static void winsock_shutdown(void) {
- int status = WSACleanup();
- GPR_ASSERT(status == 0);
-}
-
-static void iomgr_platform_init(void) {
- winsock_init();
- grpc_iocp_init();
- grpc_pollset_global_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 "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/iomgr/sockaddr_windows.h"
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/iomgr/pollset_windows.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/socket_windows.h"
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "src/core/lib/iomgr/timer.h"
+
+extern grpc_tcp_server_vtable grpc_windows_tcp_server_vtable;
+extern grpc_tcp_client_vtable grpc_windows_tcp_client_vtable;
+extern grpc_timer_vtable grpc_generic_timer_vtable;
+extern grpc_pollset_vtable grpc_windows_pollset_vtable;
+extern grpc_pollset_set_vtable grpc_windows_pollset_set_vtable;
+extern grpc_address_resolver_vtable grpc_windows_resolver_vtable;
+
+/* Windows' io manager is going to be fully designed using IO completion
+ ports. All of what we're doing here is basically make sure that
+ Windows sockets are initialized in and out. */
+
+static void winsock_init(void) {
+ WSADATA wsaData;
+ int status = WSAStartup(MAKEWORD(2, 0), &wsaData);
+ GPR_ASSERT(status == 0);
+}
+
+static void winsock_shutdown(void) {
+ int status = WSACleanup();
+ GPR_ASSERT(status == 0);
+}
+
+static void iomgr_platform_init(void) {
+ winsock_init();
+ grpc_iocp_init();
+ grpc_pollset_global_init();
grpc_wsa_socket_flags_init();
-}
-
-static void iomgr_platform_flush(void) { grpc_iocp_flush(); }
-
-static void iomgr_platform_shutdown(void) {
- grpc_pollset_global_shutdown();
- grpc_iocp_shutdown();
- winsock_shutdown();
-}
-
+}
+
+static void iomgr_platform_flush(void) { grpc_iocp_flush(); }
+
+static void iomgr_platform_shutdown(void) {
+ grpc_pollset_global_shutdown();
+ grpc_iocp_shutdown();
+ winsock_shutdown();
+}
+
static void iomgr_platform_shutdown_background_closure(void) {}
static bool iomgr_platform_is_any_background_poller_thread(void) {
@@ -83,24 +83,24 @@ static bool iomgr_platform_add_closure_to_background_poller(
return false;
}
-static grpc_iomgr_platform_vtable vtable = {
+static grpc_iomgr_platform_vtable vtable = {
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};
-
-void grpc_set_default_iomgr_platform() {
- grpc_set_tcp_client_impl(&grpc_windows_tcp_client_vtable);
- grpc_set_tcp_server_impl(&grpc_windows_tcp_server_vtable);
- grpc_set_timer_impl(&grpc_generic_timer_vtable);
- grpc_set_pollset_vtable(&grpc_windows_pollset_vtable);
- grpc_set_pollset_set_vtable(&grpc_windows_pollset_set_vtable);
- grpc_set_resolver_impl(&grpc_windows_resolver_vtable);
- grpc_set_iomgr_platform_vtable(&vtable);
-}
-
+
+void grpc_set_default_iomgr_platform() {
+ grpc_set_tcp_client_impl(&grpc_windows_tcp_client_vtable);
+ grpc_set_tcp_server_impl(&grpc_windows_tcp_server_vtable);
+ grpc_set_timer_impl(&grpc_generic_timer_vtable);
+ grpc_set_pollset_vtable(&grpc_windows_pollset_vtable);
+ grpc_set_pollset_set_vtable(&grpc_windows_pollset_set_vtable);
+ grpc_set_resolver_impl(&grpc_windows_resolver_vtable);
+ grpc_set_iomgr_platform_vtable(&vtable);
+}
+
bool grpc_iomgr_run_in_background() { return false; }
-#endif /* GRPC_WINSOCK_SOCKET */
+#endif /* GRPC_WINSOCK_SOCKET */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc b/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc
index abc901efbe0..97ebf9411aa 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc
@@ -1,98 +1,98 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#include "src/core/lib/iomgr/is_epollexclusive_available.h"
-
-#ifdef GRPC_LINUX_EPOLL_CREATE1
-
-#include <grpc/support/log.h>
-
-#include <errno.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#include "src/core/lib/iomgr/is_epollexclusive_available.h"
+
+#ifdef GRPC_LINUX_EPOLL_CREATE1
+
+#include <grpc/support/log.h>
+
+#include <errno.h>
#include <sys/epoll.h>
-#include <sys/eventfd.h>
-#include <unistd.h>
-
-#include "src/core/lib/iomgr/sys_epoll_wrapper.h"
-
-/* This polling engine is only relevant on linux kernels supporting epoll() */
-bool grpc_is_epollexclusive_available(void) {
- static bool logged_why_not = false;
-
- int fd = epoll_create1(EPOLL_CLOEXEC);
- if (fd < 0) {
- if (!logged_why_not) {
- gpr_log(GPR_DEBUG,
- "epoll_create1 failed with error: %d. Not using epollex polling "
- "engine.",
- fd);
- logged_why_not = true;
- }
- return false;
- }
- int evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
- if (evfd < 0) {
- if (!logged_why_not) {
- gpr_log(GPR_DEBUG,
- "eventfd failed with error: %d. Not using epollex polling "
- "engine.",
- fd);
- logged_why_not = true;
- }
- close(fd);
- return false;
- }
- struct epoll_event ev;
- /* choose events that should cause an error on
- EPOLLEXCLUSIVE enabled kernels - specifically the combination of
- EPOLLONESHOT and EPOLLEXCLUSIVE */
- ev.events =
- static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLEXCLUSIVE | EPOLLONESHOT);
- ev.data.ptr = nullptr;
- if (epoll_ctl(fd, EPOLL_CTL_ADD, evfd, &ev) != 0) {
- if (errno != EINVAL) {
- if (!logged_why_not) {
- gpr_log(
- GPR_ERROR,
- "epoll_ctl with EPOLLEXCLUSIVE | EPOLLONESHOT failed with error: "
- "%d. Not using epollex polling engine.",
- errno);
- logged_why_not = true;
- }
- close(fd);
- close(evfd);
- return false;
- }
- } else {
- if (!logged_why_not) {
- gpr_log(GPR_DEBUG,
- "epoll_ctl with EPOLLEXCLUSIVE | EPOLLONESHOT succeeded. This is "
- "evidence of no EPOLLEXCLUSIVE support. Not using "
- "epollex polling engine.");
- logged_why_not = true;
- }
- close(fd);
- close(evfd);
- return false;
- }
+#include <sys/eventfd.h>
+#include <unistd.h>
+
+#include "src/core/lib/iomgr/sys_epoll_wrapper.h"
+
+/* This polling engine is only relevant on linux kernels supporting epoll() */
+bool grpc_is_epollexclusive_available(void) {
+ static bool logged_why_not = false;
+
+ int fd = epoll_create1(EPOLL_CLOEXEC);
+ if (fd < 0) {
+ if (!logged_why_not) {
+ gpr_log(GPR_DEBUG,
+ "epoll_create1 failed with error: %d. Not using epollex polling "
+ "engine.",
+ fd);
+ logged_why_not = true;
+ }
+ return false;
+ }
+ int evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
+ if (evfd < 0) {
+ if (!logged_why_not) {
+ gpr_log(GPR_DEBUG,
+ "eventfd failed with error: %d. Not using epollex polling "
+ "engine.",
+ fd);
+ logged_why_not = true;
+ }
+ close(fd);
+ return false;
+ }
+ struct epoll_event ev;
+ /* choose events that should cause an error on
+ EPOLLEXCLUSIVE enabled kernels - specifically the combination of
+ EPOLLONESHOT and EPOLLEXCLUSIVE */
+ ev.events =
+ static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLEXCLUSIVE | EPOLLONESHOT);
+ ev.data.ptr = nullptr;
+ if (epoll_ctl(fd, EPOLL_CTL_ADD, evfd, &ev) != 0) {
+ if (errno != EINVAL) {
+ if (!logged_why_not) {
+ gpr_log(
+ GPR_ERROR,
+ "epoll_ctl with EPOLLEXCLUSIVE | EPOLLONESHOT failed with error: "
+ "%d. Not using epollex polling engine.",
+ errno);
+ logged_why_not = true;
+ }
+ close(fd);
+ close(evfd);
+ return false;
+ }
+ } else {
+ if (!logged_why_not) {
+ gpr_log(GPR_DEBUG,
+ "epoll_ctl with EPOLLEXCLUSIVE | EPOLLONESHOT succeeded. This is "
+ "evidence of no EPOLLEXCLUSIVE support. Not using "
+ "epollex polling engine.");
+ logged_why_not = true;
+ }
+ close(fd);
+ close(evfd);
+ return false;
+ }
// Check that EPOLLEXCLUSIVE is supported at all.
ev.events = static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLEXCLUSIVE);
if (epoll_ctl(fd, EPOLL_CTL_ADD, evfd, &ev) != 0) {
@@ -107,13 +107,13 @@ bool grpc_is_epollexclusive_available(void) {
close(evfd);
return false;
}
- close(evfd);
- close(fd);
- return true;
-}
-
-#else
-
-bool grpc_is_epollexclusive_available(void) { return false; }
-
-#endif
+ close(evfd);
+ close(fd);
+ return true;
+}
+
+#else
+
+bool grpc_is_epollexclusive_available(void) { return false; }
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.h b/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.h
index 8a44113c3f7..1577fb7a521 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.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_CORE_LIB_IOMGR_IS_EPOLLEXCLUSIVE_AVAILABLE_H
-#define GRPC_CORE_LIB_IOMGR_IS_EPOLLEXCLUSIVE_AVAILABLE_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-bool grpc_is_epollexclusive_available(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* GRPC_CORE_LIB_IOMGR_IS_EPOLLEXCLUSIVE_AVAILABLE_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_IOMGR_IS_EPOLLEXCLUSIVE_AVAILABLE_H
+#define GRPC_CORE_LIB_IOMGR_IS_EPOLLEXCLUSIVE_AVAILABLE_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+bool grpc_is_epollexclusive_available(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GRPC_CORE_LIB_IOMGR_IS_EPOLLEXCLUSIVE_AVAILABLE_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/load_file.cc b/contrib/libs/grpc/src/core/lib/iomgr/load_file.cc
index 4bed6275dca..4a98eb0d3ba 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/load_file.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/load_file.cc
@@ -1,81 +1,81 @@
-/*
- *
- * 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/iomgr/load_file.h"
-
-#include <errno.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/string.h"
-#include "src/core/lib/iomgr/block_annotate.h"
-
-grpc_error* grpc_load_file(const char* filename, int add_null_terminator,
- grpc_slice* output) {
- unsigned char* contents = nullptr;
- size_t contents_size = 0;
- grpc_slice result = grpc_empty_slice();
- FILE* file;
- size_t bytes_read = 0;
- grpc_error* error = GRPC_ERROR_NONE;
-
- GRPC_SCHEDULING_START_BLOCKING_REGION;
- file = fopen(filename, "rb");
- if (file == nullptr) {
- error = GRPC_OS_ERROR(errno, "fopen");
- goto end;
- }
- fseek(file, 0, SEEK_END);
- /* Converting to size_t on the assumption that it will not fail */
- contents_size = static_cast<size_t>(ftell(file));
- fseek(file, 0, SEEK_SET);
- contents = static_cast<unsigned char*>(
- gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)));
- bytes_read = fread(contents, 1, contents_size, file);
- if (bytes_read < contents_size) {
+/*
+ *
+ * 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/iomgr/load_file.h"
+
+#include <errno.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/string.h"
+#include "src/core/lib/iomgr/block_annotate.h"
+
+grpc_error* grpc_load_file(const char* filename, int add_null_terminator,
+ grpc_slice* output) {
+ unsigned char* contents = nullptr;
+ size_t contents_size = 0;
+ grpc_slice result = grpc_empty_slice();
+ FILE* file;
+ size_t bytes_read = 0;
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
+ file = fopen(filename, "rb");
+ if (file == nullptr) {
+ error = GRPC_OS_ERROR(errno, "fopen");
+ goto end;
+ }
+ fseek(file, 0, SEEK_END);
+ /* Converting to size_t on the assumption that it will not fail */
+ contents_size = static_cast<size_t>(ftell(file));
+ fseek(file, 0, SEEK_SET);
+ contents = static_cast<unsigned char*>(
+ gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)));
+ bytes_read = fread(contents, 1, contents_size, file);
+ if (bytes_read < contents_size) {
gpr_free(contents);
- error = GRPC_OS_ERROR(errno, "fread");
- GPR_ASSERT(ferror(file));
- goto end;
- }
- if (add_null_terminator) {
- contents[contents_size++] = 0;
- }
- result = grpc_slice_new(contents, contents_size, gpr_free);
-
-end:
- *output = result;
- if (file != nullptr) fclose(file);
- if (error != GRPC_ERROR_NONE) {
- grpc_error* error_out =
- grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Failed to load file", &error, 1),
- GRPC_ERROR_STR_FILENAME,
- grpc_slice_from_copied_string(
- filename)); // TODO(ncteisen), always static?
- GRPC_ERROR_UNREF(error);
- error = error_out;
- }
- GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX;
- return error;
-}
+ error = GRPC_OS_ERROR(errno, "fread");
+ GPR_ASSERT(ferror(file));
+ goto end;
+ }
+ if (add_null_terminator) {
+ contents[contents_size++] = 0;
+ }
+ result = grpc_slice_new(contents, contents_size, gpr_free);
+
+end:
+ *output = result;
+ if (file != nullptr) fclose(file);
+ if (error != GRPC_ERROR_NONE) {
+ grpc_error* error_out =
+ grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Failed to load file", &error, 1),
+ GRPC_ERROR_STR_FILENAME,
+ grpc_slice_from_copied_string(
+ filename)); // TODO(ncteisen), always static?
+ GRPC_ERROR_UNREF(error);
+ error = error_out;
+ }
+ GRPC_SCHEDULING_END_BLOCKING_REGION_NO_EXEC_CTX;
+ return error;
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/load_file.h b/contrib/libs/grpc/src/core/lib/iomgr/load_file.h
index 1cb2b5de731..03647b306a3 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/load_file.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/load_file.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_LOAD_FILE_H
#define GRPC_CORE_LIB_IOMGR_LOAD_FILE_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdio.h>
#include <grpc/slice.h>
@@ -29,7 +29,7 @@
/* Loads the content of a file into a slice. add_null_terminator will add
a NULL terminator if non-zero. */
-grpc_error* grpc_load_file(const char* filename, int add_null_terminator,
- grpc_slice* slice);
+grpc_error* grpc_load_file(const char* filename, int add_null_terminator,
+ grpc_slice* slice);
#endif /* GRPC_CORE_LIB_IOMGR_LOAD_FILE_H */
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 4b28af4ba4b..17013e5ee7d 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/lockfree_event.h"
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/debug/trace.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/lockfree_event.h"
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-
+
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:
- kClosureReady : The fd has an I/O event of interest but there is no
- closure yet to execute
-
- kClosureNotReady : The fd has no I/O event of interest
-
- closure ptr : The closure to be executed when the fd has an I/O
- event of interest
-
- shutdown_error | kShutdownBit :
- 'shutdown_error' field ORed with kShutdownBit.
- This indicates that the fd is shutdown. Since all
- memory allocations are word-aligned, the lower two
- bits of the shutdown_error pointer are always 0. So
- it is safe to OR these with kShutdownBit
-
- Valid state transitions:
-
- <closure ptr> <-----3------ kClosureNotReady -----1-------> kClosureReady
- | | ^ | ^ | |
- | | | | | | |
- | +--------------4----------+ 6 +---------2---------------+ |
- | | |
- | v |
- +-----5-------> [shutdown_error | kShutdownBit] <-------7---------+
-
- For 1, 4 : See SetReady() function
- For 2, 3 : See NotifyOn() function
- For 5,6,7: See SetShutdown() function */
-
-namespace grpc_core {
-
-LockfreeEvent::LockfreeEvent() { InitEvent(); }
-
-void LockfreeEvent::InitEvent() {
- /* Perform an atomic store to start the state machine.
-
- Note carefully that LockfreeEvent *MAY* be used whilst in a destroyed
- state, while a file descriptor is on a freelist. In such a state it may
- be SetReady'd, and so we need to perform an atomic operation here to
- ensure no races */
- gpr_atm_no_barrier_store(&state_, kClosureNotReady);
-}
-
-void LockfreeEvent::DestroyEvent() {
- gpr_atm curr;
- do {
- curr = gpr_atm_no_barrier_load(&state_);
- if (curr & kShutdownBit) {
- GRPC_ERROR_UNREF((grpc_error*)(curr & ~kShutdownBit));
- } else {
- GPR_ASSERT(curr == kClosureNotReady || curr == kClosureReady);
- }
- /* we CAS in a shutdown, no error value here. If this event is interacted
- with post-deletion (see the note in the constructor) we want the bit
- pattern to prevent error retention in a deleted object */
- } while (!gpr_atm_no_barrier_cas(&state_, curr,
- kShutdownBit /* shutdown, no error */));
-}
-
-void LockfreeEvent::NotifyOn(grpc_closure* closure) {
- while (true) {
+
+/* 'state' holds the to call when the fd is readable or writable respectively.
+ It can contain one of the following values:
+ kClosureReady : The fd has an I/O event of interest but there is no
+ closure yet to execute
+
+ kClosureNotReady : The fd has no I/O event of interest
+
+ closure ptr : The closure to be executed when the fd has an I/O
+ event of interest
+
+ shutdown_error | kShutdownBit :
+ 'shutdown_error' field ORed with kShutdownBit.
+ This indicates that the fd is shutdown. Since all
+ memory allocations are word-aligned, the lower two
+ bits of the shutdown_error pointer are always 0. So
+ it is safe to OR these with kShutdownBit
+
+ Valid state transitions:
+
+ <closure ptr> <-----3------ kClosureNotReady -----1-------> kClosureReady
+ | | ^ | ^ | |
+ | | | | | | |
+ | +--------------4----------+ 6 +---------2---------------+ |
+ | | |
+ | v |
+ +-----5-------> [shutdown_error | kShutdownBit] <-------7---------+
+
+ For 1, 4 : See SetReady() function
+ For 2, 3 : See NotifyOn() function
+ For 5,6,7: See SetShutdown() function */
+
+namespace grpc_core {
+
+LockfreeEvent::LockfreeEvent() { InitEvent(); }
+
+void LockfreeEvent::InitEvent() {
+ /* Perform an atomic store to start the state machine.
+
+ Note carefully that LockfreeEvent *MAY* be used whilst in a destroyed
+ state, while a file descriptor is on a freelist. In such a state it may
+ be SetReady'd, and so we need to perform an atomic operation here to
+ ensure no races */
+ gpr_atm_no_barrier_store(&state_, kClosureNotReady);
+}
+
+void LockfreeEvent::DestroyEvent() {
+ gpr_atm curr;
+ do {
+ curr = gpr_atm_no_barrier_load(&state_);
+ if (curr & kShutdownBit) {
+ GRPC_ERROR_UNREF((grpc_error*)(curr & ~kShutdownBit));
+ } else {
+ GPR_ASSERT(curr == kClosureNotReady || curr == kClosureReady);
+ }
+ /* we CAS in a shutdown, no error value here. If this event is interacted
+ with post-deletion (see the note in the constructor) we want the bit
+ pattern to prevent error retention in a deleted object */
+ } while (!gpr_atm_no_barrier_cas(&state_, curr,
+ kShutdownBit /* shutdown, no error */));
+}
+
+void LockfreeEvent::NotifyOn(grpc_closure* closure) {
+ while (true) {
/* This load needs to be an acquire load because this can be a shutdown
* error that we might need to reference. Adding acquire semantics makes
* sure that the shutdown error has been initialized properly before us
@@ -97,159 +97,159 @@ void LockfreeEvent::NotifyOn(grpc_closure* closure) {
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,
- (void*)curr, closure);
- }
- switch (curr) {
- case kClosureNotReady: {
- /* kClosureNotReady -> <closure>.
-
- We're guaranteed by API that there's an acquire barrier before here,
- so there's no need to double-dip and this can be a release-only.
-
- The release itself pairs with the acquire half of a set_ready full
- barrier. */
- if (gpr_atm_rel_cas(&state_, kClosureNotReady, (gpr_atm)closure)) {
- return; /* Successful. Return */
- }
-
- break; /* retry */
- }
-
- case kClosureReady: {
- /* Change the state to kClosureNotReady. Schedule the closure if
- successful. If not, the state most likely transitioned to shutdown.
- We should retry.
-
- This can be a no-barrier cas since the state is being transitioned to
- kClosureNotReady; set_ready and set_shutdown do not schedule any
- 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)) {
+ (void*)curr, closure);
+ }
+ switch (curr) {
+ case kClosureNotReady: {
+ /* kClosureNotReady -> <closure>.
+
+ We're guaranteed by API that there's an acquire barrier before here,
+ so there's no need to double-dip and this can be a release-only.
+
+ The release itself pairs with the acquire half of a set_ready full
+ barrier. */
+ if (gpr_atm_rel_cas(&state_, kClosureNotReady, (gpr_atm)closure)) {
+ return; /* Successful. Return */
+ }
+
+ break; /* retry */
+ }
+
+ case kClosureReady: {
+ /* Change the state to kClosureNotReady. Schedule the closure if
+ successful. If not, the state most likely transitioned to shutdown.
+ We should retry.
+
+ This can be a no-barrier cas since the state is being transitioned to
+ kClosureNotReady; set_ready and set_shutdown do not schedule any
+ 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);
- return; /* Successful. Return */
- }
-
- break; /* retry */
- }
-
- default: {
- /* 'curr' is either a closure or the fd is shutdown(in which case 'curr'
- contains a pointer to the shutdown-error). If the fd is shutdown,
- schedule the closure with the shutdown error */
- if ((curr & kShutdownBit) > 0) {
- grpc_error* shutdown_err = (grpc_error*)(curr & ~kShutdownBit);
+ return; /* Successful. Return */
+ }
+
+ break; /* retry */
+ }
+
+ default: {
+ /* 'curr' is either a closure or the fd is shutdown(in which case 'curr'
+ contains a pointer to the shutdown-error). If the fd is shutdown,
+ 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));
- return;
- }
-
- /* There is already a closure!. This indicates a bug in the code */
- gpr_log(GPR_ERROR,
- "LockfreeEvent::NotifyOn: notify_on called with a previous "
- "callback still pending");
- abort();
- }
- }
- }
-
- GPR_UNREACHABLE_CODE(return );
-}
-
-bool LockfreeEvent::SetShutdown(grpc_error* shutdown_err) {
- gpr_atm new_state = (gpr_atm)shutdown_err | kShutdownBit;
-
- while (true) {
- gpr_atm curr = gpr_atm_no_barrier_load(&state_);
+ return;
+ }
+
+ /* There is already a closure!. This indicates a bug in the code */
+ gpr_log(GPR_ERROR,
+ "LockfreeEvent::NotifyOn: notify_on called with a previous "
+ "callback still pending");
+ abort();
+ }
+ }
+ }
+
+ GPR_UNREACHABLE_CODE(return );
+}
+
+bool LockfreeEvent::SetShutdown(grpc_error* shutdown_err) {
+ gpr_atm new_state = (gpr_atm)shutdown_err | kShutdownBit;
+
+ 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",
- &state_, (void*)curr, grpc_error_string(shutdown_err));
- }
- switch (curr) {
- case kClosureReady:
- case kClosureNotReady:
- /* Need a full barrier here so that the initial load in notify_on
- doesn't need a barrier */
- if (gpr_atm_full_cas(&state_, curr, new_state)) {
- return true; /* early out */
- }
- break; /* retry */
-
- default: {
- /* 'curr' is either a closure or the fd is already shutdown */
-
- /* If fd is already shutdown, we are done */
- if ((curr & kShutdownBit) > 0) {
- GRPC_ERROR_UNREF(shutdown_err);
- return false;
- }
-
- /* Fd is not shutdown. Schedule the closure and move the state to
- shutdown state.
- Needs an acquire to pair with setting the closure (and get a
- 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)) {
+ &state_, (void*)curr, grpc_error_string(shutdown_err));
+ }
+ switch (curr) {
+ case kClosureReady:
+ case kClosureNotReady:
+ /* Need a full barrier here so that the initial load in notify_on
+ doesn't need a barrier */
+ if (gpr_atm_full_cas(&state_, curr, new_state)) {
+ return true; /* early out */
+ }
+ break; /* retry */
+
+ default: {
+ /* 'curr' is either a closure or the fd is already shutdown */
+
+ /* If fd is already shutdown, we are done */
+ if ((curr & kShutdownBit) > 0) {
+ GRPC_ERROR_UNREF(shutdown_err);
+ return false;
+ }
+
+ /* Fd is not shutdown. Schedule the closure and move the state to
+ shutdown state.
+ Needs an acquire to pair with setting the closure (and get a
+ 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));
- return true;
- }
-
- /* 'curr' was a closure but now changed to a different state. We will
- have to retry */
- break;
- }
- }
- }
-
- GPR_UNREACHABLE_CODE(return false);
-}
-
-void LockfreeEvent::SetReady() {
- while (true) {
- gpr_atm curr = gpr_atm_no_barrier_load(&state_);
-
+ return true;
+ }
+
+ /* 'curr' was a closure but now changed to a different state. We will
+ have to retry */
+ break;
+ }
+ }
+ }
+
+ GPR_UNREACHABLE_CODE(return false);
+}
+
+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_,
- (void*)curr);
- }
-
- switch (curr) {
- case kClosureReady: {
- /* Already ready. We are done here */
- return;
- }
-
- case kClosureNotReady: {
- /* No barrier required as we're transitioning to a state that does not
- involve a closure */
- if (gpr_atm_no_barrier_cas(&state_, kClosureNotReady, kClosureReady)) {
- return; /* early out */
- }
- break; /* retry */
- }
-
- default: {
- /* 'curr' is either a closure or the fd is shutdown */
- if ((curr & kShutdownBit) > 0) {
- /* The fd is shutdown. Do nothing */
- return;
- }
- /* Full cas: acquire pairs with this cas' release in the event of a
- 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)) {
+ (void*)curr);
+ }
+
+ switch (curr) {
+ case kClosureReady: {
+ /* Already ready. We are done here */
+ return;
+ }
+
+ case kClosureNotReady: {
+ /* No barrier required as we're transitioning to a state that does not
+ involve a closure */
+ if (gpr_atm_no_barrier_cas(&state_, kClosureNotReady, kClosureReady)) {
+ return; /* early out */
+ }
+ break; /* retry */
+ }
+
+ default: {
+ /* 'curr' is either a closure or the fd is shutdown */
+ if ((curr & kShutdownBit) > 0) {
+ /* The fd is shutdown. Do nothing */
+ return;
+ }
+ /* Full cas: acquire pairs with this cas' release in the event of a
+ 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);
- return;
- }
- /* else the state changed again (only possible by either a racing
- set_ready or set_shutdown functions. In both these cases, the closure
- would have been scheduled for execution. So we are done here */
- return;
- }
- }
- }
-}
-
-} // namespace grpc_core
+ return;
+ }
+ /* else the state changed again (only possible by either a racing
+ set_ready or set_shutdown functions. In both these cases, the closure
+ would have been scheduled for execution. So we are done here */
+ return;
+ }
+ }
+ }
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.h b/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.h
index d6a6c226bc0..1fcf0a9fc26 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.h
@@ -1,72 +1,72 @@
-/*
- *
- * 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_IOMGR_LOCKFREE_EVENT_H
-#define GRPC_CORE_LIB_IOMGR_LOCKFREE_EVENT_H
-
-/* Lock free event notification for file descriptors */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/atm.h>
-
-#include "src/core/lib/iomgr/closure.h"
-
-namespace grpc_core {
-
-class LockfreeEvent {
- public:
- LockfreeEvent();
-
- LockfreeEvent(const LockfreeEvent&) = delete;
- LockfreeEvent& operator=(const LockfreeEvent&) = delete;
-
- // These methods are used to initialize and destroy the internal state. These
- // cannot be done in constructor and destructor because SetReady may be called
- // when the event is destroyed and put in a freelist.
- void InitEvent();
- void DestroyEvent();
-
- // Returns true if fd has been shutdown, false otherwise.
- bool IsShutdown() const {
- return (gpr_atm_no_barrier_load(&state_) & kShutdownBit) != 0;
- }
-
- // Schedules \a closure when the event is received (see SetReady()) or the
- // shutdown state has been set. Note that the event may have already been
- // received, in which case the closure would be scheduled immediately.
- // If the shutdown state has already been set, then \a closure is scheduled
- // with the shutdown error.
- void NotifyOn(grpc_closure* closure);
-
- // Sets the shutdown state. If a closure had been provided by NotifyOn and has
- // not yet been scheduled, it will be scheduled with \a error.
- bool SetShutdown(grpc_error* error);
-
- // Signals that the event has been received.
- void SetReady();
-
- private:
- enum State { kClosureNotReady = 0, kClosureReady = 2, kShutdownBit = 1 };
-
- gpr_atm state_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_IOMGR_LOCKFREE_EVENT_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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_LOCKFREE_EVENT_H
+#define GRPC_CORE_LIB_IOMGR_LOCKFREE_EVENT_H
+
+/* Lock free event notification for file descriptors */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/support/atm.h>
+
+#include "src/core/lib/iomgr/closure.h"
+
+namespace grpc_core {
+
+class LockfreeEvent {
+ public:
+ LockfreeEvent();
+
+ LockfreeEvent(const LockfreeEvent&) = delete;
+ LockfreeEvent& operator=(const LockfreeEvent&) = delete;
+
+ // These methods are used to initialize and destroy the internal state. These
+ // cannot be done in constructor and destructor because SetReady may be called
+ // when the event is destroyed and put in a freelist.
+ void InitEvent();
+ void DestroyEvent();
+
+ // Returns true if fd has been shutdown, false otherwise.
+ bool IsShutdown() const {
+ return (gpr_atm_no_barrier_load(&state_) & kShutdownBit) != 0;
+ }
+
+ // Schedules \a closure when the event is received (see SetReady()) or the
+ // shutdown state has been set. Note that the event may have already been
+ // received, in which case the closure would be scheduled immediately.
+ // If the shutdown state has already been set, then \a closure is scheduled
+ // with the shutdown error.
+ void NotifyOn(grpc_closure* closure);
+
+ // Sets the shutdown state. If a closure had been provided by NotifyOn and has
+ // not yet been scheduled, it will be scheduled with \a error.
+ bool SetShutdown(grpc_error* error);
+
+ // Signals that the event has been received.
+ void SetReady();
+
+ private:
+ enum State { kClosureNotReady = 0, kClosureReady = 2, kShutdownBit = 1 };
+
+ gpr_atm state_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_IOMGR_LOCKFREE_EVENT_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/nameser.h b/contrib/libs/grpc/src/core/lib/iomgr/nameser.h
index 22a00cdab8b..e3ac2a715e0 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/nameser.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/nameser.h
@@ -1,106 +1,106 @@
-/*
- *
- * 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_IOMGR_NAMESER_H
-#define GRPC_CORE_LIB_IOMGR_NAMESER_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_HAVE_ARPA_NAMESER
-
-#include <arpa/nameser.h>
-
-#else /* GRPC_HAVE_ARPA_NAMESER */
-
-typedef enum __ns_class {
- ns_c_invalid = 0, /* Cookie. */
- ns_c_in = 1, /* Internet. */
- ns_c_2 = 2, /* unallocated/unsupported. */
- ns_c_chaos = 3, /* MIT Chaos-net. */
- ns_c_hs = 4, /* MIT Hesiod. */
- /* Query class values which do not appear in resource records */
- ns_c_none = 254, /* for prereq. sections in update requests */
- ns_c_any = 255, /* Wildcard match. */
- ns_c_max = 65536
-} ns_class;
-
-typedef enum __ns_type {
- ns_t_invalid = 0, /* Cookie. */
- ns_t_a = 1, /* Host address. */
- ns_t_ns = 2, /* Authoritative server. */
- ns_t_md = 3, /* Mail destination. */
- ns_t_mf = 4, /* Mail forwarder. */
- ns_t_cname = 5, /* Canonical name. */
- ns_t_soa = 6, /* Start of authority zone. */
- ns_t_mb = 7, /* Mailbox domain name. */
- ns_t_mg = 8, /* Mail group member. */
- ns_t_mr = 9, /* Mail rename name. */
- ns_t_null = 10, /* Null resource record. */
- ns_t_wks = 11, /* Well known service. */
- ns_t_ptr = 12, /* Domain name pointer. */
- ns_t_hinfo = 13, /* Host information. */
- ns_t_minfo = 14, /* Mailbox information. */
- ns_t_mx = 15, /* Mail routing information. */
- ns_t_txt = 16, /* Text strings. */
- ns_t_rp = 17, /* Responsible person. */
- ns_t_afsdb = 18, /* AFS cell database. */
- ns_t_x25 = 19, /* X_25 calling address. */
- ns_t_isdn = 20, /* ISDN calling address. */
- ns_t_rt = 21, /* Router. */
- ns_t_nsap = 22, /* NSAP address. */
- ns_t_nsap_ptr = 23, /* Reverse NSAP lookup (deprecated). */
- ns_t_sig = 24, /* Security signature. */
- ns_t_key = 25, /* Security key. */
- ns_t_px = 26, /* X.400 mail mapping. */
- ns_t_gpos = 27, /* Geographical position (withdrawn). */
- ns_t_aaaa = 28, /* Ip6 Address. */
- ns_t_loc = 29, /* Location Information. */
- ns_t_nxt = 30, /* Next domain (security). */
- ns_t_eid = 31, /* Endpoint identifier. */
- ns_t_nimloc = 32, /* Nimrod Locator. */
- ns_t_srv = 33, /* Server Selection. */
- ns_t_atma = 34, /* ATM Address */
- ns_t_naptr = 35, /* Naming Authority PoinTeR */
- ns_t_kx = 36, /* Key Exchange */
- ns_t_cert = 37, /* Certification record */
- ns_t_a6 = 38, /* IPv6 address (deprecates AAAA) */
- ns_t_dname = 39, /* Non-terminal DNAME (for IPv6) */
- ns_t_sink = 40, /* Kitchen sink (experimentatl) */
- ns_t_opt = 41, /* EDNS0 option (meta-RR) */
- ns_t_apl = 42, /* Address prefix list (RFC3123) */
- ns_t_ds = 43, /* Delegation Signer (RFC4034) */
- ns_t_sshfp = 44, /* SSH Key Fingerprint (RFC4255) */
- ns_t_rrsig = 46, /* Resource Record Signature (RFC4034) */
- ns_t_nsec = 47, /* Next Secure (RFC4034) */
- ns_t_dnskey = 48, /* DNS Public Key (RFC4034) */
- ns_t_tkey = 249, /* Transaction key */
- ns_t_tsig = 250, /* Transaction signature. */
- ns_t_ixfr = 251, /* Incremental zone transfer. */
- ns_t_axfr = 252, /* Transfer zone of authority. */
- ns_t_mailb = 253, /* Transfer mailbox records. */
- ns_t_maila = 254, /* Transfer mail agent records. */
- ns_t_any = 255, /* Wildcard match. */
- ns_t_zxfr = 256, /* BIND-specific, nonstandard. */
- ns_t_max = 65536
-} ns_type;
-
-#endif /* GRPC_HAVE_ARPA_NAMESER */
-
-#endif /* GRPC_CORE_LIB_IOMGR_NAMESER_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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_NAMESER_H
+#define GRPC_CORE_LIB_IOMGR_NAMESER_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_HAVE_ARPA_NAMESER
+
+#include <arpa/nameser.h>
+
+#else /* GRPC_HAVE_ARPA_NAMESER */
+
+typedef enum __ns_class {
+ ns_c_invalid = 0, /* Cookie. */
+ ns_c_in = 1, /* Internet. */
+ ns_c_2 = 2, /* unallocated/unsupported. */
+ ns_c_chaos = 3, /* MIT Chaos-net. */
+ ns_c_hs = 4, /* MIT Hesiod. */
+ /* Query class values which do not appear in resource records */
+ ns_c_none = 254, /* for prereq. sections in update requests */
+ ns_c_any = 255, /* Wildcard match. */
+ ns_c_max = 65536
+} ns_class;
+
+typedef enum __ns_type {
+ ns_t_invalid = 0, /* Cookie. */
+ ns_t_a = 1, /* Host address. */
+ ns_t_ns = 2, /* Authoritative server. */
+ ns_t_md = 3, /* Mail destination. */
+ ns_t_mf = 4, /* Mail forwarder. */
+ ns_t_cname = 5, /* Canonical name. */
+ ns_t_soa = 6, /* Start of authority zone. */
+ ns_t_mb = 7, /* Mailbox domain name. */
+ ns_t_mg = 8, /* Mail group member. */
+ ns_t_mr = 9, /* Mail rename name. */
+ ns_t_null = 10, /* Null resource record. */
+ ns_t_wks = 11, /* Well known service. */
+ ns_t_ptr = 12, /* Domain name pointer. */
+ ns_t_hinfo = 13, /* Host information. */
+ ns_t_minfo = 14, /* Mailbox information. */
+ ns_t_mx = 15, /* Mail routing information. */
+ ns_t_txt = 16, /* Text strings. */
+ ns_t_rp = 17, /* Responsible person. */
+ ns_t_afsdb = 18, /* AFS cell database. */
+ ns_t_x25 = 19, /* X_25 calling address. */
+ ns_t_isdn = 20, /* ISDN calling address. */
+ ns_t_rt = 21, /* Router. */
+ ns_t_nsap = 22, /* NSAP address. */
+ ns_t_nsap_ptr = 23, /* Reverse NSAP lookup (deprecated). */
+ ns_t_sig = 24, /* Security signature. */
+ ns_t_key = 25, /* Security key. */
+ ns_t_px = 26, /* X.400 mail mapping. */
+ ns_t_gpos = 27, /* Geographical position (withdrawn). */
+ ns_t_aaaa = 28, /* Ip6 Address. */
+ ns_t_loc = 29, /* Location Information. */
+ ns_t_nxt = 30, /* Next domain (security). */
+ ns_t_eid = 31, /* Endpoint identifier. */
+ ns_t_nimloc = 32, /* Nimrod Locator. */
+ ns_t_srv = 33, /* Server Selection. */
+ ns_t_atma = 34, /* ATM Address */
+ ns_t_naptr = 35, /* Naming Authority PoinTeR */
+ ns_t_kx = 36, /* Key Exchange */
+ ns_t_cert = 37, /* Certification record */
+ ns_t_a6 = 38, /* IPv6 address (deprecates AAAA) */
+ ns_t_dname = 39, /* Non-terminal DNAME (for IPv6) */
+ ns_t_sink = 40, /* Kitchen sink (experimentatl) */
+ ns_t_opt = 41, /* EDNS0 option (meta-RR) */
+ ns_t_apl = 42, /* Address prefix list (RFC3123) */
+ ns_t_ds = 43, /* Delegation Signer (RFC4034) */
+ ns_t_sshfp = 44, /* SSH Key Fingerprint (RFC4255) */
+ ns_t_rrsig = 46, /* Resource Record Signature (RFC4034) */
+ ns_t_nsec = 47, /* Next Secure (RFC4034) */
+ ns_t_dnskey = 48, /* DNS Public Key (RFC4034) */
+ ns_t_tkey = 249, /* Transaction key */
+ ns_t_tsig = 250, /* Transaction signature. */
+ ns_t_ixfr = 251, /* Incremental zone transfer. */
+ ns_t_axfr = 252, /* Transfer zone of authority. */
+ ns_t_mailb = 253, /* Transfer mailbox records. */
+ ns_t_maila = 254, /* Transfer mail agent records. */
+ ns_t_any = 255, /* Wildcard match. */
+ ns_t_zxfr = 256, /* BIND-specific, nonstandard. */
+ ns_t_max = 65536
+} ns_type;
+
+#endif /* GRPC_HAVE_ARPA_NAMESER */
+
+#endif /* GRPC_CORE_LIB_IOMGR_NAMESER_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc
index dea07cae537..851f54997e5 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc
@@ -1,96 +1,96 @@
-/*
- *
- * 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 <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/polling_entity.h"
-
-grpc_polling_entity grpc_polling_entity_create_from_pollset_set(
- grpc_pollset_set* pollset_set) {
- grpc_polling_entity pollent;
- pollent.pollent.pollset_set = pollset_set;
- pollent.tag = GRPC_POLLS_POLLSET_SET;
- return pollent;
-}
-
-grpc_polling_entity grpc_polling_entity_create_from_pollset(
- grpc_pollset* pollset) {
- grpc_polling_entity pollent;
- pollent.pollent.pollset = pollset;
- pollent.tag = GRPC_POLLS_POLLSET;
- return pollent;
-}
-
-grpc_pollset* grpc_polling_entity_pollset(grpc_polling_entity* pollent) {
- if (pollent->tag == GRPC_POLLS_POLLSET) {
- return pollent->pollent.pollset;
- }
- return nullptr;
-}
-
-grpc_pollset_set* grpc_polling_entity_pollset_set(
- grpc_polling_entity* pollent) {
- if (pollent->tag == GRPC_POLLS_POLLSET_SET) {
- return pollent->pollent.pollset_set;
- }
- return nullptr;
-}
-
-bool grpc_polling_entity_is_empty(const grpc_polling_entity* pollent) {
- return pollent->tag == GRPC_POLLS_NONE;
-}
-
-void grpc_polling_entity_add_to_pollset_set(grpc_polling_entity* pollent,
- grpc_pollset_set* pss_dst) {
- if (pollent->tag == GRPC_POLLS_POLLSET) {
+/*
+ *
+ * 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 <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/polling_entity.h"
+
+grpc_polling_entity grpc_polling_entity_create_from_pollset_set(
+ grpc_pollset_set* pollset_set) {
+ grpc_polling_entity pollent;
+ pollent.pollent.pollset_set = pollset_set;
+ pollent.tag = GRPC_POLLS_POLLSET_SET;
+ return pollent;
+}
+
+grpc_polling_entity grpc_polling_entity_create_from_pollset(
+ grpc_pollset* pollset) {
+ grpc_polling_entity pollent;
+ pollent.pollent.pollset = pollset;
+ pollent.tag = GRPC_POLLS_POLLSET;
+ return pollent;
+}
+
+grpc_pollset* grpc_polling_entity_pollset(grpc_polling_entity* pollent) {
+ if (pollent->tag == GRPC_POLLS_POLLSET) {
+ return pollent->pollent.pollset;
+ }
+ return nullptr;
+}
+
+grpc_pollset_set* grpc_polling_entity_pollset_set(
+ grpc_polling_entity* pollent) {
+ if (pollent->tag == GRPC_POLLS_POLLSET_SET) {
+ return pollent->pollent.pollset_set;
+ }
+ return nullptr;
+}
+
+bool grpc_polling_entity_is_empty(const grpc_polling_entity* pollent) {
+ return pollent->tag == GRPC_POLLS_NONE;
+}
+
+void grpc_polling_entity_add_to_pollset_set(grpc_polling_entity* pollent,
+ grpc_pollset_set* pss_dst) {
+ if (pollent->tag == GRPC_POLLS_POLLSET) {
// CFStream does not use file destriptors. When CFStream is used, the fd
// pollset is possible to be null.
if (pollent->pollent.pollset != nullptr) {
grpc_pollset_set_add_pollset(pss_dst, pollent->pollent.pollset);
}
- } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) {
- GPR_ASSERT(pollent->pollent.pollset_set != nullptr);
- grpc_pollset_set_add_pollset_set(pss_dst, pollent->pollent.pollset_set);
- } else {
- gpr_log(GPR_ERROR, "Invalid grpc_polling_entity tag '%d'", pollent->tag);
- abort();
- }
-}
-
-void grpc_polling_entity_del_from_pollset_set(grpc_polling_entity* pollent,
- grpc_pollset_set* pss_dst) {
- if (pollent->tag == GRPC_POLLS_POLLSET) {
+ } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) {
+ GPR_ASSERT(pollent->pollent.pollset_set != nullptr);
+ grpc_pollset_set_add_pollset_set(pss_dst, pollent->pollent.pollset_set);
+ } else {
+ gpr_log(GPR_ERROR, "Invalid grpc_polling_entity tag '%d'", pollent->tag);
+ abort();
+ }
+}
+
+void grpc_polling_entity_del_from_pollset_set(grpc_polling_entity* pollent,
+ grpc_pollset_set* pss_dst) {
+ if (pollent->tag == GRPC_POLLS_POLLSET) {
#ifdef GRPC_CFSTREAM
if (pollent->pollent.pollset != nullptr) {
grpc_pollset_set_del_pollset(pss_dst, pollent->pollent.pollset);
}
#else
- GPR_ASSERT(pollent->pollent.pollset != nullptr);
- grpc_pollset_set_del_pollset(pss_dst, pollent->pollent.pollset);
+ GPR_ASSERT(pollent->pollent.pollset != nullptr);
+ grpc_pollset_set_del_pollset(pss_dst, pollent->pollent.pollset);
#endif
- } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) {
- GPR_ASSERT(pollent->pollent.pollset_set != nullptr);
- grpc_pollset_set_del_pollset_set(pss_dst, pollent->pollent.pollset_set);
- } else {
- gpr_log(GPR_ERROR, "Invalid grpc_polling_entity tag '%d'", pollent->tag);
- abort();
- }
-}
+ } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) {
+ GPR_ASSERT(pollent->pollent.pollset_set != nullptr);
+ grpc_pollset_set_del_pollset_set(pss_dst, pollent->pollent.pollset_set);
+ } else {
+ gpr_log(GPR_ERROR, "Invalid grpc_polling_entity tag '%d'", pollent->tag);
+ abort();
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h
index 6f4c5bdd665..49fe21073ad 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h
@@ -1,68 +1,68 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_POLLING_ENTITY_H
#define GRPC_CORE_LIB_IOMGR_POLLING_ENTITY_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_set.h"
-typedef enum grpc_pollset_tag {
- GRPC_POLLS_NONE,
- GRPC_POLLS_POLLSET,
- GRPC_POLLS_POLLSET_SET
-} grpc_pollset_tag;
-
+typedef enum grpc_pollset_tag {
+ GRPC_POLLS_NONE,
+ GRPC_POLLS_POLLSET,
+ GRPC_POLLS_POLLSET_SET
+} grpc_pollset_tag;
+
/* A grpc_polling_entity is a pollset-or-pollset_set container. It allows
- * functions that accept a pollset XOR a pollset_set to do so through an
- * abstract interface. No ownership is taken. */
+ * functions that accept a pollset XOR a pollset_set to do so through an
+ * abstract interface. No ownership is taken. */
struct grpc_polling_entity {
union {
grpc_pollset* pollset = nullptr;
- grpc_pollset_set* pollset_set;
+ grpc_pollset_set* pollset_set;
} pollent;
grpc_pollset_tag tag = GRPC_POLLS_NONE;
};
grpc_polling_entity grpc_polling_entity_create_from_pollset_set(
- grpc_pollset_set* pollset_set);
+ grpc_pollset_set* pollset_set);
grpc_polling_entity grpc_polling_entity_create_from_pollset(
- grpc_pollset* pollset);
+ grpc_pollset* pollset);
/** If \a pollent contains a pollset, return it. Otherwise, return NULL */
-grpc_pollset* grpc_polling_entity_pollset(grpc_polling_entity* pollent);
+grpc_pollset* grpc_polling_entity_pollset(grpc_polling_entity* pollent);
/** If \a pollent contains a pollset_set, return it. Otherwise, return NULL */
-grpc_pollset_set* grpc_polling_entity_pollset_set(grpc_polling_entity* pollent);
+grpc_pollset_set* grpc_polling_entity_pollset_set(grpc_polling_entity* pollent);
-bool grpc_polling_entity_is_empty(const grpc_polling_entity* pollent);
+bool grpc_polling_entity_is_empty(const grpc_polling_entity* pollent);
/** Add the pollset or pollset_set in \a pollent to the destination pollset_set
- * \a * pss_dst */
-void grpc_polling_entity_add_to_pollset_set(grpc_polling_entity* pollent,
- grpc_pollset_set* pss_dst);
+ * \a * pss_dst */
+void grpc_polling_entity_add_to_pollset_set(grpc_polling_entity* pollent,
+ grpc_pollset_set* pss_dst);
/** Delete the pollset or pollset_set in \a pollent from the destination
- * pollset_set \a * pss_dst */
-void grpc_polling_entity_del_from_pollset_set(grpc_polling_entity* pollent,
- grpc_pollset_set* pss_dst);
+ * pollset_set \a * pss_dst */
+void grpc_polling_entity_del_from_pollset_set(grpc_polling_entity* pollent,
+ grpc_pollset_set* pss_dst);
#endif /* GRPC_CORE_LIB_IOMGR_POLLING_ENTITY_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset.cc
index ebfef1dbc76..fac1da0a67a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset.cc
@@ -1,56 +1,56 @@
-/*
- *
- * 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/lib/iomgr/pollset.h"
-
-grpc_pollset_vtable* grpc_pollset_impl;
-
-void grpc_set_pollset_vtable(grpc_pollset_vtable* vtable) {
- grpc_pollset_impl = vtable;
-}
-
-void grpc_pollset_global_init() { grpc_pollset_impl->global_init(); }
-
-void grpc_pollset_global_shutdown() { grpc_pollset_impl->global_shutdown(); }
-
-void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
- grpc_pollset_impl->init(pollset, mu);
-}
-
-void grpc_pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
- grpc_pollset_impl->shutdown(pollset, closure);
-}
-
-void grpc_pollset_destroy(grpc_pollset* pollset) {
- grpc_pollset_impl->destroy(pollset);
-}
-
-grpc_error* grpc_pollset_work(grpc_pollset* pollset,
- grpc_pollset_worker** worker,
- grpc_millis deadline) {
- return grpc_pollset_impl->work(pollset, worker, deadline);
-}
-
-grpc_error* grpc_pollset_kick(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker) {
- return grpc_pollset_impl->kick(pollset, specific_worker);
-}
-
-size_t grpc_pollset_size(void) { return grpc_pollset_impl->pollset_size(); }
+/*
+ *
+ * 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/lib/iomgr/pollset.h"
+
+grpc_pollset_vtable* grpc_pollset_impl;
+
+void grpc_set_pollset_vtable(grpc_pollset_vtable* vtable) {
+ grpc_pollset_impl = vtable;
+}
+
+void grpc_pollset_global_init() { grpc_pollset_impl->global_init(); }
+
+void grpc_pollset_global_shutdown() { grpc_pollset_impl->global_shutdown(); }
+
+void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
+ grpc_pollset_impl->init(pollset, mu);
+}
+
+void grpc_pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
+ grpc_pollset_impl->shutdown(pollset, closure);
+}
+
+void grpc_pollset_destroy(grpc_pollset* pollset) {
+ grpc_pollset_impl->destroy(pollset);
+}
+
+grpc_error* grpc_pollset_work(grpc_pollset* pollset,
+ grpc_pollset_worker** worker,
+ grpc_millis deadline) {
+ return grpc_pollset_impl->work(pollset, worker, deadline);
+}
+
+grpc_error* grpc_pollset_kick(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker) {
+ return grpc_pollset_impl->kick(pollset, specific_worker);
+}
+
+size_t grpc_pollset_size(void) { return grpc_pollset_impl->pollset_size(); }
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset.h b/contrib/libs/grpc/src/core/lib/iomgr/pollset.h
index 28472b360d6..a20614e9085 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -20,13 +20,13 @@
#define GRPC_CORE_LIB_IOMGR_POLLSET_H
#include <grpc/support/port_platform.h>
-
+
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
#include "src/core/lib/iomgr/exec_ctx.h"
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount;
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount;
/* A grpc_pollset is a set of file descriptors that a higher level item is
interested in. For example:
@@ -38,31 +38,31 @@ extern grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount;
typedef struct grpc_pollset grpc_pollset;
typedef struct grpc_pollset_worker grpc_pollset_worker;
-typedef struct grpc_pollset_vtable {
- void (*global_init)(void);
- void (*global_shutdown)(void);
- void (*init)(grpc_pollset* pollset, gpr_mu** mu);
- void (*shutdown)(grpc_pollset* pollset, grpc_closure* closure);
- void (*destroy)(grpc_pollset* pollset);
- grpc_error* (*work)(grpc_pollset* pollset, grpc_pollset_worker** worker,
- grpc_millis deadline);
- grpc_error* (*kick)(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker);
- size_t (*pollset_size)(void);
-} grpc_pollset_vtable;
-
-void grpc_set_pollset_vtable(grpc_pollset_vtable* vtable);
-
-void grpc_pollset_global_init(void);
-void grpc_pollset_global_shutdown(void);
-
+typedef struct grpc_pollset_vtable {
+ void (*global_init)(void);
+ void (*global_shutdown)(void);
+ void (*init)(grpc_pollset* pollset, gpr_mu** mu);
+ void (*shutdown)(grpc_pollset* pollset, grpc_closure* closure);
+ void (*destroy)(grpc_pollset* pollset);
+ grpc_error* (*work)(grpc_pollset* pollset, grpc_pollset_worker** worker,
+ grpc_millis deadline);
+ grpc_error* (*kick)(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker);
+ size_t (*pollset_size)(void);
+} grpc_pollset_vtable;
+
+void grpc_set_pollset_vtable(grpc_pollset_vtable* vtable);
+
+void grpc_pollset_global_init(void);
+void grpc_pollset_global_shutdown(void);
+
size_t grpc_pollset_size(void);
-/* Initialize a pollset: assumes *pollset contains all zeros */
-void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu);
+/* Initialize a pollset: assumes *pollset contains all zeros */
+void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu);
/* Begin shutting down the pollset, and call closure when done.
* pollset's mutex must be held */
-void grpc_pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure);
-void grpc_pollset_destroy(grpc_pollset* pollset);
+void grpc_pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure);
+void grpc_pollset_destroy(grpc_pollset* pollset);
/* Do some work on a pollset.
May involve invoking asynchronous callbacks, or actually polling file
@@ -78,22 +78,22 @@ void grpc_pollset_destroy(grpc_pollset* pollset);
and it is guaranteed that it will not be released by grpc_pollset_work
AFTER worker has been destroyed.
- It's legal for worker to be NULL: in that case, this specific thread can not
- be directly woken with a kick, but maybe be indirectly (with a kick against
- the pollset as a whole).
-
+ It's legal for worker to be NULL: in that case, this specific thread can not
+ be directly woken with a kick, but maybe be indirectly (with a kick against
+ the pollset as a whole).
+
Tries not to block past deadline.
May call grpc_closure_list_run on grpc_closure_list, without holding the
pollset
lock */
-grpc_error* grpc_pollset_work(grpc_pollset* pollset,
- grpc_pollset_worker** worker,
- grpc_millis deadline) GRPC_MUST_USE_RESULT;
+grpc_error* grpc_pollset_work(grpc_pollset* pollset,
+ grpc_pollset_worker** worker,
+ grpc_millis deadline) GRPC_MUST_USE_RESULT;
/* Break one polling thread out of polling work for this pollset.
- If specific_worker is non-NULL, then kick that worker. */
-grpc_error* grpc_pollset_kick(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker)
+ If specific_worker is non-NULL, then kick that worker. */
+grpc_error* grpc_pollset_kick(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker)
GRPC_MUST_USE_RESULT;
#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_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 98c8e64e2f0..1f07027e386 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#include <stddef.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/iomgr/closure.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/pollset.h"
-#include "src/core/lib/iomgr/pollset_custom.h"
-#include "src/core/lib/iomgr/timer.h"
-
-#include "src/core/lib/debug/trace.h"
-
-static grpc_custom_poller_vtable* poller_vtable;
-
-struct grpc_pollset {
- gpr_mu mu;
-};
-
-static size_t pollset_size() { return sizeof(grpc_pollset); }
-
-static void pollset_global_init() { poller_vtable->init(); }
-
-static void pollset_global_shutdown() { poller_vtable->shutdown(); }
-
-static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- gpr_mu_init(&pollset->mu);
- *mu = &pollset->mu;
-}
-
+/*
+ *
+ * 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/lib/iomgr/port.h"
+
+#include <stddef.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/pollset.h"
+#include "src/core/lib/iomgr/pollset_custom.h"
+#include "src/core/lib/iomgr/timer.h"
+
+#include "src/core/lib/debug/trace.h"
+
+static grpc_custom_poller_vtable* poller_vtable;
+
+struct grpc_pollset {
+ gpr_mu mu;
+};
+
+static size_t pollset_size() { return sizeof(grpc_pollset); }
+
+static void pollset_global_init() { poller_vtable->init(); }
+
+static void pollset_global_shutdown() { poller_vtable->shutdown(); }
+
+static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ gpr_mu_init(&pollset->mu);
+ *mu = &pollset->mu;
+}
+
static void pollset_shutdown(grpc_pollset* /*pollset*/, grpc_closure* closure) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
-}
-
-static void pollset_destroy(grpc_pollset* pollset) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- gpr_mu_destroy(&pollset->mu);
-}
-
-static grpc_error* pollset_work(grpc_pollset* pollset,
+}
+
+static void pollset_destroy(grpc_pollset* pollset) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ gpr_mu_destroy(&pollset->mu);
+}
+
+static grpc_error* pollset_work(grpc_pollset* pollset,
grpc_pollset_worker** /*worker_hdl*/,
- grpc_millis deadline) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- gpr_mu_unlock(&pollset->mu);
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
+ grpc_millis deadline) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ gpr_mu_unlock(&pollset->mu);
+ grpc_millis now = grpc_core::ExecCtx::Get()->Now();
grpc_millis timeout = 0;
- if (deadline > now) {
- timeout = deadline - now;
- }
- // We yield here because the poll() call might yield
- // control back to the application
- grpc_core::ExecCtx* curr = grpc_core::ExecCtx::Get();
- grpc_core::ExecCtx::Set(nullptr);
+ if (deadline > now) {
+ timeout = deadline - now;
+ }
+ // We yield here because the poll() call might yield
+ // control back to the application
+ grpc_core::ExecCtx* curr = grpc_core::ExecCtx::Get();
+ grpc_core::ExecCtx::Set(nullptr);
poller_vtable->poll(static_cast<size_t>(timeout));
- grpc_core::ExecCtx::Set(curr);
- grpc_core::ExecCtx::Get()->InvalidateNow();
- if (grpc_core::ExecCtx::Get()->HasWork()) {
- grpc_core::ExecCtx::Get()->Flush();
- }
- gpr_mu_lock(&pollset->mu);
- return GRPC_ERROR_NONE;
-}
-
+ grpc_core::ExecCtx::Set(curr);
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+ if (grpc_core::ExecCtx::Get()->HasWork()) {
+ grpc_core::ExecCtx::Get()->Flush();
+ }
+ gpr_mu_lock(&pollset->mu);
+ return GRPC_ERROR_NONE;
+}
+
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;
-}
-
-grpc_pollset_vtable custom_pollset_vtable = {
- pollset_global_init, pollset_global_shutdown,
- pollset_init, pollset_shutdown,
- pollset_destroy, pollset_work,
- pollset_kick, pollset_size};
-
-void grpc_custom_pollset_init(grpc_custom_poller_vtable* vtable) {
- poller_vtable = vtable;
- grpc_set_pollset_vtable(&custom_pollset_vtable);
-}
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ poller_vtable->kick();
+ return GRPC_ERROR_NONE;
+}
+
+grpc_pollset_vtable custom_pollset_vtable = {
+ pollset_global_init, pollset_global_shutdown,
+ pollset_init, pollset_shutdown,
+ pollset_destroy, pollset_work,
+ pollset_kick, pollset_size};
+
+void grpc_custom_pollset_init(grpc_custom_poller_vtable* vtable) {
+ poller_vtable = vtable;
+ grpc_set_pollset_vtable(&custom_pollset_vtable);
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.h b/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.h
index 9e2027f7f4a..7eb94cccb4f 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_POLLSET_CUSTOM_H
-#define GRPC_CORE_LIB_IOMGR_POLLSET_CUSTOM_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stddef.h>
-
-typedef struct grpc_custom_poller_vtable {
- void (*init)();
- void (*poll)(size_t timeout_ms);
- void (*kick)();
- void (*shutdown)();
-} grpc_custom_poller_vtable;
-
-void grpc_custom_pollset_init(grpc_custom_poller_vtable* vtable);
-
-#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_CUSTOM_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_LIB_IOMGR_POLLSET_CUSTOM_H
+#define GRPC_CORE_LIB_IOMGR_POLLSET_CUSTOM_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stddef.h>
+
+typedef struct grpc_custom_poller_vtable {
+ void (*init)();
+ void (*poll)(size_t timeout_ms);
+ void (*kick)();
+ void (*shutdown)();
+} grpc_custom_poller_vtable;
+
+void grpc_custom_pollset_init(grpc_custom_poller_vtable* vtable);
+
+#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_CUSTOM_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.cc
index 42a647a7376..309250a33c9 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.cc
@@ -1,55 +1,55 @@
-/*
- *
- * 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/lib/iomgr/pollset_set.h"
-
-grpc_pollset_set_vtable* grpc_pollset_set_impl;
-
-void grpc_set_pollset_set_vtable(grpc_pollset_set_vtable* vtable) {
- grpc_pollset_set_impl = vtable;
-}
-
-grpc_pollset_set* grpc_pollset_set_create() {
- return grpc_pollset_set_impl->create();
-}
-
-void grpc_pollset_set_destroy(grpc_pollset_set* pollset_set) {
- grpc_pollset_set_impl->destroy(pollset_set);
-}
-
-void grpc_pollset_set_add_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {
- grpc_pollset_set_impl->add_pollset(pollset_set, pollset);
-}
-
-void grpc_pollset_set_del_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {
- grpc_pollset_set_impl->del_pollset(pollset_set, pollset);
-}
-
-void grpc_pollset_set_add_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item) {
- grpc_pollset_set_impl->add_pollset_set(bag, item);
-}
-
-void grpc_pollset_set_del_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item) {
- grpc_pollset_set_impl->del_pollset_set(bag, item);
-}
+/*
+ *
+ * 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/lib/iomgr/pollset_set.h"
+
+grpc_pollset_set_vtable* grpc_pollset_set_impl;
+
+void grpc_set_pollset_set_vtable(grpc_pollset_set_vtable* vtable) {
+ grpc_pollset_set_impl = vtable;
+}
+
+grpc_pollset_set* grpc_pollset_set_create() {
+ return grpc_pollset_set_impl->create();
+}
+
+void grpc_pollset_set_destroy(grpc_pollset_set* pollset_set) {
+ grpc_pollset_set_impl->destroy(pollset_set);
+}
+
+void grpc_pollset_set_add_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {
+ grpc_pollset_set_impl->add_pollset(pollset_set, pollset);
+}
+
+void grpc_pollset_set_del_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {
+ grpc_pollset_set_impl->del_pollset(pollset_set, pollset);
+}
+
+void grpc_pollset_set_add_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item) {
+ grpc_pollset_set_impl->add_pollset_set(bag, item);
+}
+
+void grpc_pollset_set_del_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item) {
+ grpc_pollset_set_impl->del_pollset_set(bag, item);
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.h b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.h
index d3355b8ff8c..80bad98fe97 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_POLLSET_SET_H
#define GRPC_CORE_LIB_IOMGR_POLLSET_SET_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/pollset.h"
/* A grpc_pollset_set is a set of pollsets that are interested in an
@@ -30,26 +30,26 @@
typedef struct grpc_pollset_set grpc_pollset_set;
-typedef struct grpc_pollset_set_vtable {
- grpc_pollset_set* (*create)(void);
- void (*destroy)(grpc_pollset_set* pollset_set);
- void (*add_pollset)(grpc_pollset_set* pollset_set, grpc_pollset* pollset);
- void (*del_pollset)(grpc_pollset_set* pollset_set, grpc_pollset* pollset);
- void (*add_pollset_set)(grpc_pollset_set* bag, grpc_pollset_set* item);
- void (*del_pollset_set)(grpc_pollset_set* bag, grpc_pollset_set* item);
-} grpc_pollset_set_vtable;
-
-void grpc_set_pollset_set_vtable(grpc_pollset_set_vtable* vtable);
-
-grpc_pollset_set* grpc_pollset_set_create(void);
-void grpc_pollset_set_destroy(grpc_pollset_set* pollset_set);
-void grpc_pollset_set_add_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset);
-void grpc_pollset_set_del_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset);
-void grpc_pollset_set_add_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item);
-void grpc_pollset_set_del_pollset_set(grpc_pollset_set* bag,
- grpc_pollset_set* item);
-
+typedef struct grpc_pollset_set_vtable {
+ grpc_pollset_set* (*create)(void);
+ void (*destroy)(grpc_pollset_set* pollset_set);
+ void (*add_pollset)(grpc_pollset_set* pollset_set, grpc_pollset* pollset);
+ void (*del_pollset)(grpc_pollset_set* pollset_set, grpc_pollset* pollset);
+ void (*add_pollset_set)(grpc_pollset_set* bag, grpc_pollset_set* item);
+ void (*del_pollset_set)(grpc_pollset_set* bag, grpc_pollset_set* item);
+} grpc_pollset_set_vtable;
+
+void grpc_set_pollset_set_vtable(grpc_pollset_set_vtable* vtable);
+
+grpc_pollset_set* grpc_pollset_set_create(void);
+void grpc_pollset_set_destroy(grpc_pollset_set* pollset_set);
+void grpc_pollset_set_add_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset);
+void grpc_pollset_set_del_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset);
+void grpc_pollset_set_add_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item);
+void grpc_pollset_set_del_pollset_set(grpc_pollset_set* bag,
+ grpc_pollset_set* item);
+
#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_SET_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.cc
index 2c1df608197..24b047eb8e1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#include "src/core/lib/iomgr/pollset_set.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"
+
+#include "src/core/lib/iomgr/pollset_set.h"
+
static grpc_pollset_set* pollset_set_create(void) {
- return (grpc_pollset_set*)((intptr_t)0xdeafbeef);
-}
-
+ return (grpc_pollset_set*)((intptr_t)0xdeafbeef);
+}
+
static void pollset_set_destroy(grpc_pollset_set* /*pollset_set*/) {}
-
+
static void pollset_set_add_pollset(grpc_pollset_set* /*pollset_set*/,
grpc_pollset* /*pollset*/) {}
-
+
static void pollset_set_del_pollset(grpc_pollset_set* /*pollset_set*/,
grpc_pollset* /*pollset*/) {}
-
+
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 grpc_pollset_set_vtable vtable = {
- pollset_set_create, pollset_set_destroy,
- pollset_set_add_pollset, pollset_set_del_pollset,
- pollset_set_add_pollset_set, pollset_set_del_pollset_set};
-
-void grpc_custom_pollset_set_init() { grpc_set_pollset_set_vtable(&vtable); }
+
+static grpc_pollset_set_vtable vtable = {
+ pollset_set_create, pollset_set_destroy,
+ pollset_set_add_pollset, pollset_set_del_pollset,
+ pollset_set_add_pollset_set, pollset_set_del_pollset_set};
+
+void grpc_custom_pollset_set_init() { grpc_set_pollset_set_vtable(&vtable); }
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.h b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.h
index 80e19a1fef9..e95a9fa4bf3 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_custom.h
@@ -1,26 +1,26 @@
-/*
- *
- * 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_POLLSET_SET_CUSTOM_H
-#define GRPC_CORE_LIB_IOMGR_POLLSET_SET_CUSTOM_H
-
-#include <grpc/support/port_platform.h>
-
-void grpc_custom_pollset_set_init();
-
-#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_SET_CUSTOM_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_LIB_IOMGR_POLLSET_SET_CUSTOM_H
+#define GRPC_CORE_LIB_IOMGR_POLLSET_SET_CUSTOM_H
+
+#include <grpc/support/port_platform.h>
+
+void grpc_custom_pollset_set_init();
+
+#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_SET_CUSTOM_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.cc
index bb9e7f5d28d..45e8bb28a32 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <stdint.h>
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include "src/core/lib/iomgr/pollset_set_windows.h"
-
-static grpc_pollset_set* pollset_set_create(void) {
- return (grpc_pollset_set*)((intptr_t)0xdeafbeef);
-}
-
-static void pollset_set_destroy(grpc_pollset_set* pollset_set) {}
-
-static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {}
-
-static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
- grpc_pollset* pollset) {}
-
-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) {}
-
-grpc_pollset_set_vtable grpc_windows_pollset_set_vtable = {
- pollset_set_create, pollset_set_destroy,
- pollset_set_add_pollset, pollset_set_del_pollset,
- pollset_set_add_pollset_set, pollset_set_del_pollset_set};
-
-#endif /* GRPC_WINSOCK_SOCKET */
+/*
+ *
+ * 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 <stdint.h>
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/iomgr/pollset_set_windows.h"
+
+static grpc_pollset_set* pollset_set_create(void) {
+ return (grpc_pollset_set*)((intptr_t)0xdeafbeef);
+}
+
+static void pollset_set_destroy(grpc_pollset_set* pollset_set) {}
+
+static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {}
+
+static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
+ grpc_pollset* pollset) {}
+
+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) {}
+
+grpc_pollset_set_vtable grpc_windows_pollset_set_vtable = {
+ pollset_set_create, pollset_set_destroy,
+ pollset_set_add_pollset, pollset_set_del_pollset,
+ pollset_set_add_pollset_set, pollset_set_del_pollset_set};
+
+#endif /* GRPC_WINSOCK_SOCKET */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.h
index 5ac9d1823bd..7f2e1af4ddd 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_set_windows.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_POLLSET_SET_WINDOWS_H
#define GRPC_CORE_LIB_IOMGR_POLLSET_SET_WINDOWS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/pollset_set.h"
#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_SET_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.cc
index 5421a584e95..8f3a6d8d0d6 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.cc
@@ -1,93 +1,93 @@
-/*
- *
- * 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"
-
-#ifdef GRPC_UV
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include "src/core/lib/iomgr/pollset_custom.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"
+
+#ifdef GRPC_UV
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include "src/core/lib/iomgr/pollset_custom.h"
+
#error #include <uv.h>
-
-/* Indicates that grpc_pollset_work should run an iteration of the UV loop
- before running callbacks. This defaults to 1, and should be disabled if
- grpc_pollset_work will be called within the callstack of uv_run */
-int grpc_pollset_work_run_loop = 1;
-
-static bool g_kicked = false;
-
-typedef struct uv_poller_handle {
- uv_timer_t poll_timer;
- uv_timer_t kick_timer;
- int refs;
-} uv_poller_handle;
-
-static uv_poller_handle* g_handle;
-
-static void init() {
- g_handle = (uv_poller_handle*)gpr_malloc(sizeof(uv_poller_handle));
- g_handle->refs = 2;
- uv_timer_init(uv_default_loop(), &g_handle->poll_timer);
- uv_timer_init(uv_default_loop(), &g_handle->kick_timer);
-}
-
-static void empty_timer_cb(uv_timer_t* handle) {}
-
-static void kick_timer_cb(uv_timer_t* handle) { g_kicked = false; }
-
-static void run_loop(size_t timeout) {
- if (grpc_pollset_work_run_loop) {
- if (timeout == 0) {
- uv_run(uv_default_loop(), UV_RUN_NOWAIT);
- } else {
- uv_timer_start(&g_handle->poll_timer, empty_timer_cb, timeout, 0);
- uv_run(uv_default_loop(), UV_RUN_ONCE);
- uv_timer_stop(&g_handle->poll_timer);
- }
- }
-}
-
-static void kick() {
- if (!g_kicked) {
- g_kicked = true;
- uv_timer_start(&g_handle->kick_timer, kick_timer_cb, 0, 0);
- }
-}
-
-static void close_timer_cb(uv_handle_t* handle) {
- g_handle->refs--;
- if (g_handle->refs == 0) {
- gpr_free(g_handle);
- }
-}
-
-static void shutdown() {
- uv_close((uv_handle_t*)&g_handle->poll_timer, close_timer_cb);
- uv_close((uv_handle_t*)&g_handle->kick_timer, close_timer_cb);
- if (grpc_pollset_work_run_loop) {
- GPR_ASSERT(uv_run(uv_default_loop(), UV_RUN_DEFAULT) == 0);
- }
-}
-
-grpc_custom_poller_vtable uv_pollset_vtable = {init, run_loop, kick, shutdown};
-
-#endif /* GRPC_UV */
+
+/* Indicates that grpc_pollset_work should run an iteration of the UV loop
+ before running callbacks. This defaults to 1, and should be disabled if
+ grpc_pollset_work will be called within the callstack of uv_run */
+int grpc_pollset_work_run_loop = 1;
+
+static bool g_kicked = false;
+
+typedef struct uv_poller_handle {
+ uv_timer_t poll_timer;
+ uv_timer_t kick_timer;
+ int refs;
+} uv_poller_handle;
+
+static uv_poller_handle* g_handle;
+
+static void init() {
+ g_handle = (uv_poller_handle*)gpr_malloc(sizeof(uv_poller_handle));
+ g_handle->refs = 2;
+ uv_timer_init(uv_default_loop(), &g_handle->poll_timer);
+ uv_timer_init(uv_default_loop(), &g_handle->kick_timer);
+}
+
+static void empty_timer_cb(uv_timer_t* handle) {}
+
+static void kick_timer_cb(uv_timer_t* handle) { g_kicked = false; }
+
+static void run_loop(size_t timeout) {
+ if (grpc_pollset_work_run_loop) {
+ if (timeout == 0) {
+ uv_run(uv_default_loop(), UV_RUN_NOWAIT);
+ } else {
+ uv_timer_start(&g_handle->poll_timer, empty_timer_cb, timeout, 0);
+ uv_run(uv_default_loop(), UV_RUN_ONCE);
+ uv_timer_stop(&g_handle->poll_timer);
+ }
+ }
+}
+
+static void kick() {
+ if (!g_kicked) {
+ g_kicked = true;
+ uv_timer_start(&g_handle->kick_timer, kick_timer_cb, 0, 0);
+ }
+}
+
+static void close_timer_cb(uv_handle_t* handle) {
+ g_handle->refs--;
+ if (g_handle->refs == 0) {
+ gpr_free(g_handle);
+ }
+}
+
+static void shutdown() {
+ uv_close((uv_handle_t*)&g_handle->poll_timer, close_timer_cb);
+ uv_close((uv_handle_t*)&g_handle->kick_timer, close_timer_cb);
+ if (grpc_pollset_work_run_loop) {
+ GPR_ASSERT(uv_run(uv_default_loop(), UV_RUN_DEFAULT) == 0);
+ }
+}
+
+grpc_custom_poller_vtable uv_pollset_vtable = {init, run_loop, kick, shutdown};
+
+#endif /* GRPC_UV */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.h b/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.h
index de82bcc1d31..9493e651071 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_uv.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,12 +21,12 @@
extern int grpc_pollset_work_run_loop;
-typedef struct grpc_custom_poller_vtable {
- void (*init)(void);
- void (*run_loop)(int blocking);
-} grpc_custom_poller_vtable;
-
-void grpc_custom_pollset_global_init(grpc_custom_poller_vtable* vtable);
-void grpc_custom_pollset_global_shutdown(void);
+typedef struct grpc_custom_poller_vtable {
+ void (*init)(void);
+ void (*run_loop)(int blocking);
+} grpc_custom_poller_vtable;
+void grpc_custom_pollset_global_init(grpc_custom_poller_vtable* vtable);
+void grpc_custom_pollset_global_shutdown(void);
+
#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_UV_H */
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 184c330cf7c..9cc35e415e7 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.cc
@@ -1,228 +1,228 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gprpp/thd.h"
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/pollset.h"
-#include "src/core/lib/iomgr/pollset_windows.h"
-
-#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker*)1)
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount");
-
-gpr_mu grpc_polling_mu;
-static grpc_pollset_worker* g_active_poller;
-static grpc_pollset_worker g_global_root_worker;
-
-static void pollset_global_init(void) {
- gpr_mu_init(&grpc_polling_mu);
- g_active_poller = NULL;
- g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
- g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev =
- &g_global_root_worker;
-}
-
-static void pollset_global_shutdown(void) { gpr_mu_destroy(&grpc_polling_mu); }
-
-static void remove_worker(grpc_pollset_worker* worker,
- grpc_pollset_worker_link_type type) {
- worker->links[type].prev->links[type].next = worker->links[type].next;
- worker->links[type].next->links[type].prev = worker->links[type].prev;
- worker->links[type].next = worker->links[type].prev = worker;
-}
-
-static int has_workers(grpc_pollset_worker* root,
- grpc_pollset_worker_link_type type) {
- return root->links[type].next != root;
-}
-
-static grpc_pollset_worker* pop_front_worker(
- grpc_pollset_worker* root, grpc_pollset_worker_link_type type) {
- if (has_workers(root, type)) {
- grpc_pollset_worker* w = root->links[type].next;
- remove_worker(w, type);
- return w;
- } else {
- return NULL;
- }
-}
-
-static void push_front_worker(grpc_pollset_worker* root,
- grpc_pollset_worker_link_type type,
- grpc_pollset_worker* worker) {
- worker->links[type].prev = root;
- worker->links[type].next = worker->links[type].prev->links[type].next;
- worker->links[type].prev->links[type].next =
- worker->links[type].next->links[type].prev = worker;
-}
-
-static size_t pollset_size(void) { return sizeof(grpc_pollset); }
-
-/* There isn't really any such thing as a pollset under Windows, due to the
- nature of the IO completion ports. We're still going to provide a minimal
- set of features for the sake of the rest of grpc. But grpc_pollset_work
- won't actually do any polling, and return as quickly as possible. */
-
-static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
- *mu = &grpc_polling_mu;
- pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
- pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
- &pollset->root_worker;
-}
-
-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) {
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/pollset.h"
+#include "src/core/lib/iomgr/pollset_windows.h"
+
+#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker*)1)
+
+grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount");
+
+gpr_mu grpc_polling_mu;
+static grpc_pollset_worker* g_active_poller;
+static grpc_pollset_worker g_global_root_worker;
+
+static void pollset_global_init(void) {
+ gpr_mu_init(&grpc_polling_mu);
+ g_active_poller = NULL;
+ g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
+ g_global_root_worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev =
+ &g_global_root_worker;
+}
+
+static void pollset_global_shutdown(void) { gpr_mu_destroy(&grpc_polling_mu); }
+
+static void remove_worker(grpc_pollset_worker* worker,
+ grpc_pollset_worker_link_type type) {
+ worker->links[type].prev->links[type].next = worker->links[type].next;
+ worker->links[type].next->links[type].prev = worker->links[type].prev;
+ worker->links[type].next = worker->links[type].prev = worker;
+}
+
+static int has_workers(grpc_pollset_worker* root,
+ grpc_pollset_worker_link_type type) {
+ return root->links[type].next != root;
+}
+
+static grpc_pollset_worker* pop_front_worker(
+ grpc_pollset_worker* root, grpc_pollset_worker_link_type type) {
+ if (has_workers(root, type)) {
+ grpc_pollset_worker* w = root->links[type].next;
+ remove_worker(w, type);
+ return w;
+ } else {
+ return NULL;
+ }
+}
+
+static void push_front_worker(grpc_pollset_worker* root,
+ grpc_pollset_worker_link_type type,
+ grpc_pollset_worker* worker) {
+ worker->links[type].prev = root;
+ worker->links[type].next = worker->links[type].prev->links[type].next;
+ worker->links[type].prev->links[type].next =
+ worker->links[type].next->links[type].prev = worker;
+}
+
+static size_t pollset_size(void) { return sizeof(grpc_pollset); }
+
+/* There isn't really any such thing as a pollset under Windows, due to the
+ nature of the IO completion ports. We're still going to provide a minimal
+ set of features for the sake of the rest of grpc. But grpc_pollset_work
+ won't actually do any polling, and return as quickly as possible. */
+
+static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
+ *mu = &grpc_polling_mu;
+ pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
+ pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
+ &pollset->root_worker;
+}
+
+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);
- } else {
- pollset->on_shutdown = closure;
- }
-}
-
-static void pollset_destroy(grpc_pollset* pollset) {}
-
-static grpc_error* pollset_work(grpc_pollset* pollset,
- grpc_pollset_worker** worker_hdl,
- grpc_millis deadline) {
- grpc_pollset_worker worker;
- if (worker_hdl) *worker_hdl = &worker;
-
- int added_worker = 0;
- worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
- worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
- worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
- worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev = NULL;
- worker.kicked = 0;
- worker.pollset = pollset;
- gpr_cv_init(&worker.cv);
- if (!pollset->kicked_without_pollers && !pollset->shutting_down) {
- if (g_active_poller == NULL) {
- grpc_pollset_worker* next_worker;
- /* become poller */
- pollset->is_iocp_worker = 1;
- g_active_poller = &worker;
- gpr_mu_unlock(&grpc_polling_mu);
- grpc_iocp_work(deadline);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(&grpc_polling_mu);
- pollset->is_iocp_worker = 0;
- g_active_poller = NULL;
- /* try to get a worker from this pollsets worker list */
- next_worker = pop_front_worker(&pollset->root_worker,
- GRPC_POLLSET_WORKER_LINK_POLLSET);
- if (next_worker == NULL) {
- /* try to get a worker from the global list */
- next_worker = pop_front_worker(&g_global_root_worker,
- GRPC_POLLSET_WORKER_LINK_GLOBAL);
- }
- if (next_worker != NULL) {
- next_worker->kicked = 1;
- gpr_cv_signal(&next_worker->cv);
- }
-
- if (pollset->shutting_down && pollset->on_shutdown != NULL) {
+ } else {
+ pollset->on_shutdown = closure;
+ }
+}
+
+static void pollset_destroy(grpc_pollset* pollset) {}
+
+static grpc_error* pollset_work(grpc_pollset* pollset,
+ grpc_pollset_worker** worker_hdl,
+ grpc_millis deadline) {
+ grpc_pollset_worker worker;
+ if (worker_hdl) *worker_hdl = &worker;
+
+ int added_worker = 0;
+ worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next =
+ worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev =
+ worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].next =
+ worker.links[GRPC_POLLSET_WORKER_LINK_GLOBAL].prev = NULL;
+ worker.kicked = 0;
+ worker.pollset = pollset;
+ gpr_cv_init(&worker.cv);
+ if (!pollset->kicked_without_pollers && !pollset->shutting_down) {
+ if (g_active_poller == NULL) {
+ grpc_pollset_worker* next_worker;
+ /* become poller */
+ pollset->is_iocp_worker = 1;
+ g_active_poller = &worker;
+ gpr_mu_unlock(&grpc_polling_mu);
+ grpc_iocp_work(deadline);
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(&grpc_polling_mu);
+ pollset->is_iocp_worker = 0;
+ g_active_poller = NULL;
+ /* try to get a worker from this pollsets worker list */
+ next_worker = pop_front_worker(&pollset->root_worker,
+ GRPC_POLLSET_WORKER_LINK_POLLSET);
+ if (next_worker == NULL) {
+ /* try to get a worker from the global list */
+ next_worker = pop_front_worker(&g_global_root_worker,
+ GRPC_POLLSET_WORKER_LINK_GLOBAL);
+ }
+ if (next_worker != NULL) {
+ next_worker->kicked = 1;
+ gpr_cv_signal(&next_worker->cv);
+ }
+
+ if (pollset->shutting_down && pollset->on_shutdown != NULL) {
grpc_core::ExecCtx::Run(DEBUG_LOCATION, pollset->on_shutdown,
GRPC_ERROR_NONE);
- pollset->on_shutdown = NULL;
- }
- goto done;
- }
- push_front_worker(&g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL,
- &worker);
- push_front_worker(&pollset->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET,
- &worker);
- added_worker = 1;
- while (!worker.kicked) {
- if (gpr_cv_wait(&worker.cv, &grpc_polling_mu,
- grpc_millis_to_timespec(deadline, GPR_CLOCK_REALTIME))) {
- grpc_core::ExecCtx::Get()->InvalidateNow();
- break;
- }
- grpc_core::ExecCtx::Get()->InvalidateNow();
- }
- } else {
- pollset->kicked_without_pollers = 0;
- }
-done:
- if (!grpc_closure_list_empty(*grpc_core::ExecCtx::Get()->closure_list())) {
- gpr_mu_unlock(&grpc_polling_mu);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(&grpc_polling_mu);
- }
- if (added_worker) {
- remove_worker(&worker, GRPC_POLLSET_WORKER_LINK_GLOBAL);
- remove_worker(&worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
- }
- gpr_cv_destroy(&worker.cv);
- if (worker_hdl) *worker_hdl = NULL;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* pollset_kick(grpc_pollset* p,
- grpc_pollset_worker* specific_worker) {
+ pollset->on_shutdown = NULL;
+ }
+ goto done;
+ }
+ push_front_worker(&g_global_root_worker, GRPC_POLLSET_WORKER_LINK_GLOBAL,
+ &worker);
+ push_front_worker(&pollset->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET,
+ &worker);
+ added_worker = 1;
+ while (!worker.kicked) {
+ if (gpr_cv_wait(&worker.cv, &grpc_polling_mu,
+ grpc_millis_to_timespec(deadline, GPR_CLOCK_REALTIME))) {
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+ break;
+ }
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+ }
+ } else {
+ pollset->kicked_without_pollers = 0;
+ }
+done:
+ if (!grpc_closure_list_empty(*grpc_core::ExecCtx::Get()->closure_list())) {
+ gpr_mu_unlock(&grpc_polling_mu);
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(&grpc_polling_mu);
+ }
+ if (added_worker) {
+ remove_worker(&worker, GRPC_POLLSET_WORKER_LINK_GLOBAL);
+ remove_worker(&worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
+ }
+ gpr_cv_destroy(&worker.cv);
+ if (worker_hdl) *worker_hdl = NULL;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* pollset_kick(grpc_pollset* p,
+ grpc_pollset_worker* specific_worker) {
bool should_kick_global = false;
- if (specific_worker != NULL) {
- if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
+ if (specific_worker != NULL) {
+ if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
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;
+ 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;
- gpr_cv_signal(&specific_worker->cv);
- }
- p->kicked_without_pollers = 1;
- if (p->is_iocp_worker) {
- grpc_iocp_kick();
+ gpr_cv_signal(&specific_worker->cv);
+ }
+ p->kicked_without_pollers = 1;
+ if (p->is_iocp_worker) {
+ grpc_iocp_kick();
should_kick_global = false;
- }
- } else {
- if (p->is_iocp_worker && g_active_poller == specific_worker) {
- grpc_iocp_kick();
- } else {
- specific_worker->kicked = 1;
- gpr_cv_signal(&specific_worker->cv);
- }
- }
- } else {
- specific_worker =
- pop_front_worker(&p->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
- if (specific_worker != NULL) {
- grpc_pollset_kick(p, specific_worker);
- } else if (p->is_iocp_worker) {
- grpc_iocp_kick();
- } else {
- p->kicked_without_pollers = 1;
+ }
+ } else {
+ if (p->is_iocp_worker && g_active_poller == specific_worker) {
+ grpc_iocp_kick();
+ } else {
+ specific_worker->kicked = 1;
+ gpr_cv_signal(&specific_worker->cv);
+ }
+ }
+ } else {
+ specific_worker =
+ pop_front_worker(&p->root_worker, GRPC_POLLSET_WORKER_LINK_POLLSET);
+ if (specific_worker != NULL) {
+ grpc_pollset_kick(p, specific_worker);
+ } else if (p->is_iocp_worker) {
+ 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);
@@ -231,13 +231,13 @@ static grpc_error* pollset_kick(grpc_pollset* p,
gpr_cv_signal(&next_global_worker->cv);
}
}
- return GRPC_ERROR_NONE;
-}
-
-grpc_pollset_vtable grpc_windows_pollset_vtable = {
- pollset_global_init, pollset_global_shutdown,
- pollset_init, pollset_shutdown,
- pollset_destroy, pollset_work,
- pollset_kick, pollset_size};
-
-#endif /* GRPC_WINSOCK_SOCKET */
+ return GRPC_ERROR_NONE;
+}
+
+grpc_pollset_vtable grpc_windows_pollset_vtable = {
+ pollset_global_init, pollset_global_shutdown,
+ pollset_init, pollset_shutdown,
+ pollset_destroy, pollset_work,
+ pollset_kick, pollset_size};
+
+#endif /* GRPC_WINSOCK_SOCKET */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.h
index e89758c6941..3dad4198ebb 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_windows.h
@@ -1,31 +1,31 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_POLLSET_WINDOWS_H
#define GRPC_CORE_LIB_IOMGR_POLLSET_WINDOWS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/support/sync.h>
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
#include "src/core/lib/iomgr/socket_windows.h"
/* There isn't really any such thing as a pollset under Windows, due to the
@@ -40,8 +40,8 @@ typedef enum {
} grpc_pollset_worker_link_type;
typedef struct grpc_pollset_worker_link {
- struct grpc_pollset_worker* next;
- struct grpc_pollset_worker* prev;
+ struct grpc_pollset_worker* next;
+ struct grpc_pollset_worker* prev;
} grpc_pollset_worker_link;
struct grpc_pollset;
@@ -50,7 +50,7 @@ typedef struct grpc_pollset grpc_pollset;
typedef struct grpc_pollset_worker {
gpr_cv cv;
int kicked;
- struct grpc_pollset* pollset;
+ struct grpc_pollset* pollset;
grpc_pollset_worker_link links[GRPC_POLLSET_WORKER_LINK_TYPES];
} grpc_pollset_worker;
@@ -59,12 +59,12 @@ struct grpc_pollset {
int kicked_without_pollers;
int is_iocp_worker;
grpc_pollset_worker root_worker;
- grpc_closure* on_shutdown;
+ grpc_closure* on_shutdown;
};
void grpc_pollset_global_init(void);
void grpc_pollset_global_shutdown(void);
-#endif
-
+#endif
+
#endif /* GRPC_CORE_LIB_IOMGR_POLLSET_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/port.h b/contrib/libs/grpc/src/core/lib/iomgr/port.h
index 2a8d67b261c..321addd8302 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/port.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/port.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,18 +21,18 @@
#ifndef GRPC_CORE_LIB_IOMGR_PORT_H
#define GRPC_CORE_LIB_IOMGR_PORT_H
-#ifdef GRPC_UV
-#ifndef GRPC_CUSTOM_SOCKET
-#define GRPC_CUSTOM_SOCKET
-#endif
-#endif
+#ifdef GRPC_UV
+#ifndef GRPC_CUSTOM_SOCKET
+#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
-#if defined(GRPC_CUSTOM_SOCKET)
-// Do Nothing
+#if defined(GRPC_CUSTOM_SOCKET)
+// Do Nothing
#elif defined(GPR_WINDOWS)
#define GRPC_WINSOCK_SOCKET 1
#define GRPC_WINDOWS_SOCKETUTILS 1
@@ -47,8 +47,8 @@
#define GRPC_POSIX_SOCKETUTILS 1
#define GRPC_POSIX_WAKEUP_FD 1
#elif defined(GPR_LINUX)
-#define GRPC_HAVE_ARPA_NAMESER 1
-#define GRPC_HAVE_IFADDRS 1
+#define GRPC_HAVE_ARPA_NAMESER 1
+#define GRPC_HAVE_IFADDRS 1
#define GRPC_HAVE_IPV6_RECVPKTINFO 1
#define GRPC_HAVE_IP_PKTINFO 1
#define GRPC_HAVE_MSG_NOSIGNAL 1
@@ -62,16 +62,16 @@
#endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) */
#endif /* LINUX_VERSION_CODE */
#define GRPC_LINUX_MULTIPOLL_WITH_EPOLL 1
-#define GRPC_POSIX_FORK 1
-#define GRPC_POSIX_HOST_NAME_MAX 1
+#define GRPC_POSIX_FORK 1
+#define GRPC_POSIX_HOST_NAME_MAX 1
#define GRPC_POSIX_SOCKET 1
#define GRPC_POSIX_WAKEUP_FD 1
#ifdef __GLIBC_PREREQ
-#if __GLIBC_PREREQ(2, 4)
-#define GRPC_LINUX_EPOLL 1
-#endif
+#if __GLIBC_PREREQ(2, 4)
+#define GRPC_LINUX_EPOLL 1
+#endif
#if __GLIBC_PREREQ(2, 9)
-#define GRPC_LINUX_EPOLL_CREATE1 1
+#define GRPC_LINUX_EPOLL_CREATE1 1
#define GRPC_LINUX_EVENTFD 1
#endif
#if __GLIBC_PREREQ(2, 10)
@@ -85,12 +85,12 @@
#define GRPC_LINUX_TCP_H 1
#endif /* __GLIBC_PREREQ(2, 17) */
#endif
-#ifndef __GLIBC__
-#define GRPC_LINUX_EPOLL 1
-#define GRPC_LINUX_EPOLL_CREATE1 1
-#define GRPC_LINUX_EVENTFD 1
-#define GRPC_MSG_IOVLEN_TYPE int
-#endif
+#ifndef __GLIBC__
+#define GRPC_LINUX_EPOLL 1
+#define GRPC_LINUX_EPOLL_CREATE1 1
+#define GRPC_LINUX_EVENTFD 1
+#define GRPC_MSG_IOVLEN_TYPE int
+#endif
#ifndef GRPC_LINUX_EVENTFD
#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
#endif
@@ -98,12 +98,12 @@
#define GRPC_POSIX_SOCKETUTILS
#endif
#elif defined(GPR_APPLE)
-#define GRPC_HAVE_ARPA_NAMESER 1
-#define GRPC_HAVE_IFADDRS 1
+#define GRPC_HAVE_ARPA_NAMESER 1
+#define GRPC_HAVE_IFADDRS 1
#define GRPC_HAVE_SO_NOSIGPIPE 1
#define GRPC_HAVE_UNIX_SOCKET 1
#define GRPC_MSG_IOVLEN_TYPE int
-#define GRPC_POSIX_FORK 1
+#define GRPC_POSIX_FORK 1
#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
#ifdef GRPC_CFSTREAM
#define GRPC_CFSTREAM_IOMGR 1
@@ -129,27 +129,27 @@
#define GRPC_POSIX_SOCKET 1
#endif
#define GRPC_POSIX_SOCKETUTILS 1
-#define GRPC_POSIX_SYSCONF 1
+#define GRPC_POSIX_SYSCONF 1
#define GRPC_POSIX_WAKEUP_FD 1
#elif defined(GPR_FREEBSD)
-#define GRPC_HAVE_ARPA_NAMESER 1
-#define GRPC_HAVE_IFADDRS 1
+#define GRPC_HAVE_ARPA_NAMESER 1
+#define GRPC_HAVE_IFADDRS 1
#define GRPC_HAVE_IPV6_RECVPKTINFO 1
#define GRPC_HAVE_SO_NOSIGPIPE 1
#define GRPC_HAVE_UNIX_SOCKET 1
-#define GRPC_POSIX_FORK 1
-#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
-#define GRPC_POSIX_SOCKET 1
-#define GRPC_POSIX_SOCKETUTILS 1
-#define GRPC_POSIX_WAKEUP_FD 1
-#elif defined(GPR_OPENBSD)
-#define GRPC_HAVE_IFADDRS 1
-#define GRPC_HAVE_IPV6_RECVPKTINFO 1
-#define GRPC_HAVE_UNIX_SOCKET 1
+#define GRPC_POSIX_FORK 1
#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
#define GRPC_POSIX_SOCKET 1
#define GRPC_POSIX_SOCKETUTILS 1
#define GRPC_POSIX_WAKEUP_FD 1
+#elif defined(GPR_OPENBSD)
+#define GRPC_HAVE_IFADDRS 1
+#define GRPC_HAVE_IPV6_RECVPKTINFO 1
+#define GRPC_HAVE_UNIX_SOCKET 1
+#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
+#define GRPC_POSIX_SOCKET 1
+#define GRPC_POSIX_SOCKETUTILS 1
+#define GRPC_POSIX_WAKEUP_FD 1
#elif defined(GPR_SOLARIS)
#define GRPC_HAVE_UNIX_SOCKET 1
#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
@@ -163,7 +163,7 @@
#define GRPC_POSIX_SOCKETUTILS 1
#define GRPC_POSIX_WAKEUP_FD 1
#elif defined(GPR_NACL)
-#define GRPC_HAVE_ARPA_NAMESER 1
+#define GRPC_HAVE_ARPA_NAMESER 1
#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1
#define GRPC_POSIX_SOCKET 1
#define GRPC_POSIX_SOCKETUTILS 1
@@ -191,8 +191,8 @@
#if defined(GRPC_POSIX_SOCKET) + defined(GRPC_WINSOCK_SOCKET) + \
defined(GRPC_CUSTOM_SOCKET) + defined(GRPC_CFSTREAM) != \
1
-#error \
- "Must define exactly one of GRPC_POSIX_SOCKET, GRPC_WINSOCK_SOCKET, GRPC_CUSTOM_SOCKET"
+#error \
+ "Must define exactly one of GRPC_POSIX_SOCKET, GRPC_WINSOCK_SOCKET, GRPC_CUSTOM_SOCKET"
#endif
#ifdef GRPC_POSIX_SOCKET
@@ -214,11 +214,11 @@
#define GRPC_POSIX_SOCKET_UTILS_COMMON 1
#endif
-#if defined(GRPC_POSIX_HOST_NAME_MAX) && defined(GRPC_POSIX_SYSCONF)
-#error "Cannot define both GRPC_POSIX_HOST_NAME_MAX and GRPC_POSIX_SYSCONF"
-#endif
-#if !defined(GRPC_POSIX_HOST_NAME_MAX) && !defined(GRPC_POSIX_SYSCONF)
-#define GRPC_GETHOSTNAME_FALLBACK 1
-#endif
-
+#if defined(GRPC_POSIX_HOST_NAME_MAX) && defined(GRPC_POSIX_SYSCONF)
+#error "Cannot define both GRPC_POSIX_HOST_NAME_MAX and GRPC_POSIX_SYSCONF"
+#endif
+#if !defined(GRPC_POSIX_HOST_NAME_MAX) && !defined(GRPC_POSIX_SYSCONF)
+#define GRPC_GETHOSTNAME_FALLBACK 1
+#endif
+
#endif /* GRPC_CORE_LIB_IOMGR_PORT_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.cc b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.cc
index f2a4676369a..dd8ab278fc6 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.cc
@@ -1,50 +1,50 @@
-/*
- *
- * 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/support/alloc.h>
-#include "src/core/lib/iomgr/resolve_address.h"
-
-grpc_address_resolver_vtable* grpc_resolve_address_impl;
-
-void grpc_set_resolver_impl(grpc_address_resolver_vtable* vtable) {
- grpc_resolve_address_impl = vtable;
-}
-
-void grpc_resolve_address(const char* addr, const char* default_port,
- grpc_pollset_set* interested_parties,
- grpc_closure* on_done,
- grpc_resolved_addresses** addresses) {
- grpc_resolve_address_impl->resolve_address(
- addr, default_port, interested_parties, on_done, addresses);
-}
-
-void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addrs) {
- if (addrs != nullptr) {
- gpr_free(addrs->addrs);
- }
- gpr_free(addrs);
-}
-
-grpc_error* grpc_blocking_resolve_address(const char* name,
- const char* default_port,
- grpc_resolved_addresses** addresses) {
- return grpc_resolve_address_impl->blocking_resolve_address(name, default_port,
- addresses);
-}
+/*
+ *
+ * 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/support/alloc.h>
+#include "src/core/lib/iomgr/resolve_address.h"
+
+grpc_address_resolver_vtable* grpc_resolve_address_impl;
+
+void grpc_set_resolver_impl(grpc_address_resolver_vtable* vtable) {
+ grpc_resolve_address_impl = vtable;
+}
+
+void grpc_resolve_address(const char* addr, const char* default_port,
+ grpc_pollset_set* interested_parties,
+ grpc_closure* on_done,
+ grpc_resolved_addresses** addresses) {
+ grpc_resolve_address_impl->resolve_address(
+ addr, default_port, interested_parties, on_done, addresses);
+}
+
+void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addrs) {
+ if (addrs != nullptr) {
+ gpr_free(addrs->addrs);
+ }
+ gpr_free(addrs);
+}
+
+grpc_error* grpc_blocking_resolve_address(const char* name,
+ const char* default_port,
+ grpc_resolved_addresses** addresses) {
+ return grpc_resolve_address_impl->blocking_resolve_address(name, default_port,
+ addresses);
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h
index 57126c7c938..ddfcba30535 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h
@@ -1,81 +1,81 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_RESOLVE_ADDRESS_H
#define GRPC_CORE_LIB_IOMGR_RESOLVE_ADDRESS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stddef.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_UV
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_UV
#error #include <uv.h>
-#endif
-
-#ifdef GRPC_WINSOCK_SOCKET
-#include <ws2tcpip.h>
-#endif
-
+#endif
+
+#ifdef GRPC_WINSOCK_SOCKET
+#include <ws2tcpip.h>
+#endif
+
#if defined(GRPC_POSIX_SOCKET) || defined(GRPC_CFSTREAM)
-#include <sys/socket.h>
-#endif
-
+#include <sys/socket.h>
+#endif
+
#include "src/core/lib/iomgr/pollset_set.h"
#define GRPC_MAX_SOCKADDR_SIZE 128
struct grpc_resolved_address {
char addr[GRPC_MAX_SOCKADDR_SIZE];
- socklen_t len;
+ socklen_t len;
};
struct grpc_resolved_addresses {
size_t naddrs;
- grpc_resolved_address* addrs;
+ grpc_resolved_address* addrs;
};
-typedef struct grpc_address_resolver_vtable {
- void (*resolve_address)(const char* addr, const char* default_port,
- grpc_pollset_set* interested_parties,
- grpc_closure* on_done,
- grpc_resolved_addresses** addresses);
- grpc_error* (*blocking_resolve_address)(const char* name,
- const char* default_port,
- grpc_resolved_addresses** addresses);
-} grpc_address_resolver_vtable;
-
-void grpc_set_resolver_impl(grpc_address_resolver_vtable* vtable);
-
+typedef struct grpc_address_resolver_vtable {
+ void (*resolve_address)(const char* addr, const char* default_port,
+ grpc_pollset_set* interested_parties,
+ grpc_closure* on_done,
+ grpc_resolved_addresses** addresses);
+ grpc_error* (*blocking_resolve_address)(const char* name,
+ const char* default_port,
+ grpc_resolved_addresses** addresses);
+} grpc_address_resolver_vtable;
+
+void grpc_set_resolver_impl(grpc_address_resolver_vtable* vtable);
+
/* Asynchronously resolve addr. Use default_port if a port isn't designated
in addr, otherwise use the port in addr. */
/* TODO(apolcyn): add a timeout here */
-void grpc_resolve_address(const char* addr, const char* default_port,
- grpc_pollset_set* interested_parties,
- grpc_closure* on_done,
- grpc_resolved_addresses** addresses);
-
+void grpc_resolve_address(const char* addr, const char* default_port,
+ grpc_pollset_set* interested_parties,
+ grpc_closure* on_done,
+ grpc_resolved_addresses** addresses);
+
/* Destroy resolved addresses */
-void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addresses);
+void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addresses);
-/* Resolve addr in a blocking fashion. On success,
+/* Resolve addr in a blocking fashion. On success,
result must be freed with grpc_resolved_addresses_destroy. */
-grpc_error* grpc_blocking_resolve_address(const char* name,
- const char* default_port,
- grpc_resolved_addresses** addresses);
+grpc_error* grpc_blocking_resolve_address(const char* name,
+ const char* default_port,
+ grpc_resolved_addresses** addresses);
#endif /* GRPC_CORE_LIB_IOMGR_RESOLVE_ADDRESS_H */
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 69b4382b2be..d1cc5ea30aa 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
@@ -1,168 +1,168 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/lib/iomgr/resolve_address_custom.h"
-
+
#include <string.h>
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.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/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/host_port.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
#include "src/core/lib/iomgr/port.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+
struct grpc_custom_resolver {
grpc_closure* on_done = nullptr;
grpc_resolved_addresses** addresses = nullptr;
TString host;
TString port;
};
-
-static grpc_custom_resolver_vtable* resolve_address_vtable = nullptr;
-
-static int retry_named_port_failure(grpc_custom_resolver* r,
- grpc_resolved_addresses** res) {
- // This loop is copied from resolve_address_posix.c
- const char* svc[][2] = {{"http", "80"}, {"https", "443"}};
- for (size_t i = 0; i < GPR_ARRAY_SIZE(svc); i++) {
+
+static grpc_custom_resolver_vtable* resolve_address_vtable = nullptr;
+
+static int retry_named_port_failure(grpc_custom_resolver* r,
+ grpc_resolved_addresses** res) {
+ // This loop is copied from resolve_address_posix.c
+ const char* svc[][2] = {{"http", "80"}, {"https", "443"}};
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(svc); i++) {
if (r->port == svc[i][0]) {
r->port = svc[i][1];
- if (res) {
+ if (res) {
grpc_error* error = resolve_address_vtable->resolve(
r->host.c_str(), r->port.c_str(), res);
- if (error != GRPC_ERROR_NONE) {
- GRPC_ERROR_UNREF(error);
- return 0;
- }
- } else {
+ if (error != GRPC_ERROR_NONE) {
+ GRPC_ERROR_UNREF(error);
+ return 0;
+ }
+ } else {
resolve_address_vtable->resolve_async(r, r->host.c_str(),
r->port.c_str());
- }
- return 1;
- }
- }
- return 0;
-}
-
-void grpc_custom_resolve_callback(grpc_custom_resolver* r,
- grpc_resolved_addresses* result,
- grpc_error* error) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ }
+ return 1;
+ }
+ }
+ return 0;
+}
+
+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::ExecCtx exec_ctx;
- if (error == GRPC_ERROR_NONE) {
- *r->addresses = result;
- } else if (retry_named_port_failure(r, nullptr)) {
- return;
- }
- if (r->on_done) {
+ grpc_core::ExecCtx exec_ctx;
+ if (error == GRPC_ERROR_NONE) {
+ *r->addresses = result;
+ } else if (retry_named_port_failure(r, nullptr)) {
+ return;
+ }
+ if (r->on_done) {
grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
- }
+ }
delete r;
-}
-
-static grpc_error* try_split_host_port(const char* name,
+}
+
+static grpc_error* try_split_host_port(const char* name,
const char* default_port,
TString* host, TString* port) {
- /* parse name, splitting it into host and port parts */
+ /* parse name, splitting it into host and port parts */
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());
- }
+ }
if (port->empty()) {
- // TODO(murgatroid99): add tests for this case
- if (default_port == nullptr) {
+ // TODO(murgatroid99): add tests for this case
+ if (default_port == nullptr) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("no port in name '%s'", name).c_str());
- }
+ }
*port = default_port;
- }
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* blocking_resolve_address_impl(
- const char* name, const char* default_port,
- grpc_resolved_addresses** addresses) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
-
+ }
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* blocking_resolve_address_impl(
+ const char* name, const char* default_port,
+ grpc_resolved_addresses** addresses) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+
grpc_custom_resolver resolver;
grpc_error* err =
try_split_host_port(name, default_port, &resolver.host, &resolver.port);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
-
- /* Call getaddrinfo */
- grpc_resolved_addresses* addrs;
- grpc_core::ExecCtx* curr = grpc_core::ExecCtx::Get();
- grpc_core::ExecCtx::Set(nullptr);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+
+ /* Call getaddrinfo */
+ grpc_resolved_addresses* addrs;
+ grpc_core::ExecCtx* curr = grpc_core::ExecCtx::Get();
+ grpc_core::ExecCtx::Set(nullptr);
err = resolve_address_vtable->resolve(resolver.host.c_str(),
resolver.port.c_str(), &addrs);
- if (err != GRPC_ERROR_NONE) {
- if (retry_named_port_failure(&resolver, &addrs)) {
- GRPC_ERROR_UNREF(err);
- err = GRPC_ERROR_NONE;
- }
- }
- grpc_core::ExecCtx::Set(curr);
- if (err == GRPC_ERROR_NONE) {
- *addresses = addrs;
- }
- return err;
-}
-
-static void resolve_address_impl(const char* name, const char* default_port,
+ if (err != GRPC_ERROR_NONE) {
+ if (retry_named_port_failure(&resolver, &addrs)) {
+ GRPC_ERROR_UNREF(err);
+ err = GRPC_ERROR_NONE;
+ }
+ }
+ grpc_core::ExecCtx::Set(curr);
+ if (err == GRPC_ERROR_NONE) {
+ *addresses = addrs;
+ }
+ return err;
+}
+
+static void resolve_address_impl(const char* name, const char* default_port,
grpc_pollset_set* /*interested_parties*/,
- grpc_closure* on_done,
- grpc_resolved_addresses** addrs) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ grpc_closure* on_done,
+ grpc_resolved_addresses** addrs) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
TString host;
TString port;
grpc_error* err = try_split_host_port(name, default_port, &host, &port);
- if (err != GRPC_ERROR_NONE) {
+ if (err != GRPC_ERROR_NONE) {
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, err);
- return;
- }
+ return;
+ }
grpc_custom_resolver* r = new grpc_custom_resolver();
- r->on_done = on_done;
- r->addresses = addrs;
+ r->on_done = on_done;
+ r->addresses = addrs;
r->host = std::move(host);
r->port = std::move(port);
-
- /* Call getaddrinfo */
+
+ /* Call getaddrinfo */
resolve_address_vtable->resolve_async(r, r->host.c_str(), r->port.c_str());
-}
-
-static grpc_address_resolver_vtable custom_resolver_vtable = {
- resolve_address_impl, blocking_resolve_address_impl};
-
-void grpc_custom_resolver_init(grpc_custom_resolver_vtable* impl) {
- resolve_address_vtable = impl;
- grpc_set_resolver_impl(&custom_resolver_vtable);
-}
+}
+
+static grpc_address_resolver_vtable custom_resolver_vtable = {
+ resolve_address_impl, blocking_resolve_address_impl};
+
+void grpc_custom_resolver_init(grpc_custom_resolver_vtable* impl) {
+ resolve_address_vtable = impl;
+ grpc_set_resolver_impl(&custom_resolver_vtable);
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.h b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.h
index f5f68ca32dd..3e7720ff571 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_custom.h
@@ -1,45 +1,45 @@
-/*
- *
- * 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_RESOLVE_ADDRESS_CUSTOM_H
-#define GRPC_CORE_LIB_IOMGR_RESOLVE_ADDRESS_CUSTOM_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-
-typedef struct grpc_custom_resolver grpc_custom_resolver;
-
-typedef struct grpc_custom_resolver_vtable {
+/*
+ *
+ * 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_RESOLVE_ADDRESS_CUSTOM_H
+#define GRPC_CORE_LIB_IOMGR_RESOLVE_ADDRESS_CUSTOM_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+
+typedef struct grpc_custom_resolver grpc_custom_resolver;
+
+typedef 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);
-} grpc_custom_resolver_vtable;
-
-void grpc_custom_resolve_callback(grpc_custom_resolver* resolver,
- grpc_resolved_addresses* result,
- grpc_error* error);
-
-/* Internal APIs */
-void grpc_custom_resolver_init(grpc_custom_resolver_vtable* impl);
-
-#endif /* GRPC_CORE_LIB_IOMGR_RESOLVE_ADDRESS_CUSTOM_H */
+} grpc_custom_resolver_vtable;
+
+void grpc_custom_resolve_callback(grpc_custom_resolver* resolver,
+ grpc_resolved_addresses* result,
+ grpc_error* error);
+
+/* Internal APIs */
+void grpc_custom_resolver_init(grpc_custom_resolver_vtable* impl);
+
+#endif /* GRPC_CORE_LIB_IOMGR_RESOLVE_ADDRESS_CUSTOM_H */
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 4f290873919..b4173c73db1 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
@@ -1,178 +1,178 @@
-/*
- *
- * 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/iomgr/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/iomgr/port.h"
#ifdef GRPC_POSIX_SOCKET_RESOLVE_ADDRESS
-
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include "src/core/lib/iomgr/resolve_address.h"
-
-#include <string.h>
-#include <sys/types.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/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
+
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include "src/core/lib/iomgr/resolve_address.h"
+
+#include <string.h>
+#include <sys/types.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/lib/gpr/string.h"
+#include "src/core/lib/gpr/useful.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"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
-
-static grpc_error* posix_blocking_resolve_address(
- const char* name, const char* default_port,
- grpc_resolved_addresses** addresses) {
- grpc_core::ExecCtx exec_ctx;
- struct addrinfo hints;
- struct addrinfo *result = nullptr, *resp;
- int s;
- size_t i;
- grpc_error* err;
-
- if (name[0] == 'u' && name[1] == 'n' && name[2] == 'i' && name[3] == 'x' &&
- name[4] == ':' && name[5] != 0) {
- return grpc_resolve_unix_domain_address(name + 5, addresses);
- }
-
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/block_annotate.h"
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
+
+static grpc_error* posix_blocking_resolve_address(
+ const char* name, const char* default_port,
+ grpc_resolved_addresses** addresses) {
+ grpc_core::ExecCtx exec_ctx;
+ struct addrinfo hints;
+ struct addrinfo *result = nullptr, *resp;
+ int s;
+ size_t i;
+ grpc_error* err;
+
+ if (name[0] == 'u' && name[1] == 'n' && name[2] == 'i' && name[3] == 'x' &&
+ name[4] == ':' && name[5] != 0) {
+ return grpc_resolve_unix_domain_address(name + 5, addresses);
+ }
+
TString host;
TString port;
- /* parse name, splitting it into host and port parts */
+ /* parse name, splitting it into host and port parts */
grpc_core::SplitHostPort(name, &host, &port);
if (host.empty()) {
- err = grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"),
- GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
- goto done;
- }
+ err = grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"),
+ GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
+ goto done;
+ }
if (port.empty()) {
- if (default_port == nullptr) {
- err = grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("no port in name"),
- GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
- goto done;
- }
+ if (default_port == nullptr) {
+ err = grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("no port in name"),
+ GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
+ goto done;
+ }
port = default_port;
- }
-
- /* Call getaddrinfo */
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
- hints.ai_socktype = SOCK_STREAM; /* stream socket */
- hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
-
- GRPC_SCHEDULING_START_BLOCKING_REGION;
+ }
+
+ /* Call getaddrinfo */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
+ hints.ai_socktype = SOCK_STREAM; /* stream socket */
+ hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
+
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
s = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);
- GRPC_SCHEDULING_END_BLOCKING_REGION;
-
- if (s != 0) {
- /* Retry if well-known service name is recognized */
- const char* svc[][2] = {{"http", "80"}, {"https", "443"}};
- for (i = 0; i < GPR_ARRAY_SIZE(svc); i++) {
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+
+ if (s != 0) {
+ /* Retry if well-known service name is recognized */
+ const char* svc[][2] = {{"http", "80"}, {"https", "443"}};
+ for (i = 0; i < GPR_ARRAY_SIZE(svc); i++) {
if (port == svc[i][0]) {
- GRPC_SCHEDULING_START_BLOCKING_REGION;
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
s = getaddrinfo(host.c_str(), svc[i][1], &hints, &result);
- GRPC_SCHEDULING_END_BLOCKING_REGION;
- break;
- }
- }
- }
-
- if (s != 0) {
- err = grpc_error_set_str(
- grpc_error_set_str(
- grpc_error_set_str(
- grpc_error_set_int(
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+ break;
+ }
+ }
+ }
+
+ if (s != 0) {
+ err = grpc_error_set_str(
+ grpc_error_set_str(
+ grpc_error_set_str(
+ grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_STATIC_STRING(gai_strerror(s)),
- GRPC_ERROR_INT_ERRNO, s),
- GRPC_ERROR_STR_OS_ERROR,
- grpc_slice_from_static_string(gai_strerror(s))),
- GRPC_ERROR_STR_SYSCALL,
- grpc_slice_from_static_string("getaddrinfo")),
- GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
- goto done;
- }
-
- /* Success path: set addrs non-NULL, fill it in */
- *addresses = static_cast<grpc_resolved_addresses*>(
- gpr_malloc(sizeof(grpc_resolved_addresses)));
- (*addresses)->naddrs = 0;
- for (resp = result; resp != nullptr; resp = resp->ai_next) {
- (*addresses)->naddrs++;
- }
- (*addresses)->addrs = static_cast<grpc_resolved_address*>(
- gpr_malloc(sizeof(grpc_resolved_address) * (*addresses)->naddrs));
- i = 0;
- for (resp = result; resp != nullptr; resp = resp->ai_next) {
- memcpy(&(*addresses)->addrs[i].addr, resp->ai_addr, resp->ai_addrlen);
- (*addresses)->addrs[i].len = resp->ai_addrlen;
- i++;
- }
- err = GRPC_ERROR_NONE;
-
-done:
- if (result) {
- freeaddrinfo(result);
- }
- return err;
-}
-
+ GRPC_ERROR_INT_ERRNO, s),
+ GRPC_ERROR_STR_OS_ERROR,
+ grpc_slice_from_static_string(gai_strerror(s))),
+ GRPC_ERROR_STR_SYSCALL,
+ grpc_slice_from_static_string("getaddrinfo")),
+ GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name));
+ goto done;
+ }
+
+ /* Success path: set addrs non-NULL, fill it in */
+ *addresses = static_cast<grpc_resolved_addresses*>(
+ gpr_malloc(sizeof(grpc_resolved_addresses)));
+ (*addresses)->naddrs = 0;
+ for (resp = result; resp != nullptr; resp = resp->ai_next) {
+ (*addresses)->naddrs++;
+ }
+ (*addresses)->addrs = static_cast<grpc_resolved_address*>(
+ gpr_malloc(sizeof(grpc_resolved_address) * (*addresses)->naddrs));
+ i = 0;
+ for (resp = result; resp != nullptr; resp = resp->ai_next) {
+ memcpy(&(*addresses)->addrs[i].addr, resp->ai_addr, resp->ai_addrlen);
+ (*addresses)->addrs[i].len = resp->ai_addrlen;
+ i++;
+ }
+ err = GRPC_ERROR_NONE;
+
+done:
+ if (result) {
+ freeaddrinfo(result);
+ }
+ return err;
+}
+
struct request {
- char* name;
- char* default_port;
- grpc_closure* on_done;
- grpc_resolved_addresses** addrs_out;
- grpc_closure request_closure;
- void* arg;
+ char* name;
+ char* default_port;
+ grpc_closure* on_done;
+ grpc_resolved_addresses** addrs_out;
+ grpc_closure request_closure;
+ void* arg;
};
/* Callback to be passed to grpc Executor to asynch-ify
- * grpc_blocking_resolve_address */
+ * grpc_blocking_resolve_address */
static void do_request_thread(void* rp, grpc_error* /*error*/) {
- request* r = static_cast<request*>(rp);
+ 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));
- gpr_free(r->name);
- gpr_free(r->default_port);
- gpr_free(r);
-}
-
-static void posix_resolve_address(const char* name, const char* default_port,
+ 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_closure* on_done,
- grpc_resolved_addresses** addrs) {
- request* r = static_cast<request*>(gpr_malloc(sizeof(request)));
+ 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);
- r->name = gpr_strdup(name);
- r->default_port = gpr_strdup(default_port);
- r->on_done = on_done;
- r->addrs_out = addrs;
+ 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_address_resolver_vtable grpc_posix_resolver_vtable = {
- posix_resolve_address, posix_blocking_resolve_address};
-#endif
+}
+
+grpc_address_resolver_vtable grpc_posix_resolver_vtable = {
+ posix_resolve_address, posix_blocking_resolve_address};
+#endif
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 9922b88065b..c59407391da 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
@@ -1,154 +1,154 @@
-/*
- *
- * 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/iomgr/port.h"
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include "src/core/lib/iomgr/resolve_address.h"
-
-#include <inttypes.h>
-#include <string.h>
-#include <sys/types.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/iomgr/port.h"
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include "src/core/lib/iomgr/resolve_address.h"
+
+#include <inttypes.h>
+#include <string.h>
+#include <sys/types.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/log_windows.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/gpr/string.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_windows.h>
+#include <grpc/support/string_util.h>
+#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/thd.h"
-#include "src/core/lib/iomgr/block_annotate.h"
-#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/block_annotate.h"
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+
struct request {
- char* name;
- char* default_port;
- grpc_closure request_closure;
- grpc_closure* on_done;
- grpc_resolved_addresses** addresses;
+ char* name;
+ char* default_port;
+ grpc_closure request_closure;
+ grpc_closure* on_done;
+ grpc_resolved_addresses** addresses;
};
-static grpc_error* windows_blocking_resolve_address(
- const char* name, const char* default_port,
- grpc_resolved_addresses** addresses) {
- grpc_core::ExecCtx exec_ctx;
- struct addrinfo hints;
- struct addrinfo *result = NULL, *resp;
- int s;
- size_t i;
- grpc_error* error = GRPC_ERROR_NONE;
-
- /* parse name, splitting it into host and port parts */
+static grpc_error* windows_blocking_resolve_address(
+ const char* name, const char* default_port,
+ grpc_resolved_addresses** addresses) {
+ grpc_core::ExecCtx exec_ctx;
+ struct addrinfo hints;
+ struct addrinfo *result = NULL, *resp;
+ int s;
+ size_t i;
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ /* parse name, splitting it into host and port parts */
TString host;
TString 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());
- goto done;
- }
+ goto done;
+ }
if (port.empty()) {
- if (default_port == NULL) {
+ if (default_port == NULL) {
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrFormat("no port in name '%s'", name).c_str());
- goto done;
- }
+ goto done;
+ }
port = default_port;
- }
-
- /* Call getaddrinfo */
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
- hints.ai_socktype = SOCK_STREAM; /* stream socket */
- hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
-
- GRPC_SCHEDULING_START_BLOCKING_REGION;
+ }
+
+ /* Call getaddrinfo */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
+ hints.ai_socktype = SOCK_STREAM; /* stream socket */
+ hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
+
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
s = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);
- GRPC_SCHEDULING_END_BLOCKING_REGION;
- if (s != 0) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "getaddrinfo");
- goto done;
- }
-
- /* Success path: set addrs non-NULL, fill it in */
- (*addresses) =
- (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses));
- (*addresses)->naddrs = 0;
- for (resp = result; resp != NULL; resp = resp->ai_next) {
- (*addresses)->naddrs++;
- }
- (*addresses)->addrs = (grpc_resolved_address*)gpr_malloc(
- sizeof(grpc_resolved_address) * (*addresses)->naddrs);
- i = 0;
- for (resp = result; resp != NULL; resp = resp->ai_next) {
- memcpy(&(*addresses)->addrs[i].addr, resp->ai_addr, resp->ai_addrlen);
- (*addresses)->addrs[i].len = resp->ai_addrlen;
- i++;
- }
-
-done:
- if (result) {
- freeaddrinfo(result);
- }
- return error;
-}
-
-/* Callback to be passed to grpc_executor to asynch-ify
- * grpc_blocking_resolve_address */
-static void do_request_thread(void* rp, grpc_error* error) {
- request* r = (request*)rp;
- if (error == GRPC_ERROR_NONE) {
- error =
- grpc_blocking_resolve_address(r->name, r->default_port, r->addresses);
- } else {
- GRPC_ERROR_REF(error);
- }
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+ if (s != 0) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "getaddrinfo");
+ goto done;
+ }
+
+ /* Success path: set addrs non-NULL, fill it in */
+ (*addresses) =
+ (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses));
+ (*addresses)->naddrs = 0;
+ for (resp = result; resp != NULL; resp = resp->ai_next) {
+ (*addresses)->naddrs++;
+ }
+ (*addresses)->addrs = (grpc_resolved_address*)gpr_malloc(
+ sizeof(grpc_resolved_address) * (*addresses)->naddrs);
+ i = 0;
+ for (resp = result; resp != NULL; resp = resp->ai_next) {
+ memcpy(&(*addresses)->addrs[i].addr, resp->ai_addr, resp->ai_addrlen);
+ (*addresses)->addrs[i].len = resp->ai_addrlen;
+ i++;
+ }
+
+done:
+ if (result) {
+ freeaddrinfo(result);
+ }
+ return error;
+}
+
+/* Callback to be passed to grpc_executor to asynch-ify
+ * grpc_blocking_resolve_address */
+static void do_request_thread(void* rp, grpc_error* error) {
+ request* r = (request*)rp;
+ if (error == GRPC_ERROR_NONE) {
+ error =
+ grpc_blocking_resolve_address(r->name, r->default_port, r->addresses);
+ } else {
+ GRPC_ERROR_REF(error);
+ }
grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error);
- gpr_free(r->name);
- gpr_free(r->default_port);
- gpr_free(r);
-}
-
-static void windows_resolve_address(const char* name, const char* default_port,
- grpc_pollset_set* interested_parties,
- grpc_closure* on_done,
- grpc_resolved_addresses** addresses) {
- request* r = (request*)gpr_malloc(sizeof(request));
+ gpr_free(r->name);
+ gpr_free(r->default_port);
+ gpr_free(r);
+}
+
+static void windows_resolve_address(const char* name, const char* default_port,
+ grpc_pollset_set* interested_parties,
+ 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);
- r->name = gpr_strdup(name);
- r->default_port = gpr_strdup(default_port);
- r->on_done = on_done;
- r->addresses = addresses;
+ 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_address_resolver_vtable grpc_windows_resolver_vtable = {
- windows_resolve_address, windows_blocking_resolve_address};
-#endif
+}
+
+grpc_address_resolver_vtable grpc_windows_resolver_vtable = {
+ windows_resolve_address, windows_blocking_resolve_address};
+#endif
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 f416e096f46..8403bb0ebc9 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.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/support/port_platform.h>
-
-#include "src/core/lib/iomgr/resource_quota.h"
-
-#include <inttypes.h>
-#include <limits.h>
-#include <stdint.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/resource_quota.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <stdint.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/combiner.h"
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/slice/slice_internal.h"
-
-grpc_core::TraceFlag grpc_resource_quota_trace(false, "resource_quota");
-
-#define MEMORY_USAGE_ESTIMATION_MAX 65536
-
-/* Internal linked list pointers for a resource user */
+
+grpc_core::TraceFlag grpc_resource_quota_trace(false, "resource_quota");
+
+#define MEMORY_USAGE_ESTIMATION_MAX 65536
+
+/* Internal linked list pointers for a resource user */
struct grpc_resource_user_link {
- grpc_resource_user* next;
- grpc_resource_user* prev;
+ grpc_resource_user* next;
+ grpc_resource_user* prev;
};
-/* Resource users are kept in (potentially) several intrusive linked lists
- at once. These are the list names. */
-typedef enum {
- /* Resource users that are waiting for an allocation */
- GRPC_RULIST_AWAITING_ALLOCATION,
- /* Resource users that have free memory available for internal reclamation */
- GRPC_RULIST_NON_EMPTY_FREE_POOL,
- /* Resource users that have published a benign reclamation is available */
- GRPC_RULIST_RECLAIMER_BENIGN,
- /* Resource users that have published a destructive reclamation is
- available */
- GRPC_RULIST_RECLAIMER_DESTRUCTIVE,
- /* Number of lists: must be last */
- GRPC_RULIST_COUNT
-} grpc_rulist;
-
-struct grpc_resource_user {
- /* The quota this resource user consumes from */
- grpc_resource_quota* resource_quota;
-
- /* Closure to schedule an allocation under the resource quota combiner lock */
- grpc_closure allocate_closure;
- /* Closure to publish a non empty free pool under the resource quota combiner
- lock */
- grpc_closure add_to_free_pool_closure;
-
- /* one ref for each ref call (released by grpc_resource_user_unref), and one
- ref for each byte allocated (released by grpc_resource_user_free) */
- gpr_atm refs;
- /* is this resource user unlocked? starts at 0, increases for each shutdown
- call */
- gpr_atm shutdown;
-
- gpr_mu mu;
- /* The amount of memory (in bytes) this user has cached for its own use: to
- avoid quota contention, each resource user can keep some memory in
- addition to what it is immediately using (e.g., for caching), and the quota
- can pull it back under memory pressure.
- This value can become negative if more memory has been requested than
- existed in the free pool, at which point the quota is consulted to bring
- this value non-negative (asynchronously). */
- int64_t free_pool;
- /* A list of closures to call once free_pool becomes non-negative - ie when
- all outstanding allocations have been granted. */
- grpc_closure_list on_allocated;
- /* True if we are currently trying to allocate from the quota, false if not */
- bool allocating;
+/* Resource users are kept in (potentially) several intrusive linked lists
+ at once. These are the list names. */
+typedef enum {
+ /* Resource users that are waiting for an allocation */
+ GRPC_RULIST_AWAITING_ALLOCATION,
+ /* Resource users that have free memory available for internal reclamation */
+ GRPC_RULIST_NON_EMPTY_FREE_POOL,
+ /* Resource users that have published a benign reclamation is available */
+ GRPC_RULIST_RECLAIMER_BENIGN,
+ /* Resource users that have published a destructive reclamation is
+ available */
+ GRPC_RULIST_RECLAIMER_DESTRUCTIVE,
+ /* Number of lists: must be last */
+ GRPC_RULIST_COUNT
+} grpc_rulist;
+
+struct grpc_resource_user {
+ /* The quota this resource user consumes from */
+ grpc_resource_quota* resource_quota;
+
+ /* Closure to schedule an allocation under the resource quota combiner lock */
+ grpc_closure allocate_closure;
+ /* Closure to publish a non empty free pool under the resource quota combiner
+ lock */
+ grpc_closure add_to_free_pool_closure;
+
+ /* one ref for each ref call (released by grpc_resource_user_unref), and one
+ ref for each byte allocated (released by grpc_resource_user_free) */
+ gpr_atm refs;
+ /* is this resource user unlocked? starts at 0, increases for each shutdown
+ call */
+ gpr_atm shutdown;
+
+ gpr_mu mu;
+ /* The amount of memory (in bytes) this user has cached for its own use: to
+ avoid quota contention, each resource user can keep some memory in
+ addition to what it is immediately using (e.g., for caching), and the quota
+ can pull it back under memory pressure.
+ This value can become negative if more memory has been requested than
+ existed in the free pool, at which point the quota is consulted to bring
+ this value non-negative (asynchronously). */
+ int64_t free_pool;
+ /* A list of closures to call once free_pool becomes non-negative - ie when
+ all outstanding allocations have been granted. */
+ grpc_closure_list on_allocated;
+ /* True if we are currently trying to allocate from the quota, false if not */
+ bool allocating;
/* The amount of memory (in bytes) that has been requested from this user
* asynchronously but hasn't been granted yet. */
- int64_t outstanding_allocations;
- /* True if we are currently trying to add ourselves to the non-free quota
- list, false otherwise */
- bool added_to_free_pool;
-
+ int64_t outstanding_allocations;
+ /* True if we are currently trying to add ourselves to the non-free quota
+ list, false otherwise */
+ bool added_to_free_pool;
+
/* The number of threads currently allocated to this resource user */
gpr_atm num_threads_allocated;
- /* Reclaimers: index 0 is the benign reclaimer, 1 is the destructive reclaimer
- */
- grpc_closure* reclaimers[2];
- /* Reclaimers just posted: once we're in the combiner lock, we'll move them
- to the array above */
- grpc_closure* new_reclaimers[2];
- /* Trampoline closures to finish reclamation and re-enter the quota combiner
- lock */
- grpc_closure post_reclaimer_closure[2];
-
- /* Closure to execute under the quota combiner to de-register and shutdown the
- resource user */
- grpc_closure destroy_closure;
-
- /* Links in the various grpc_rulist lists */
- grpc_resource_user_link links[GRPC_RULIST_COUNT];
-
- /* The name of this resource user, for debugging/tracing */
+ /* Reclaimers: index 0 is the benign reclaimer, 1 is the destructive reclaimer
+ */
+ grpc_closure* reclaimers[2];
+ /* Reclaimers just posted: once we're in the combiner lock, we'll move them
+ to the array above */
+ grpc_closure* new_reclaimers[2];
+ /* Trampoline closures to finish reclamation and re-enter the quota combiner
+ lock */
+ grpc_closure post_reclaimer_closure[2];
+
+ /* Closure to execute under the quota combiner to de-register and shutdown the
+ resource user */
+ grpc_closure destroy_closure;
+
+ /* Links in the various grpc_rulist lists */
+ grpc_resource_user_link links[GRPC_RULIST_COUNT];
+
+ /* The name of this resource user, for debugging/tracing */
TString name;
-};
-
-struct grpc_resource_quota {
- /* refcount */
- gpr_refcount refs;
-
- /* estimate of current memory usage
- scaled to the range [0..RESOURCE_USAGE_ESTIMATION_MAX] */
- gpr_atm memory_usage_estimation;
-
- /* Master combiner lock: all activity on a quota executes under this combiner
- * (so no mutex is needed for this data structure) */
+};
+
+struct grpc_resource_quota {
+ /* refcount */
+ gpr_refcount refs;
+
+ /* estimate of current memory usage
+ scaled to the range [0..RESOURCE_USAGE_ESTIMATION_MAX] */
+ gpr_atm memory_usage_estimation;
+
+ /* 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;
- /* Size of the resource quota */
- int64_t size;
- /* Amount of free memory in the resource quota */
- int64_t free_pool;
+ /* Size of the resource quota */
+ int64_t size;
+ /* Amount of free memory in the resource quota */
+ int64_t free_pool;
/* Used size of memory in the resource quota. Updated as soon as the resource
* users start to allocate or free the memory. */
gpr_atm used;
-
- gpr_atm last_size;
-
+
+ gpr_atm last_size;
+
/* Mutex to protect max_threads and num_threads_allocated */
/* Note: We could have used gpr_atm for max_threads and num_threads_allocated
* and avoid having this mutex; but in that case, each invocation of the
@@ -163,240 +163,240 @@ struct grpc_resource_quota {
/* Number of threads currently allocated via this resource_quota object */
int num_threads_allocated;
- /* Has rq_step been scheduled to occur? */
- bool step_scheduled;
-
- /* Are we currently reclaiming memory */
- bool reclaiming;
-
- /* Closure around rq_step */
- grpc_closure rq_step_closure;
-
- /* Closure around rq_reclamation_done */
- grpc_closure rq_reclamation_done_closure;
-
- /* This is only really usable for debugging: it's always a stale pointer, but
- a stale pointer that might just be fresh enough to guide us to where the
- reclamation system is stuck */
- grpc_closure* debug_only_last_initiated_reclaimer;
- grpc_resource_user* debug_only_last_reclaimer_resource_user;
-
- /* Roots of all resource user lists */
- grpc_resource_user* roots[GRPC_RULIST_COUNT];
-
+ /* Has rq_step been scheduled to occur? */
+ bool step_scheduled;
+
+ /* Are we currently reclaiming memory */
+ bool reclaiming;
+
+ /* Closure around rq_step */
+ grpc_closure rq_step_closure;
+
+ /* Closure around rq_reclamation_done */
+ grpc_closure rq_reclamation_done_closure;
+
+ /* This is only really usable for debugging: it's always a stale pointer, but
+ a stale pointer that might just be fresh enough to guide us to where the
+ reclamation system is stuck */
+ grpc_closure* debug_only_last_initiated_reclaimer;
+ grpc_resource_user* debug_only_last_reclaimer_resource_user;
+
+ /* Roots of all resource user lists */
+ grpc_resource_user* roots[GRPC_RULIST_COUNT];
+
TString name;
-};
-
-static void ru_unref_by(grpc_resource_user* resource_user, gpr_atm amount);
-
-/*******************************************************************************
- * list management
- */
-
-static void rulist_add_head(grpc_resource_user* resource_user,
- grpc_rulist list) {
- grpc_resource_quota* resource_quota = resource_user->resource_quota;
- grpc_resource_user** root = &resource_quota->roots[list];
- if (*root == nullptr) {
- *root = resource_user;
- resource_user->links[list].next = resource_user->links[list].prev =
- resource_user;
- } else {
- resource_user->links[list].next = *root;
- resource_user->links[list].prev = (*root)->links[list].prev;
- resource_user->links[list].next->links[list].prev =
- resource_user->links[list].prev->links[list].next = resource_user;
- *root = resource_user;
- }
-}
-
-static void rulist_add_tail(grpc_resource_user* resource_user,
- grpc_rulist list) {
- grpc_resource_quota* resource_quota = resource_user->resource_quota;
- grpc_resource_user** root = &resource_quota->roots[list];
- if (*root == nullptr) {
- *root = resource_user;
- resource_user->links[list].next = resource_user->links[list].prev =
- resource_user;
- } else {
- resource_user->links[list].next = (*root)->links[list].next;
- resource_user->links[list].prev = *root;
- resource_user->links[list].next->links[list].prev =
- resource_user->links[list].prev->links[list].next = resource_user;
- }
-}
-
-static bool rulist_empty(grpc_resource_quota* resource_quota,
- grpc_rulist list) {
- return resource_quota->roots[list] == nullptr;
-}
-
-static grpc_resource_user* rulist_pop_head(grpc_resource_quota* resource_quota,
- grpc_rulist list) {
- grpc_resource_user** root = &resource_quota->roots[list];
- grpc_resource_user* resource_user = *root;
- if (resource_user == nullptr) {
- return nullptr;
- }
- if (resource_user->links[list].next == resource_user) {
- *root = nullptr;
- } else {
- resource_user->links[list].next->links[list].prev =
- resource_user->links[list].prev;
- resource_user->links[list].prev->links[list].next =
- resource_user->links[list].next;
- *root = resource_user->links[list].next;
- }
- resource_user->links[list].next = resource_user->links[list].prev = nullptr;
- return resource_user;
-}
-
-static void rulist_remove(grpc_resource_user* resource_user, grpc_rulist list) {
- if (resource_user->links[list].next == nullptr) return;
- grpc_resource_quota* resource_quota = resource_user->resource_quota;
- if (resource_quota->roots[list] == resource_user) {
- resource_quota->roots[list] = resource_user->links[list].next;
- if (resource_quota->roots[list] == resource_user) {
- resource_quota->roots[list] = nullptr;
- }
- }
- resource_user->links[list].next->links[list].prev =
- resource_user->links[list].prev;
- resource_user->links[list].prev->links[list].next =
- resource_user->links[list].next;
- resource_user->links[list].next = resource_user->links[list].prev = nullptr;
-}
-
-/*******************************************************************************
- * resource quota state machine
- */
-
-static bool rq_alloc(grpc_resource_quota* resource_quota);
-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 ru_unref_by(grpc_resource_user* resource_user, gpr_atm amount);
+
+/*******************************************************************************
+ * list management
+ */
+
+static void rulist_add_head(grpc_resource_user* resource_user,
+ grpc_rulist list) {
+ grpc_resource_quota* resource_quota = resource_user->resource_quota;
+ grpc_resource_user** root = &resource_quota->roots[list];
+ if (*root == nullptr) {
+ *root = resource_user;
+ resource_user->links[list].next = resource_user->links[list].prev =
+ resource_user;
+ } else {
+ resource_user->links[list].next = *root;
+ resource_user->links[list].prev = (*root)->links[list].prev;
+ resource_user->links[list].next->links[list].prev =
+ resource_user->links[list].prev->links[list].next = resource_user;
+ *root = resource_user;
+ }
+}
+
+static void rulist_add_tail(grpc_resource_user* resource_user,
+ grpc_rulist list) {
+ grpc_resource_quota* resource_quota = resource_user->resource_quota;
+ grpc_resource_user** root = &resource_quota->roots[list];
+ if (*root == nullptr) {
+ *root = resource_user;
+ resource_user->links[list].next = resource_user->links[list].prev =
+ resource_user;
+ } else {
+ resource_user->links[list].next = (*root)->links[list].next;
+ resource_user->links[list].prev = *root;
+ resource_user->links[list].next->links[list].prev =
+ resource_user->links[list].prev->links[list].next = resource_user;
+ }
+}
+
+static bool rulist_empty(grpc_resource_quota* resource_quota,
+ grpc_rulist list) {
+ return resource_quota->roots[list] == nullptr;
+}
+
+static grpc_resource_user* rulist_pop_head(grpc_resource_quota* resource_quota,
+ grpc_rulist list) {
+ grpc_resource_user** root = &resource_quota->roots[list];
+ grpc_resource_user* resource_user = *root;
+ if (resource_user == nullptr) {
+ return nullptr;
+ }
+ if (resource_user->links[list].next == resource_user) {
+ *root = nullptr;
+ } else {
+ resource_user->links[list].next->links[list].prev =
+ resource_user->links[list].prev;
+ resource_user->links[list].prev->links[list].next =
+ resource_user->links[list].next;
+ *root = resource_user->links[list].next;
+ }
+ resource_user->links[list].next = resource_user->links[list].prev = nullptr;
+ return resource_user;
+}
+
+static void rulist_remove(grpc_resource_user* resource_user, grpc_rulist list) {
+ if (resource_user->links[list].next == nullptr) return;
+ grpc_resource_quota* resource_quota = resource_user->resource_quota;
+ if (resource_quota->roots[list] == resource_user) {
+ resource_quota->roots[list] = resource_user->links[list].next;
+ if (resource_quota->roots[list] == resource_user) {
+ resource_quota->roots[list] = nullptr;
+ }
+ }
+ resource_user->links[list].next->links[list].prev =
+ resource_user->links[list].prev;
+ resource_user->links[list].prev->links[list].next =
+ resource_user->links[list].next;
+ resource_user->links[list].next = resource_user->links[list].prev = nullptr;
+}
+
+/*******************************************************************************
+ * resource quota state machine
+ */
+
+static bool rq_alloc(grpc_resource_quota* resource_quota);
+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*/) {
- grpc_resource_quota* resource_quota = static_cast<grpc_resource_quota*>(rq);
- resource_quota->step_scheduled = false;
- do {
- if (rq_alloc(resource_quota)) goto done;
- } while (rq_reclaim_from_per_user_free_pool(resource_quota));
-
- if (!rq_reclaim(resource_quota, false)) {
- rq_reclaim(resource_quota, true);
- }
-
-done:
- grpc_resource_quota_unref_internal(resource_quota);
-}
-
-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);
+ grpc_resource_quota* resource_quota = static_cast<grpc_resource_quota*>(rq);
+ resource_quota->step_scheduled = false;
+ do {
+ if (rq_alloc(resource_quota)) goto done;
+ } while (rq_reclaim_from_per_user_free_pool(resource_quota));
+
+ if (!rq_reclaim(resource_quota, false)) {
+ rq_reclaim(resource_quota, true);
+ }
+
+done:
+ grpc_resource_quota_unref_internal(resource_quota);
+}
+
+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);
-}
-
-/* update the atomically available resource estimate - use no barriers since
- timeliness of delivery really doesn't matter much */
-static void rq_update_estimate(grpc_resource_quota* resource_quota) {
- gpr_atm memory_usage_estimation = MEMORY_USAGE_ESTIMATION_MAX;
- if (resource_quota->size != 0) {
- memory_usage_estimation =
- GPR_CLAMP((gpr_atm)((1.0 - ((double)resource_quota->free_pool) /
- ((double)resource_quota->size)) *
- MEMORY_USAGE_ESTIMATION_MAX),
- 0, MEMORY_USAGE_ESTIMATION_MAX);
- }
- gpr_atm_no_barrier_store(&resource_quota->memory_usage_estimation,
- memory_usage_estimation);
-}
-
-/* returns true if all allocations are completed */
-static bool rq_alloc(grpc_resource_quota* resource_quota) {
- grpc_resource_user* resource_user;
- while ((resource_user = rulist_pop_head(resource_quota,
- GRPC_RULIST_AWAITING_ALLOCATION))) {
- gpr_mu_lock(&resource_user->mu);
+}
+
+/* update the atomically available resource estimate - use no barriers since
+ timeliness of delivery really doesn't matter much */
+static void rq_update_estimate(grpc_resource_quota* resource_quota) {
+ gpr_atm memory_usage_estimation = MEMORY_USAGE_ESTIMATION_MAX;
+ if (resource_quota->size != 0) {
+ memory_usage_estimation =
+ GPR_CLAMP((gpr_atm)((1.0 - ((double)resource_quota->free_pool) /
+ ((double)resource_quota->size)) *
+ MEMORY_USAGE_ESTIMATION_MAX),
+ 0, MEMORY_USAGE_ESTIMATION_MAX);
+ }
+ gpr_atm_no_barrier_store(&resource_quota->memory_usage_estimation,
+ memory_usage_estimation);
+}
+
+/* returns true if all allocations are completed */
+static bool rq_alloc(grpc_resource_quota* resource_quota) {
+ grpc_resource_user* resource_user;
+ 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)) {
- gpr_log(GPR_INFO,
- "RQ: check allocation for user %p shutdown=%" PRIdPTR
+ gpr_log(GPR_INFO,
+ "RQ: check allocation for user %p shutdown=%" PRIdPTR
" free_pool=%" PRId64 " outstanding_allocations=%" PRId64,
- resource_user, gpr_atm_no_barrier_load(&resource_user->shutdown),
+ resource_user, gpr_atm_no_barrier_load(&resource_user->shutdown),
resource_user->free_pool, resource_user->outstanding_allocations);
- }
- if (gpr_atm_no_barrier_load(&resource_user->shutdown)) {
- resource_user->allocating = false;
- grpc_closure_list_fail_all(
- &resource_user->on_allocated,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resource user shutdown"));
- int64_t aborted_allocations = resource_user->outstanding_allocations;
- resource_user->outstanding_allocations = 0;
- resource_user->free_pool += aborted_allocations;
+ }
+ if (gpr_atm_no_barrier_load(&resource_user->shutdown)) {
+ resource_user->allocating = false;
+ grpc_closure_list_fail_all(
+ &resource_user->on_allocated,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resource user shutdown"));
+ 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);
- gpr_mu_unlock(&resource_user->mu);
+ gpr_mu_unlock(&resource_user->mu);
if (aborted_allocations > 0) {
ru_unref_by(resource_user, static_cast<gpr_atm>(aborted_allocations));
}
- continue;
- }
- if (resource_user->free_pool < 0 &&
- -resource_user->free_pool <= resource_quota->free_pool) {
- int64_t amt = -resource_user->free_pool;
- resource_user->free_pool = 0;
- resource_quota->free_pool -= amt;
- rq_update_estimate(resource_quota);
+ continue;
+ }
+ if (resource_user->free_pool < 0 &&
+ -resource_user->free_pool <= resource_quota->free_pool) {
+ int64_t amt = -resource_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)) {
- gpr_log(GPR_INFO,
- "RQ %s %s: grant alloc %" PRId64
- " bytes; rq_free_pool -> %" PRId64,
+ 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);
- }
+ resource_quota->free_pool);
+ }
} 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_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());
- }
- if (resource_user->free_pool >= 0) {
- resource_user->allocating = false;
- resource_user->outstanding_allocations = 0;
+ }
+ 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);
- gpr_mu_unlock(&resource_user->mu);
- } else {
- rulist_add_head(resource_user, GRPC_RULIST_AWAITING_ALLOCATION);
- gpr_mu_unlock(&resource_user->mu);
- return false;
- }
- }
- return true;
-}
-
-/* returns true if any memory could be reclaimed from buffers */
-static bool rq_reclaim_from_per_user_free_pool(
- grpc_resource_quota* resource_quota) {
- grpc_resource_user* resource_user;
- while ((resource_user = rulist_pop_head(resource_quota,
- GRPC_RULIST_NON_EMPTY_FREE_POOL))) {
- gpr_mu_lock(&resource_user->mu);
+ gpr_mu_unlock(&resource_user->mu);
+ } else {
+ rulist_add_head(resource_user, GRPC_RULIST_AWAITING_ALLOCATION);
+ gpr_mu_unlock(&resource_user->mu);
+ return false;
+ }
+ }
+ return true;
+}
+
+/* returns true if any memory could be reclaimed from buffers */
+static bool rq_reclaim_from_per_user_free_pool(
+ grpc_resource_quota* resource_quota) {
+ grpc_resource_user* resource_user;
+ while ((resource_user = rulist_pop_head(resource_quota,
+ GRPC_RULIST_NON_EMPTY_FREE_POOL))) {
+ gpr_mu_lock(&resource_user->mu);
resource_user->added_to_free_pool = false;
- if (resource_user->free_pool > 0) {
- int64_t amt = resource_user->free_pool;
- resource_user->free_pool = 0;
- resource_quota->free_pool += amt;
- rq_update_estimate(resource_quota);
+ if (resource_user->free_pool > 0) {
+ int64_t amt = resource_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)) {
- gpr_log(GPR_INFO,
- "RQ %s %s: reclaim_from_per_user_free_pool %" PRId64
- " bytes; rq_free_pool -> %" PRId64,
+ gpr_log(GPR_INFO,
+ "RQ %s %s: reclaim_from_per_user_free_pool %" PRId64
+ " bytes; rq_free_pool -> %" PRId64,
resource_quota->name.c_str(), resource_user->name.c_str(), amt,
- resource_quota->free_pool);
- }
- gpr_mu_unlock(&resource_user->mu);
- return true;
- } else {
+ resource_quota->free_pool);
+ }
+ gpr_mu_unlock(&resource_user->mu);
+ return true;
+ } else {
if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO,
"RQ %s %s: failed to reclaim_from_per_user_free_pool; "
@@ -404,48 +404,48 @@ static bool rq_reclaim_from_per_user_free_pool(
resource_quota->name.c_str(), resource_user->name.c_str(),
resource_user->free_pool, resource_quota->free_pool);
}
- gpr_mu_unlock(&resource_user->mu);
- }
- }
- return false;
-}
-
-/* returns true if reclamation is proceeding */
-static bool rq_reclaim(grpc_resource_quota* resource_quota, bool destructive) {
- if (resource_quota->reclaiming) return true;
- grpc_rulist list = destructive ? GRPC_RULIST_RECLAIMER_DESTRUCTIVE
- : GRPC_RULIST_RECLAIMER_BENIGN;
- grpc_resource_user* resource_user = rulist_pop_head(resource_quota, list);
- if (resource_user == nullptr) return false;
+ gpr_mu_unlock(&resource_user->mu);
+ }
+ }
+ return false;
+}
+
+/* returns true if reclamation is proceeding */
+static bool rq_reclaim(grpc_resource_quota* resource_quota, bool destructive) {
+ if (resource_quota->reclaiming) return true;
+ grpc_rulist list = destructive ? GRPC_RULIST_RECLAIMER_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)) {
gpr_log(GPR_INFO, "RQ %s %s: initiate %s reclamation",
resource_quota->name.c_str(), resource_user->name.c_str(),
destructive ? "destructive" : "benign");
- }
- resource_quota->reclaiming = true;
- grpc_resource_quota_ref_internal(resource_quota);
- grpc_closure* c = resource_user->reclaimers[destructive];
- GPR_ASSERT(c);
- resource_quota->debug_only_last_reclaimer_resource_user = resource_user;
- resource_quota->debug_only_last_initiated_reclaimer = c;
- resource_user->reclaimers[destructive] = nullptr;
+ }
+ resource_quota->reclaiming = true;
+ grpc_resource_quota_ref_internal(resource_quota);
+ grpc_closure* c = resource_user->reclaimers[destructive];
+ GPR_ASSERT(c);
+ 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);
- return true;
-}
-
-/*******************************************************************************
- * ru_slice: a slice implementation that is backed by a grpc_resource_user
- */
-
+ return true;
+}
+
+/*******************************************************************************
+ * ru_slice: a slice implementation that is backed by a grpc_resource_user
+ */
+
namespace grpc_core {
-
+
class RuSliceRefcount {
public:
static void Destroy(void* p) {
auto* rc = static_cast<RuSliceRefcount*>(p);
rc->~RuSliceRefcount();
- gpr_free(rc);
- }
+ gpr_free(rc);
+ }
RuSliceRefcount(grpc_resource_user* resource_user, size_t size)
: base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
&base_),
@@ -454,9 +454,9 @@ class RuSliceRefcount {
// 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_;
@@ -466,132 +466,132 @@ class RuSliceRefcount {
} // namespace grpc_core
-static grpc_slice ru_slice_create(grpc_resource_user* resource_user,
- size_t size) {
+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);
- grpc_slice slice;
+ grpc_slice slice;
slice.refcount = rc->base_refcount();
- slice.data.refcounted.bytes = reinterpret_cast<uint8_t*>(rc + 1);
- slice.data.refcounted.length = size;
- return slice;
-}
-
-/*******************************************************************************
- * grpc_resource_quota internal implementation: resource user manipulation under
- * the combiner
- */
-
+ slice.data.refcounted.bytes = reinterpret_cast<uint8_t*>(rc + 1);
+ slice.data.refcounted.length = size;
+ return slice;
+}
+
+/*******************************************************************************
+ * grpc_resource_quota internal implementation: resource user manipulation under
+ * the combiner
+ */
+
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)) {
- rq_step_sched(resource_user->resource_quota);
- }
- rulist_add_tail(resource_user, GRPC_RULIST_AWAITING_ALLOCATION);
-}
-
+ grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
+ if (rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_AWAITING_ALLOCATION)) {
+ rq_step_sched(resource_user->resource_quota);
+ }
+ rulist_add_tail(resource_user, GRPC_RULIST_AWAITING_ALLOCATION);
+}
+
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) &&
- rulist_empty(resource_user->resource_quota,
- GRPC_RULIST_NON_EMPTY_FREE_POOL)) {
- rq_step_sched(resource_user->resource_quota);
- }
- rulist_add_tail(resource_user, GRPC_RULIST_NON_EMPTY_FREE_POOL);
-}
-
-static bool ru_post_reclaimer(grpc_resource_user* resource_user,
- bool destructive) {
- grpc_closure* closure = resource_user->new_reclaimers[destructive];
- GPR_ASSERT(closure != nullptr);
- resource_user->new_reclaimers[destructive] = nullptr;
- GPR_ASSERT(resource_user->reclaimers[destructive] == nullptr);
- if (gpr_atm_acq_load(&resource_user->shutdown) > 0) {
+ grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru);
+ if (!rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_AWAITING_ALLOCATION) &&
+ rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_NON_EMPTY_FREE_POOL)) {
+ rq_step_sched(resource_user->resource_quota);
+ }
+ rulist_add_tail(resource_user, GRPC_RULIST_NON_EMPTY_FREE_POOL);
+}
+
+static bool ru_post_reclaimer(grpc_resource_user* resource_user,
+ bool destructive) {
+ grpc_closure* closure = resource_user->new_reclaimers[destructive];
+ GPR_ASSERT(closure != nullptr);
+ 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);
- return false;
- }
- resource_user->reclaimers[destructive] = closure;
- return true;
-}
-
+ return false;
+ }
+ resource_user->reclaimers[destructive] = closure;
+ return true;
+}
+
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,
- GRPC_RULIST_AWAITING_ALLOCATION) &&
- rulist_empty(resource_user->resource_quota,
- GRPC_RULIST_NON_EMPTY_FREE_POOL) &&
- rulist_empty(resource_user->resource_quota,
- GRPC_RULIST_RECLAIMER_BENIGN)) {
- rq_step_sched(resource_user->resource_quota);
- }
- rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_BENIGN);
-}
-
+ 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,
+ GRPC_RULIST_AWAITING_ALLOCATION) &&
+ rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_NON_EMPTY_FREE_POOL) &&
+ rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_RECLAIMER_BENIGN)) {
+ rq_step_sched(resource_user->resource_quota);
+ }
+ rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_BENIGN);
+}
+
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,
- GRPC_RULIST_AWAITING_ALLOCATION) &&
- rulist_empty(resource_user->resource_quota,
- GRPC_RULIST_NON_EMPTY_FREE_POOL) &&
- rulist_empty(resource_user->resource_quota,
- GRPC_RULIST_RECLAIMER_BENIGN) &&
- rulist_empty(resource_user->resource_quota,
- GRPC_RULIST_RECLAIMER_DESTRUCTIVE)) {
- rq_step_sched(resource_user->resource_quota);
- }
- rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_DESTRUCTIVE);
-}
-
+ 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,
+ GRPC_RULIST_AWAITING_ALLOCATION) &&
+ rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_NON_EMPTY_FREE_POOL) &&
+ rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_RECLAIMER_BENIGN) &&
+ rulist_empty(resource_user->resource_quota,
+ GRPC_RULIST_RECLAIMER_DESTRUCTIVE)) {
+ rq_step_sched(resource_user->resource_quota);
+ }
+ 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)) {
- 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);
+ 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);
- resource_user->reclaimers[0] = nullptr;
- resource_user->reclaimers[1] = nullptr;
- rulist_remove(resource_user, GRPC_RULIST_RECLAIMER_BENIGN);
- rulist_remove(resource_user, GRPC_RULIST_RECLAIMER_DESTRUCTIVE);
- if (resource_user->allocating) {
- rq_step_sched(resource_user->resource_quota);
- }
- gpr_mu_unlock(&resource_user->mu);
-}
-
+ resource_user->reclaimers[0] = nullptr;
+ resource_user->reclaimers[1] = nullptr;
+ rulist_remove(resource_user, GRPC_RULIST_RECLAIMER_BENIGN);
+ rulist_remove(resource_user, GRPC_RULIST_RECLAIMER_DESTRUCTIVE);
+ if (resource_user->allocating) {
+ rq_step_sched(resource_user->resource_quota);
+ }
+ gpr_mu_unlock(&resource_user->mu);
+}
+
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);
+ 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
grpc_resource_user_free_threads(resource_user,
static_cast<int>(gpr_atm_no_barrier_load(
&resource_user->num_threads_allocated)));
- for (int i = 0; i < GRPC_RULIST_COUNT; i++) {
- rulist_remove(resource_user, static_cast<grpc_rulist>(i));
- }
+ 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);
- if (resource_user->free_pool != 0) {
- resource_user->resource_quota->free_pool += resource_user->free_pool;
- rq_step_sched(resource_user->resource_quota);
- }
- grpc_resource_quota_unref_internal(resource_user->resource_quota);
- gpr_mu_destroy(&resource_user->mu);
+ if (resource_user->free_pool != 0) {
+ resource_user->resource_quota->free_pool += resource_user->free_pool;
+ rq_step_sched(resource_user->resource_quota);
+ }
+ grpc_resource_quota_unref_internal(resource_user->resource_quota);
+ gpr_mu_destroy(&resource_user->mu);
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++) {
@@ -601,112 +601,112 @@ static void ru_alloc_slices(
}
}
-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);
+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));
-}
-
-/*******************************************************************************
- * grpc_resource_quota internal implementation: quota manipulation under the
- * combiner
- */
-
+}
+
+/*******************************************************************************
+ * grpc_resource_quota internal implementation: quota manipulation under the
+ * combiner
+ */
+
struct rq_resize_args {
- int64_t size;
- grpc_resource_quota* resource_quota;
- grpc_closure closure;
+ int64_t size;
+ grpc_resource_quota* resource_quota;
+ grpc_closure closure;
};
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;
- a->resource_quota->free_pool += delta;
- rq_update_estimate(a->resource_quota);
- rq_step_sched(a->resource_quota);
- grpc_resource_quota_unref_internal(a->resource_quota);
- gpr_free(a);
-}
-
+ rq_resize_args* a = static_cast<rq_resize_args*>(args);
+ int64_t delta = a->size - a->resource_quota->size;
+ a->resource_quota->size += delta;
+ a->resource_quota->free_pool += delta;
+ rq_update_estimate(a->resource_quota);
+ rq_step_sched(a->resource_quota);
+ grpc_resource_quota_unref_internal(a->resource_quota);
+ gpr_free(a);
+}
+
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);
- grpc_resource_quota_unref_internal(resource_quota);
-}
-
-/*******************************************************************************
- * grpc_resource_quota api
- */
-
-/* Public API */
-grpc_resource_quota* grpc_resource_quota_create(const char* name) {
+ grpc_resource_quota* resource_quota = static_cast<grpc_resource_quota*>(rq);
+ resource_quota->reclaiming = false;
+ rq_step_sched(resource_quota);
+ grpc_resource_quota_unref_internal(resource_quota);
+}
+
+/*******************************************************************************
+ * grpc_resource_quota api
+ */
+
+/* Public API */
+grpc_resource_quota* grpc_resource_quota_create(const char* name) {
grpc_resource_quota* resource_quota = new grpc_resource_quota;
- gpr_ref_init(&resource_quota->refs, 1);
- resource_quota->combiner = grpc_combiner_create();
- resource_quota->free_pool = INT64_MAX;
- resource_quota->size = INT64_MAX;
+ gpr_ref_init(&resource_quota->refs, 1);
+ resource_quota->combiner = grpc_combiner_create();
+ resource_quota->free_pool = INT64_MAX;
+ resource_quota->size = INT64_MAX;
resource_quota->used = 0;
- gpr_atm_no_barrier_store(&resource_quota->last_size, GPR_ATM_MAX);
+ gpr_atm_no_barrier_store(&resource_quota->last_size, GPR_ATM_MAX);
gpr_mu_init(&resource_quota->thread_count_mu);
resource_quota->max_threads = INT_MAX;
resource_quota->num_threads_allocated = 0;
- resource_quota->step_scheduled = false;
- resource_quota->reclaiming = false;
- gpr_atm_no_barrier_store(&resource_quota->memory_usage_estimation, 0);
- if (name != nullptr) {
+ resource_quota->step_scheduled = false;
+ resource_quota->reclaiming = false;
+ gpr_atm_no_barrier_store(&resource_quota->memory_usage_estimation, 0);
+ if (name != nullptr) {
resource_quota->name = name;
- } else {
+ } else {
resource_quota->name =
y_absl::StrCat("anonymous_pool_", (intptr_t)resource_quota);
- }
- GRPC_CLOSURE_INIT(&resource_quota->rq_step_closure, rq_step, resource_quota,
+ }
+ GRPC_CLOSURE_INIT(&resource_quota->rq_step_closure, rq_step, resource_quota,
nullptr);
- GRPC_CLOSURE_INIT(&resource_quota->rq_reclamation_done_closure,
+ GRPC_CLOSURE_INIT(&resource_quota->rq_reclamation_done_closure,
rq_reclamation_done, resource_quota, nullptr);
- for (int i = 0; i < GRPC_RULIST_COUNT; i++) {
- resource_quota->roots[i] = nullptr;
- }
- return resource_quota;
-}
-
-void grpc_resource_quota_unref_internal(grpc_resource_quota* resource_quota) {
- if (gpr_unref(&resource_quota->refs)) {
+ for (int i = 0; i < GRPC_RULIST_COUNT; i++) {
+ resource_quota->roots[i] = nullptr;
+ }
+ return resource_quota;
+}
+
+void grpc_resource_quota_unref_internal(grpc_resource_quota* resource_quota) {
+ if (gpr_unref(&resource_quota->refs)) {
// No outstanding thread quota
GPR_ASSERT(resource_quota->num_threads_allocated == 0);
- GRPC_COMBINER_UNREF(resource_quota->combiner, "resource_quota");
+ GRPC_COMBINER_UNREF(resource_quota->combiner, "resource_quota");
gpr_mu_destroy(&resource_quota->thread_count_mu);
delete resource_quota;
- }
-}
-
-/* Public API */
-void grpc_resource_quota_unref(grpc_resource_quota* resource_quota) {
- grpc_core::ExecCtx exec_ctx;
- grpc_resource_quota_unref_internal(resource_quota);
-}
-
-grpc_resource_quota* grpc_resource_quota_ref_internal(
- grpc_resource_quota* resource_quota) {
- gpr_ref(&resource_quota->refs);
- return resource_quota;
-}
-
-/* Public API */
-void grpc_resource_quota_ref(grpc_resource_quota* resource_quota) {
- grpc_resource_quota_ref_internal(resource_quota);
-}
-
-double grpc_resource_quota_get_memory_pressure(
- grpc_resource_quota* resource_quota) {
- return (static_cast<double>(gpr_atm_no_barrier_load(
- &resource_quota->memory_usage_estimation))) /
- (static_cast<double>(MEMORY_USAGE_ESTIMATION_MAX));
-}
-
-/* Public API */
+ }
+}
+
+/* Public API */
+void grpc_resource_quota_unref(grpc_resource_quota* resource_quota) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_resource_quota_unref_internal(resource_quota);
+}
+
+grpc_resource_quota* grpc_resource_quota_ref_internal(
+ grpc_resource_quota* resource_quota) {
+ gpr_ref(&resource_quota->refs);
+ return resource_quota;
+}
+
+/* Public API */
+void grpc_resource_quota_ref(grpc_resource_quota* resource_quota) {
+ grpc_resource_quota_ref_internal(resource_quota);
+}
+
+double grpc_resource_quota_get_memory_pressure(
+ grpc_resource_quota* resource_quota) {
+ return (static_cast<double>(gpr_atm_no_barrier_load(
+ &resource_quota->memory_usage_estimation))) /
+ (static_cast<double>(MEMORY_USAGE_ESTIMATION_MAX));
+}
+
+/* Public API */
void grpc_resource_quota_set_max_threads(grpc_resource_quota* resource_quota,
int new_max_threads) {
GPR_ASSERT(new_max_threads >= 0);
@@ -716,139 +716,139 @@ void grpc_resource_quota_set_max_threads(grpc_resource_quota* resource_quota,
}
/* Public API */
-void grpc_resource_quota_resize(grpc_resource_quota* resource_quota,
- size_t size) {
- grpc_core::ExecCtx exec_ctx;
- rq_resize_args* a = static_cast<rq_resize_args*>(gpr_malloc(sizeof(*a)));
- a->resource_quota = grpc_resource_quota_ref_internal(resource_quota);
- a->size = static_cast<int64_t>(size);
- 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);
+void grpc_resource_quota_resize(grpc_resource_quota* resource_quota,
+ size_t size) {
+ grpc_core::ExecCtx exec_ctx;
+ rq_resize_args* a = static_cast<rq_resize_args*>(gpr_malloc(sizeof(*a)));
+ a->resource_quota = grpc_resource_quota_ref_internal(resource_quota);
+ a->size = static_cast<int64_t>(size);
+ 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);
-}
-
-size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota) {
- return static_cast<size_t>(
- gpr_atm_no_barrier_load(&resource_quota->last_size));
-}
-
-/*******************************************************************************
- * grpc_resource_user channel args api
- */
-
-grpc_resource_quota* grpc_resource_quota_from_channel_args(
+}
+
+size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota) {
+ return static_cast<size_t>(
+ gpr_atm_no_barrier_load(&resource_quota->last_size));
+}
+
+/*******************************************************************************
+ * grpc_resource_user channel args api
+ */
+
+grpc_resource_quota* grpc_resource_quota_from_channel_args(
const grpc_channel_args* channel_args, bool create) {
- for (size_t i = 0; i < channel_args->num_args; i++) {
- if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
- if (channel_args->args[i].type == GRPC_ARG_POINTER) {
- return grpc_resource_quota_ref_internal(
- static_cast<grpc_resource_quota*>(
- channel_args->args[i].value.pointer.p));
- } else {
- gpr_log(GPR_DEBUG, GRPC_ARG_RESOURCE_QUOTA " should be a pointer");
- }
- }
- }
+ for (size_t i = 0; i < channel_args->num_args; i++) {
+ if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
+ if (channel_args->args[i].type == GRPC_ARG_POINTER) {
+ return grpc_resource_quota_ref_internal(
+ static_cast<grpc_resource_quota*>(
+ channel_args->args[i].value.pointer.p));
+ } else {
+ gpr_log(GPR_DEBUG, GRPC_ARG_RESOURCE_QUOTA " should be a pointer");
+ }
+ }
+ }
return create ? grpc_resource_quota_create(nullptr) : nullptr;
-}
-
-static void* rq_copy(void* rq) {
- grpc_resource_quota_ref(static_cast<grpc_resource_quota*>(rq));
- return rq;
-}
-
-static void rq_destroy(void* rq) {
- grpc_resource_quota_unref_internal(static_cast<grpc_resource_quota*>(rq));
-}
-
-static int rq_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
-
-const grpc_arg_pointer_vtable* grpc_resource_quota_arg_vtable(void) {
- static const grpc_arg_pointer_vtable vtable = {rq_copy, rq_destroy, rq_cmp};
- return &vtable;
-}
-
-/*******************************************************************************
- * grpc_resource_user api
- */
-
-grpc_resource_user* grpc_resource_user_create(
- grpc_resource_quota* resource_quota, const char* name) {
+}
+
+static void* rq_copy(void* rq) {
+ grpc_resource_quota_ref(static_cast<grpc_resource_quota*>(rq));
+ return rq;
+}
+
+static void rq_destroy(void* rq) {
+ grpc_resource_quota_unref_internal(static_cast<grpc_resource_quota*>(rq));
+}
+
+static int rq_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
+
+const grpc_arg_pointer_vtable* grpc_resource_quota_arg_vtable(void) {
+ static const grpc_arg_pointer_vtable vtable = {rq_copy, rq_destroy, rq_cmp};
+ return &vtable;
+}
+
+/*******************************************************************************
+ * grpc_resource_user api
+ */
+
+grpc_resource_user* grpc_resource_user_create(
+ grpc_resource_quota* resource_quota, const char* name) {
grpc_resource_user* resource_user = new grpc_resource_user;
- resource_user->resource_quota =
- grpc_resource_quota_ref_internal(resource_quota);
- GRPC_CLOSURE_INIT(&resource_user->allocate_closure, &ru_allocate,
+ resource_user->resource_quota =
+ grpc_resource_quota_ref_internal(resource_quota);
+ GRPC_CLOSURE_INIT(&resource_user->allocate_closure, &ru_allocate,
resource_user, nullptr);
- GRPC_CLOSURE_INIT(&resource_user->add_to_free_pool_closure,
+ GRPC_CLOSURE_INIT(&resource_user->add_to_free_pool_closure,
&ru_add_to_free_pool, resource_user, nullptr);
- GRPC_CLOSURE_INIT(&resource_user->post_reclaimer_closure[0],
+ GRPC_CLOSURE_INIT(&resource_user->post_reclaimer_closure[0],
&ru_post_benign_reclaimer, resource_user, nullptr);
- GRPC_CLOSURE_INIT(&resource_user->post_reclaimer_closure[1],
+ GRPC_CLOSURE_INIT(&resource_user->post_reclaimer_closure[1],
&ru_post_destructive_reclaimer, resource_user, nullptr);
- GRPC_CLOSURE_INIT(&resource_user->destroy_closure, &ru_destroy, resource_user,
+ GRPC_CLOSURE_INIT(&resource_user->destroy_closure, &ru_destroy, resource_user,
nullptr);
- gpr_mu_init(&resource_user->mu);
- gpr_atm_rel_store(&resource_user->refs, 1);
- gpr_atm_rel_store(&resource_user->shutdown, 0);
- resource_user->free_pool = 0;
- grpc_closure_list_init(&resource_user->on_allocated);
- resource_user->allocating = false;
- resource_user->added_to_free_pool = false;
+ gpr_mu_init(&resource_user->mu);
+ gpr_atm_rel_store(&resource_user->refs, 1);
+ gpr_atm_rel_store(&resource_user->shutdown, 0);
+ resource_user->free_pool = 0;
+ grpc_closure_list_init(&resource_user->on_allocated);
+ resource_user->allocating = false;
+ resource_user->added_to_free_pool = false;
gpr_atm_no_barrier_store(&resource_user->num_threads_allocated, 0);
- resource_user->reclaimers[0] = nullptr;
- resource_user->reclaimers[1] = nullptr;
- resource_user->new_reclaimers[0] = nullptr;
- resource_user->new_reclaimers[1] = nullptr;
- resource_user->outstanding_allocations = 0;
- for (int i = 0; i < GRPC_RULIST_COUNT; i++) {
- resource_user->links[i].next = resource_user->links[i].prev = nullptr;
- }
- if (name != nullptr) {
+ resource_user->reclaimers[0] = nullptr;
+ resource_user->reclaimers[1] = nullptr;
+ resource_user->new_reclaimers[0] = nullptr;
+ resource_user->new_reclaimers[1] = nullptr;
+ resource_user->outstanding_allocations = 0;
+ for (int i = 0; i < GRPC_RULIST_COUNT; i++) {
+ resource_user->links[i].next = resource_user->links[i].prev = nullptr;
+ }
+ if (name != nullptr) {
resource_user->name = name;
- } else {
+ } else {
resource_user->name =
y_absl::StrCat("anonymous_resource_user_", (intptr_t)resource_user);
- }
- return resource_user;
-}
-
-grpc_resource_quota* grpc_resource_user_quota(
- grpc_resource_user* resource_user) {
- return resource_user->resource_quota;
-}
-
-static void ru_ref_by(grpc_resource_user* resource_user, gpr_atm amount) {
- GPR_ASSERT(amount > 0);
- GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&resource_user->refs, amount) != 0);
-}
-
-static void ru_unref_by(grpc_resource_user* resource_user, gpr_atm amount) {
- GPR_ASSERT(amount > 0);
- gpr_atm old = gpr_atm_full_fetch_add(&resource_user->refs, -amount);
- GPR_ASSERT(old >= amount);
- if (old == amount) {
+ }
+ return resource_user;
+}
+
+grpc_resource_quota* grpc_resource_user_quota(
+ grpc_resource_user* resource_user) {
+ return resource_user->resource_quota;
+}
+
+static void ru_ref_by(grpc_resource_user* resource_user, gpr_atm amount) {
+ GPR_ASSERT(amount > 0);
+ GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&resource_user->refs, amount) != 0);
+}
+
+static void ru_unref_by(grpc_resource_user* resource_user, gpr_atm amount) {
+ GPR_ASSERT(amount > 0);
+ 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);
- }
-}
-
-void grpc_resource_user_ref(grpc_resource_user* resource_user) {
- ru_ref_by(resource_user, 1);
-}
-
-void grpc_resource_user_unref(grpc_resource_user* resource_user) {
- ru_unref_by(resource_user, 1);
-}
-
-void grpc_resource_user_shutdown(grpc_resource_user* resource_user) {
- if (gpr_atm_full_fetch_add(&resource_user->shutdown, 1) == 0) {
+ }
+}
+
+void grpc_resource_user_ref(grpc_resource_user* resource_user) {
+ ru_ref_by(resource_user, 1);
+}
+
+void grpc_resource_user_unref(grpc_resource_user* resource_user) {
+ ru_unref_by(resource_user, 1);
+}
+
+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),
- GRPC_ERROR_NONE);
- }
-}
-
+ GRPC_ERROR_NONE);
+ }
+}
+
bool grpc_resource_user_allocate_threads(grpc_resource_user* resource_user,
int thread_count) {
GPR_ASSERT(thread_count >= 0);
@@ -886,20 +886,20 @@ void grpc_resource_user_free_threads(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);
+ 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)) {
- gpr_log(GPR_INFO, "RQ %s %s: alloc %" PRIdPTR "; free_pool -> %" PRId64,
+ 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 (!resource_user->allocating) {
resource_user->allocating = true;
resource_user->resource_quota->combiner->Run(
@@ -925,10 +925,10 @@ bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user,
cas_success = gpr_atm_full_cas(&resource_quota->used, used, new_used);
} while (!cas_success);
resource_user_alloc_locked(resource_user, size, nullptr);
- gpr_mu_unlock(&resource_user->mu);
+ gpr_mu_unlock(&resource_user->mu);
return true;
-}
-
+}
+
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
@@ -942,62 +942,62 @@ bool grpc_resource_user_alloc(grpc_resource_user* resource_user, size_t size,
return ret;
}
-void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size) {
- gpr_mu_lock(&resource_user->mu);
+void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size) {
+ gpr_mu_lock(&resource_user->mu);
grpc_resource_quota* resource_quota = resource_user->resource_quota;
gpr_atm prior = gpr_atm_no_barrier_fetch_add(&resource_quota->used, -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);
+ 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)) {
- gpr_log(GPR_INFO, "RQ %s %s: free %" PRIdPTR "; free_pool -> %" PRId64,
+ 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);
- }
- bool is_bigger_than_zero = resource_user->free_pool > 0;
- if (is_bigger_than_zero && was_zero_or_negative &&
- !resource_user->added_to_free_pool) {
- resource_user->added_to_free_pool = true;
+ }
+ bool is_bigger_than_zero = resource_user->free_pool > 0;
+ 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);
- }
- gpr_mu_unlock(&resource_user->mu);
- ru_unref_by(resource_user, static_cast<gpr_atm>(size));
-}
-
-void grpc_resource_user_post_reclaimer(grpc_resource_user* resource_user,
- bool destructive,
- grpc_closure* closure) {
- GPR_ASSERT(resource_user->new_reclaimers[destructive] == nullptr);
- resource_user->new_reclaimers[destructive] = closure;
+ }
+ gpr_mu_unlock(&resource_user->mu);
+ ru_unref_by(resource_user, static_cast<gpr_atm>(size));
+}
+
+void grpc_resource_user_post_reclaimer(grpc_resource_user* resource_user,
+ bool destructive,
+ 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);
-}
-
-void grpc_resource_user_finish_reclamation(grpc_resource_user* resource_user) {
+}
+
+void grpc_resource_user_finish_reclamation(grpc_resource_user* resource_user) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
- gpr_log(GPR_INFO, "RQ %s %s: reclamation complete",
+ 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->rq_reclamation_done_closure,
- GRPC_ERROR_NONE);
-}
-
-void grpc_resource_user_slice_allocator_init(
- grpc_resource_user_slice_allocator* slice_allocator,
- grpc_resource_user* resource_user, grpc_iomgr_cb_func cb, void* p) {
- GRPC_CLOSURE_INIT(&slice_allocator->on_allocated, ru_allocated_slices,
- slice_allocator, grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&slice_allocator->on_done, cb, p,
- grpc_schedule_on_exec_ctx);
- slice_allocator->resource_user = resource_user;
-}
-
+ &resource_user->resource_quota->rq_reclamation_done_closure,
+ GRPC_ERROR_NONE);
+}
+
+void grpc_resource_user_slice_allocator_init(
+ grpc_resource_user_slice_allocator* slice_allocator,
+ grpc_resource_user* resource_user, grpc_iomgr_cb_func cb, void* p) {
+ GRPC_CLOSURE_INIT(&slice_allocator->on_allocated, ru_allocated_slices,
+ slice_allocator, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&slice_allocator->on_done, cb, p,
+ grpc_schedule_on_exec_ctx);
+ slice_allocator->resource_user = resource_user;
+}
+
bool grpc_resource_user_alloc_slices(
- grpc_resource_user_slice_allocator* slice_allocator, size_t length,
- size_t count, grpc_slice_buffer* dest) {
+ 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(
@@ -1005,12 +1005,12 @@ bool grpc_resource_user_alloc_slices(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resource user shutdown"));
return false;
}
- slice_allocator->length = length;
- slice_allocator->count = count;
- slice_allocator->dest = dest;
+ 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;
-}
+}
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 ec89a920201..13f15619f51 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h
@@ -1,30 +1,30 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_RESOURCE_QUOTA_H
#define GRPC_CORE_LIB_IOMGR_RESOURCE_QUOTA_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/grpc.h>
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/iomgr/closure.h"
/** \file Tracks resource usage against a pool.
@@ -63,40 +63,40 @@
maintain lists of users (which users arrange to leave before they are
destroyed) */
-extern grpc_core::TraceFlag grpc_resource_quota_trace;
+extern grpc_core::TraceFlag grpc_resource_quota_trace;
// TODO(juanlishen): This is a hack. We need to do real accounting instead of
// hard coding.
constexpr size_t GRPC_RESOURCE_QUOTA_CALL_SIZE = 15 * 1024;
constexpr size_t GRPC_RESOURCE_QUOTA_CHANNEL_SIZE = 50 * 1024;
-grpc_resource_quota* grpc_resource_quota_ref_internal(
- grpc_resource_quota* resource_quota);
-void grpc_resource_quota_unref_internal(grpc_resource_quota* resource_quota);
-grpc_resource_quota* grpc_resource_quota_from_channel_args(
+grpc_resource_quota* grpc_resource_quota_ref_internal(
+ grpc_resource_quota* resource_quota);
+void grpc_resource_quota_unref_internal(grpc_resource_quota* resource_quota);
+grpc_resource_quota* grpc_resource_quota_from_channel_args(
const grpc_channel_args* channel_args, bool create = true);
-/* Return a number indicating current memory pressure:
- 0.0 ==> no memory usage
- 1.0 ==> maximum memory usage */
-double grpc_resource_quota_get_memory_pressure(
- grpc_resource_quota* resource_quota);
-
-size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota);
-
+/* Return a number indicating current memory pressure:
+ 0.0 ==> no memory usage
+ 1.0 ==> maximum memory usage */
+double grpc_resource_quota_get_memory_pressure(
+ grpc_resource_quota* resource_quota);
+
+size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota);
+
typedef struct grpc_resource_user grpc_resource_user;
-grpc_resource_user* grpc_resource_user_create(
- grpc_resource_quota* resource_quota, const char* name);
+grpc_resource_user* grpc_resource_user_create(
+ grpc_resource_quota* resource_quota, const char* name);
/* Returns a borrowed reference to the underlying resource quota for this
resource user. */
-grpc_resource_quota* grpc_resource_user_quota(
- grpc_resource_user* resource_user);
+grpc_resource_quota* grpc_resource_user_quota(
+ grpc_resource_user* resource_user);
-void grpc_resource_user_ref(grpc_resource_user* resource_user);
-void grpc_resource_user_unref(grpc_resource_user* resource_user);
-void grpc_resource_user_shutdown(grpc_resource_user* resource_user);
+void grpc_resource_user_ref(grpc_resource_user* resource_user);
+void grpc_resource_user_unref(grpc_resource_user* resource_user);
+void grpc_resource_user_shutdown(grpc_resource_user* resource_user);
/* Attempts to get quota from the resource_user to create 'thread_count' number
* of threads. Returns true if successful (i.e the caller is now free to create
@@ -134,15 +134,15 @@ 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);
+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
destructive reclaimer can be posted at once. When executed, the reclaimer
MUST call grpc_resource_user_finish_reclamation before it completes, to
return control to the resource quota. */
-void grpc_resource_user_post_reclaimer(grpc_resource_user* resource_user,
- bool destructive, grpc_closure* closure);
+void grpc_resource_user_post_reclaimer(grpc_resource_user* resource_user,
+ bool destructive, grpc_closure* closure);
/* Finish a reclamation step */
-void grpc_resource_user_finish_reclamation(grpc_resource_user* resource_user);
+void grpc_resource_user_finish_reclamation(grpc_resource_user* resource_user);
/* Helper to allocate slices from a resource user */
typedef struct grpc_resource_user_slice_allocator {
@@ -155,23 +155,23 @@ typedef struct grpc_resource_user_slice_allocator {
/* Number of slices to allocate on the current request */
size_t count;
/* Destination for slices to allocate on the current request */
- grpc_slice_buffer* dest;
+ grpc_slice_buffer* dest;
/* Parent resource user */
- grpc_resource_user* resource_user;
+ grpc_resource_user* resource_user;
} grpc_resource_user_slice_allocator;
/* Initialize a slice allocator.
When an allocation is completed, calls \a cb with arg \p. */
void grpc_resource_user_slice_allocator_init(
- grpc_resource_user_slice_allocator* slice_allocator,
- grpc_resource_user* resource_user, grpc_iomgr_cb_func cb, void* p);
+ grpc_resource_user_slice_allocator* slice_allocator,
+ 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(
- grpc_resource_user_slice_allocator* slice_allocator, size_t length,
+ grpc_resource_user_slice_allocator* slice_allocator, size_t length,
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.h b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr.h
index 5edf735cd18..782615ff82c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -23,10 +23,10 @@
#ifndef GRPC_CORE_LIB_IOMGR_SOCKADDR_H
#define GRPC_CORE_LIB_IOMGR_SOCKADDR_H
-#include <grpc/support/port_platform.h>
+#include <grpc/support/port_platform.h>
-#include "src/core/lib/iomgr/sockaddr_custom.h"
-#include "src/core/lib/iomgr/sockaddr_posix.h"
+#include "src/core/lib/iomgr/sockaddr_custom.h"
+#include "src/core/lib/iomgr/sockaddr_posix.h"
#include "src/core/lib/iomgr/sockaddr_windows.h"
#endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_custom.h b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_custom.h
index a5d2a6c3a68..97e9addebb0 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_custom.h
@@ -1,54 +1,54 @@
-/*
- *
- * 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_SOCKADDR_CUSTOM_H
-#define GRPC_CORE_LIB_IOMGR_SOCKADDR_CUSTOM_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stddef.h>
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_UV
-
+/*
+ *
+ * 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_SOCKADDR_CUSTOM_H
+#define GRPC_CORE_LIB_IOMGR_SOCKADDR_CUSTOM_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stddef.h>
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_UV
+
#error #include <uv.h>
-
-// TODO(kpayson) It would be nice to abstract this so we don't
-// depend on anything uv specific
-typedef struct sockaddr grpc_sockaddr;
-typedef struct sockaddr_in grpc_sockaddr_in;
-typedef struct in_addr grpc_in_addr;
-typedef struct sockaddr_in6 grpc_sockaddr_in6;
-typedef struct in6_addr grpc_in6_addr;
-
-#define GRPC_INET_ADDRSTRLEN INET_ADDRSTRLEN
-#define GRPC_INET6_ADDRSTRLEN INET6_ADDRSTRLEN
-
-#define GRPC_SOCK_STREAM SOCK_STREAM
-#define GRPC_SOCK_DGRAM SOCK_DGRAM
-
-#define GRPC_AF_UNSPEC AF_UNSPEC
-#define GRPC_AF_UNIX AF_UNIX
-#define GRPC_AF_INET AF_INET
-#define GRPC_AF_INET6 AF_INET6
-
-#define GRPC_AI_PASSIVE AI_PASSIVE
-
-#endif // GRPC_UV
-
-#endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_CUSTOM_H */
+
+// TODO(kpayson) It would be nice to abstract this so we don't
+// depend on anything uv specific
+typedef struct sockaddr grpc_sockaddr;
+typedef struct sockaddr_in grpc_sockaddr_in;
+typedef struct in_addr grpc_in_addr;
+typedef struct sockaddr_in6 grpc_sockaddr_in6;
+typedef struct in6_addr grpc_in6_addr;
+
+#define GRPC_INET_ADDRSTRLEN INET_ADDRSTRLEN
+#define GRPC_INET6_ADDRSTRLEN INET6_ADDRSTRLEN
+
+#define GRPC_SOCK_STREAM SOCK_STREAM
+#define GRPC_SOCK_DGRAM SOCK_DGRAM
+
+#define GRPC_AF_UNSPEC AF_UNSPEC
+#define GRPC_AF_UNIX AF_UNIX
+#define GRPC_AF_INET AF_INET
+#define GRPC_AF_INET6 AF_INET6
+
+#define GRPC_AI_PASSIVE AI_PASSIVE
+
+#endif // GRPC_UV
+
+#endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_CUSTOM_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h
index 3cedd9082d7..bd2d2b5425f 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h
@@ -1,28 +1,28 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SOCKADDR_POSIX_H
#define GRPC_CORE_LIB_IOMGR_SOCKADDR_POSIX_H
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_SOCKADDR
#include <arpa/inet.h>
#include <netdb.h>
@@ -31,25 +31,25 @@
#include <sys/types.h>
#include <unistd.h>
-typedef struct sockaddr grpc_sockaddr;
-typedef struct sockaddr_in grpc_sockaddr_in;
-typedef struct in_addr grpc_in_addr;
-typedef struct sockaddr_in6 grpc_sockaddr_in6;
-typedef struct in6_addr grpc_in6_addr;
-
-#define GRPC_INET_ADDRSTRLEN INET_ADDRSTRLEN
-#define GRPC_INET6_ADDRSTRLEN INET6_ADDRSTRLEN
-
-#define GRPC_SOCK_STREAM SOCK_STREAM
-#define GRPC_SOCK_DGRAM SOCK_DGRAM
-
-#define GRPC_AF_UNSPEC AF_UNSPEC
-#define GRPC_AF_UNIX AF_UNIX
-#define GRPC_AF_INET AF_INET
-#define GRPC_AF_INET6 AF_INET6
-
-#define GRPC_AI_PASSIVE AI_PASSIVE
-
-#endif
-
+typedef struct sockaddr grpc_sockaddr;
+typedef struct sockaddr_in grpc_sockaddr_in;
+typedef struct in_addr grpc_in_addr;
+typedef struct sockaddr_in6 grpc_sockaddr_in6;
+typedef struct in6_addr grpc_in6_addr;
+
+#define GRPC_INET_ADDRSTRLEN INET_ADDRSTRLEN
+#define GRPC_INET6_ADDRSTRLEN INET6_ADDRSTRLEN
+
+#define GRPC_SOCK_STREAM SOCK_STREAM
+#define GRPC_SOCK_DGRAM SOCK_DGRAM
+
+#define GRPC_AF_UNSPEC AF_UNSPEC
+#define GRPC_AF_UNIX AF_UNIX
+#define GRPC_AF_INET AF_INET
+#define GRPC_AF_INET6 AF_INET6
+
+#define GRPC_AI_PASSIVE AI_PASSIVE
+
+#endif
+
#endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_POSIX_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 b43dbc99235..b96bc478789 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.cc
@@ -1,296 +1,296 @@
-/*
- *
- * 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/sockaddr_utils.h"
-
-#include <errno.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+
+#include <errno.h>
+#include <inttypes.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/string.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/string.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"
-
-static const uint8_t kV4MappedPrefix[] = {0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0xff, 0xff};
-
-int grpc_sockaddr_is_v4mapped(const grpc_resolved_address* resolved_addr,
- grpc_resolved_address* resolved_addr4_out) {
- GPR_ASSERT(resolved_addr != resolved_addr4_out);
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- grpc_sockaddr_in* addr4_out =
- resolved_addr4_out == nullptr
- ? nullptr
- : reinterpret_cast<grpc_sockaddr_in*>(resolved_addr4_out->addr);
- if (addr->sa_family == GRPC_AF_INET6) {
- const grpc_sockaddr_in6* addr6 =
- reinterpret_cast<const grpc_sockaddr_in6*>(addr);
- if (memcmp(addr6->sin6_addr.s6_addr, kV4MappedPrefix,
- sizeof(kV4MappedPrefix)) == 0) {
- if (resolved_addr4_out != nullptr) {
- /* Normalize ::ffff:0.0.0.0/96 to IPv4. */
- memset(resolved_addr4_out, 0, sizeof(*resolved_addr4_out));
- addr4_out->sin_family = GRPC_AF_INET;
- /* s6_addr32 would be nice, but it's non-standard. */
- memcpy(&addr4_out->sin_addr, &addr6->sin6_addr.s6_addr[12], 4);
- addr4_out->sin_port = addr6->sin6_port;
- resolved_addr4_out->len =
- static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
- }
- return 1;
- }
- }
- return 0;
-}
-
-int grpc_sockaddr_to_v4mapped(const grpc_resolved_address* resolved_addr,
- grpc_resolved_address* resolved_addr6_out) {
- GPR_ASSERT(resolved_addr != resolved_addr6_out);
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- grpc_sockaddr_in6* addr6_out =
- reinterpret_cast<grpc_sockaddr_in6*>(resolved_addr6_out->addr);
- if (addr->sa_family == GRPC_AF_INET) {
- const grpc_sockaddr_in* addr4 =
- reinterpret_cast<const grpc_sockaddr_in*>(addr);
- memset(resolved_addr6_out, 0, sizeof(*resolved_addr6_out));
- addr6_out->sin6_family = GRPC_AF_INET6;
- memcpy(&addr6_out->sin6_addr.s6_addr[0], kV4MappedPrefix, 12);
- memcpy(&addr6_out->sin6_addr.s6_addr[12], &addr4->sin_addr, 4);
- addr6_out->sin6_port = addr4->sin_port;
- resolved_addr6_out->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
- return 1;
- }
- return 0;
-}
-
-int grpc_sockaddr_is_wildcard(const grpc_resolved_address* resolved_addr,
- int* port_out) {
- const grpc_sockaddr* addr;
- grpc_resolved_address addr4_normalized;
- if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr4_normalized)) {
- resolved_addr = &addr4_normalized;
- }
- addr = reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- if (addr->sa_family == GRPC_AF_INET) {
- /* Check for 0.0.0.0 */
- const grpc_sockaddr_in* addr4 =
- reinterpret_cast<const grpc_sockaddr_in*>(addr);
- if (addr4->sin_addr.s_addr != 0) {
- return 0;
- }
- *port_out = grpc_ntohs(addr4->sin_port);
- return 1;
- } else if (addr->sa_family == GRPC_AF_INET6) {
- /* Check for :: */
- const grpc_sockaddr_in6* addr6 =
- reinterpret_cast<const grpc_sockaddr_in6*>(addr);
- int i;
- for (i = 0; i < 16; i++) {
- if (addr6->sin6_addr.s6_addr[i] != 0) {
- return 0;
- }
- }
- *port_out = grpc_ntohs(addr6->sin6_port);
- return 1;
- } else {
- return 0;
- }
-}
-
-void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address* wild4_out,
- grpc_resolved_address* wild6_out) {
- grpc_sockaddr_make_wildcard4(port, wild4_out);
- grpc_sockaddr_make_wildcard6(port, wild6_out);
-}
-
-void grpc_sockaddr_make_wildcard4(int port,
- grpc_resolved_address* resolved_wild_out) {
- grpc_sockaddr_in* wild_out =
- reinterpret_cast<grpc_sockaddr_in*>(resolved_wild_out->addr);
- GPR_ASSERT(port >= 0 && port < 65536);
- memset(resolved_wild_out, 0, sizeof(*resolved_wild_out));
- wild_out->sin_family = GRPC_AF_INET;
- wild_out->sin_port = grpc_htons(static_cast<uint16_t>(port));
- resolved_wild_out->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
-}
-
-void grpc_sockaddr_make_wildcard6(int port,
- grpc_resolved_address* resolved_wild_out) {
- grpc_sockaddr_in6* wild_out =
- reinterpret_cast<grpc_sockaddr_in6*>(resolved_wild_out->addr);
- GPR_ASSERT(port >= 0 && port < 65536);
- memset(resolved_wild_out, 0, sizeof(*resolved_wild_out));
- wild_out->sin6_family = GRPC_AF_INET6;
- wild_out->sin6_port = grpc_htons(static_cast<uint16_t>(port));
- resolved_wild_out->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
-}
-
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/socket_utils.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
+
+static const uint8_t kV4MappedPrefix[] = {0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0xff, 0xff};
+
+int grpc_sockaddr_is_v4mapped(const grpc_resolved_address* resolved_addr,
+ grpc_resolved_address* resolved_addr4_out) {
+ GPR_ASSERT(resolved_addr != resolved_addr4_out);
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ grpc_sockaddr_in* addr4_out =
+ resolved_addr4_out == nullptr
+ ? nullptr
+ : reinterpret_cast<grpc_sockaddr_in*>(resolved_addr4_out->addr);
+ if (addr->sa_family == GRPC_AF_INET6) {
+ const grpc_sockaddr_in6* addr6 =
+ reinterpret_cast<const grpc_sockaddr_in6*>(addr);
+ if (memcmp(addr6->sin6_addr.s6_addr, kV4MappedPrefix,
+ sizeof(kV4MappedPrefix)) == 0) {
+ if (resolved_addr4_out != nullptr) {
+ /* Normalize ::ffff:0.0.0.0/96 to IPv4. */
+ memset(resolved_addr4_out, 0, sizeof(*resolved_addr4_out));
+ addr4_out->sin_family = GRPC_AF_INET;
+ /* s6_addr32 would be nice, but it's non-standard. */
+ memcpy(&addr4_out->sin_addr, &addr6->sin6_addr.s6_addr[12], 4);
+ addr4_out->sin_port = addr6->sin6_port;
+ resolved_addr4_out->len =
+ static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
+ }
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int grpc_sockaddr_to_v4mapped(const grpc_resolved_address* resolved_addr,
+ grpc_resolved_address* resolved_addr6_out) {
+ GPR_ASSERT(resolved_addr != resolved_addr6_out);
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ grpc_sockaddr_in6* addr6_out =
+ reinterpret_cast<grpc_sockaddr_in6*>(resolved_addr6_out->addr);
+ if (addr->sa_family == GRPC_AF_INET) {
+ const grpc_sockaddr_in* addr4 =
+ reinterpret_cast<const grpc_sockaddr_in*>(addr);
+ memset(resolved_addr6_out, 0, sizeof(*resolved_addr6_out));
+ addr6_out->sin6_family = GRPC_AF_INET6;
+ memcpy(&addr6_out->sin6_addr.s6_addr[0], kV4MappedPrefix, 12);
+ memcpy(&addr6_out->sin6_addr.s6_addr[12], &addr4->sin_addr, 4);
+ addr6_out->sin6_port = addr4->sin_port;
+ resolved_addr6_out->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
+ return 1;
+ }
+ return 0;
+}
+
+int grpc_sockaddr_is_wildcard(const grpc_resolved_address* resolved_addr,
+ int* port_out) {
+ const grpc_sockaddr* addr;
+ grpc_resolved_address addr4_normalized;
+ if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr4_normalized)) {
+ resolved_addr = &addr4_normalized;
+ }
+ addr = reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ if (addr->sa_family == GRPC_AF_INET) {
+ /* Check for 0.0.0.0 */
+ const grpc_sockaddr_in* addr4 =
+ reinterpret_cast<const grpc_sockaddr_in*>(addr);
+ if (addr4->sin_addr.s_addr != 0) {
+ return 0;
+ }
+ *port_out = grpc_ntohs(addr4->sin_port);
+ return 1;
+ } else if (addr->sa_family == GRPC_AF_INET6) {
+ /* Check for :: */
+ const grpc_sockaddr_in6* addr6 =
+ reinterpret_cast<const grpc_sockaddr_in6*>(addr);
+ int i;
+ for (i = 0; i < 16; i++) {
+ if (addr6->sin6_addr.s6_addr[i] != 0) {
+ return 0;
+ }
+ }
+ *port_out = grpc_ntohs(addr6->sin6_port);
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address* wild4_out,
+ grpc_resolved_address* wild6_out) {
+ grpc_sockaddr_make_wildcard4(port, wild4_out);
+ grpc_sockaddr_make_wildcard6(port, wild6_out);
+}
+
+void grpc_sockaddr_make_wildcard4(int port,
+ grpc_resolved_address* resolved_wild_out) {
+ grpc_sockaddr_in* wild_out =
+ reinterpret_cast<grpc_sockaddr_in*>(resolved_wild_out->addr);
+ GPR_ASSERT(port >= 0 && port < 65536);
+ memset(resolved_wild_out, 0, sizeof(*resolved_wild_out));
+ wild_out->sin_family = GRPC_AF_INET;
+ wild_out->sin_port = grpc_htons(static_cast<uint16_t>(port));
+ resolved_wild_out->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
+}
+
+void grpc_sockaddr_make_wildcard6(int port,
+ grpc_resolved_address* resolved_wild_out) {
+ grpc_sockaddr_in6* wild_out =
+ reinterpret_cast<grpc_sockaddr_in6*>(resolved_wild_out->addr);
+ GPR_ASSERT(port >= 0 && port < 65536);
+ memset(resolved_wild_out, 0, sizeof(*resolved_wild_out));
+ wild_out->sin6_family = GRPC_AF_INET6;
+ wild_out->sin6_port = grpc_htons(static_cast<uint16_t>(port));
+ resolved_wild_out->len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
+}
+
TString grpc_sockaddr_to_string(const grpc_resolved_address* resolved_addr,
bool normalize) {
- const int save_errno = errno;
- grpc_resolved_address addr_normalized;
+ const int save_errno = errno;
+ grpc_resolved_address addr_normalized;
if (normalize && grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) {
resolved_addr = &addr_normalized;
}
const grpc_sockaddr* addr =
reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- const void* ip = nullptr;
- int port = 0;
- uint32_t sin6_scope_id = 0;
- if (addr->sa_family == GRPC_AF_INET) {
- const grpc_sockaddr_in* addr4 =
- reinterpret_cast<const grpc_sockaddr_in*>(addr);
- ip = &addr4->sin_addr;
- port = grpc_ntohs(addr4->sin_port);
- } else if (addr->sa_family == GRPC_AF_INET6) {
- const grpc_sockaddr_in6* addr6 =
- reinterpret_cast<const grpc_sockaddr_in6*>(addr);
- ip = &addr6->sin6_addr;
- port = grpc_ntohs(addr6->sin6_port);
- sin6_scope_id = addr6->sin6_scope_id;
- }
+ const void* ip = nullptr;
+ int port = 0;
+ uint32_t sin6_scope_id = 0;
+ if (addr->sa_family == GRPC_AF_INET) {
+ const grpc_sockaddr_in* addr4 =
+ reinterpret_cast<const grpc_sockaddr_in*>(addr);
+ ip = &addr4->sin_addr;
+ port = grpc_ntohs(addr4->sin_port);
+ } else if (addr->sa_family == GRPC_AF_INET6) {
+ const grpc_sockaddr_in6* addr6 =
+ reinterpret_cast<const grpc_sockaddr_in6*>(addr);
+ ip = &addr6->sin6_addr;
+ port = grpc_ntohs(addr6->sin6_port);
+ sin6_scope_id = addr6->sin6_scope_id;
+ }
char ntop_buf[GRPC_INET6_ADDRSTRLEN];
TString out;
- if (ip != nullptr && grpc_inet_ntop(addr->sa_family, ip, ntop_buf,
- sizeof(ntop_buf)) != nullptr) {
- if (sin6_scope_id != 0) {
+ if (ip != nullptr && grpc_inet_ntop(addr->sa_family, ip, ntop_buf,
+ sizeof(ntop_buf)) != nullptr) {
+ if (sin6_scope_id != 0) {
// Enclose sin6_scope_id with the format defined in RFC 6784 section 2.
TString host_with_scope =
y_absl::StrFormat("%s%%25%" PRIu32, ntop_buf, sin6_scope_id);
out = grpc_core::JoinHostPort(host_with_scope, port);
- } else {
+ } else {
out = grpc_core::JoinHostPort(ntop_buf, port);
- }
- } else {
+ }
+ } else {
out = y_absl::StrFormat("(sockaddr family=%d)", addr->sa_family);
- }
- /* This is probably redundant, but we wouldn't want to log the wrong error. */
- errno = save_errno;
+ }
+ /* This is probably redundant, but we wouldn't want to log the wrong error. */
+ errno = save_errno;
return out;
-}
-
+}
+
void grpc_string_to_sockaddr(grpc_resolved_address* out, const char* addr,
int port) {
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) {
- addr6->sin6_family = GRPC_AF_INET6;
- out->len = sizeof(grpc_sockaddr_in6);
- } else if (grpc_inet_pton(GRPC_AF_INET, addr, &addr4->sin_addr) == 1) {
- addr4->sin_family = GRPC_AF_INET;
- out->len = sizeof(grpc_sockaddr_in);
- } else {
- GPR_ASSERT(0);
- }
- grpc_sockaddr_set_port(out, port);
-}
-
+ 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) {
+ addr6->sin6_family = GRPC_AF_INET6;
+ out->len = sizeof(grpc_sockaddr_in6);
+ } else if (grpc_inet_pton(GRPC_AF_INET, addr, &addr4->sin_addr) == 1) {
+ addr4->sin_family = GRPC_AF_INET;
+ out->len = sizeof(grpc_sockaddr_in);
+ } else {
+ GPR_ASSERT(0);
+ }
+ grpc_sockaddr_set_port(out, port);
+}
+
TString grpc_sockaddr_to_uri(const grpc_resolved_address* resolved_addr) {
if (resolved_addr->len == 0) return "";
- grpc_resolved_address addr_normalized;
- if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) {
- resolved_addr = &addr_normalized;
- }
- const char* scheme = grpc_sockaddr_get_uri_scheme(resolved_addr);
- if (scheme == nullptr || strcmp("unix", scheme) == 0) {
- return grpc_sockaddr_to_uri_unix_if_possible(resolved_addr);
- }
+ grpc_resolved_address addr_normalized;
+ if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) {
+ resolved_addr = &addr_normalized;
+ }
+ const char* scheme = grpc_sockaddr_get_uri_scheme(resolved_addr);
+ if (scheme == nullptr || strcmp("unix", scheme) == 0) {
+ return grpc_sockaddr_to_uri_unix_if_possible(resolved_addr);
+ }
TString path =
grpc_sockaddr_to_string(resolved_addr, false /* normalize */);
TString uri_str;
if (scheme != nullptr) {
uri_str = y_absl::StrCat(scheme, ":", path);
- }
+ }
return uri_str;
-}
-
-const char* grpc_sockaddr_get_uri_scheme(
- const grpc_resolved_address* resolved_addr) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- switch (addr->sa_family) {
- case GRPC_AF_INET:
- return "ipv4";
- case GRPC_AF_INET6:
- return "ipv6";
- case GRPC_AF_UNIX:
- return "unix";
- }
- return nullptr;
-}
-
-int grpc_sockaddr_get_family(const grpc_resolved_address* resolved_addr) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- return addr->sa_family;
-}
-
-int grpc_sockaddr_get_port(const grpc_resolved_address* resolved_addr) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- switch (addr->sa_family) {
- case GRPC_AF_INET:
- return grpc_ntohs(((grpc_sockaddr_in*)addr)->sin_port);
- case GRPC_AF_INET6:
- return grpc_ntohs(((grpc_sockaddr_in6*)addr)->sin6_port);
- default:
- if (grpc_is_unix_socket(resolved_addr)) {
- return 1;
- }
- gpr_log(GPR_ERROR, "Unknown socket family %d in grpc_sockaddr_get_port",
- addr->sa_family);
- return 0;
- }
-}
-
-int grpc_sockaddr_set_port(const grpc_resolved_address* resolved_addr,
- int port) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- switch (addr->sa_family) {
- case GRPC_AF_INET:
- GPR_ASSERT(port >= 0 && port < 65536);
- ((grpc_sockaddr_in*)addr)->sin_port =
- grpc_htons(static_cast<uint16_t>(port));
- return 1;
- case GRPC_AF_INET6:
- GPR_ASSERT(port >= 0 && port < 65536);
- ((grpc_sockaddr_in6*)addr)->sin6_port =
- grpc_htons(static_cast<uint16_t>(port));
- return 1;
- default:
- gpr_log(GPR_ERROR, "Unknown socket family %d in grpc_sockaddr_set_port",
- addr->sa_family);
- return 0;
- }
-}
+}
+
+const char* grpc_sockaddr_get_uri_scheme(
+ const grpc_resolved_address* resolved_addr) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ switch (addr->sa_family) {
+ case GRPC_AF_INET:
+ return "ipv4";
+ case GRPC_AF_INET6:
+ return "ipv6";
+ case GRPC_AF_UNIX:
+ return "unix";
+ }
+ return nullptr;
+}
+
+int grpc_sockaddr_get_family(const grpc_resolved_address* resolved_addr) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ return addr->sa_family;
+}
+
+int grpc_sockaddr_get_port(const grpc_resolved_address* resolved_addr) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ switch (addr->sa_family) {
+ case GRPC_AF_INET:
+ return grpc_ntohs(((grpc_sockaddr_in*)addr)->sin_port);
+ case GRPC_AF_INET6:
+ return grpc_ntohs(((grpc_sockaddr_in6*)addr)->sin6_port);
+ default:
+ if (grpc_is_unix_socket(resolved_addr)) {
+ return 1;
+ }
+ gpr_log(GPR_ERROR, "Unknown socket family %d in grpc_sockaddr_get_port",
+ addr->sa_family);
+ return 0;
+ }
+}
+
+int grpc_sockaddr_set_port(const grpc_resolved_address* resolved_addr,
+ int port) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ switch (addr->sa_family) {
+ case GRPC_AF_INET:
+ GPR_ASSERT(port >= 0 && port < 65536);
+ ((grpc_sockaddr_in*)addr)->sin_port =
+ grpc_htons(static_cast<uint16_t>(port));
+ return 1;
+ case GRPC_AF_INET6:
+ GPR_ASSERT(port >= 0 && port < 65536);
+ ((grpc_sockaddr_in6*)addr)->sin6_port =
+ grpc_htons(static_cast<uint16_t>(port));
+ return 1;
+ default:
+ gpr_log(GPR_ERROR, "Unknown socket family %d in grpc_sockaddr_set_port",
+ addr->sa_family);
+ return 0;
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.h b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.h
index eeedeeb90c6..acd0e3f385e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_utils.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SOCKADDR_UTILS_H
#define GRPC_CORE_LIB_IOMGR_SOCKADDR_UTILS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include "src/core/lib/iomgr/resolve_address.h"
@@ -30,33 +30,33 @@
If addr4_out is non-NULL, the inner IPv4 address will be copied here when
returning true. */
-int grpc_sockaddr_is_v4mapped(const grpc_resolved_address* addr,
- grpc_resolved_address* addr4_out);
+int grpc_sockaddr_is_v4mapped(const grpc_resolved_address* addr,
+ grpc_resolved_address* addr4_out);
/* If addr is an AF_INET address, writes the corresponding ::ffff:0.0.0.0/96
address to addr6_out and returns true. Otherwise returns false. */
-int grpc_sockaddr_to_v4mapped(const grpc_resolved_address* addr,
- grpc_resolved_address* addr6_out);
+int grpc_sockaddr_to_v4mapped(const grpc_resolved_address* addr,
+ grpc_resolved_address* addr6_out);
/* If addr is ::, 0.0.0.0, or ::ffff:0.0.0.0, writes the port number to
- *port_out (if not NULL) and returns true, otherwise returns false. */
-int grpc_sockaddr_is_wildcard(const grpc_resolved_address* addr, int* port_out);
+ *port_out (if not NULL) and returns true, otherwise returns false. */
+int grpc_sockaddr_is_wildcard(const grpc_resolved_address* addr, int* port_out);
/* Writes 0.0.0.0:port and [::]:port to separate sockaddrs. */
-void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address* wild4_out,
- grpc_resolved_address* wild6_out);
+void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address* wild4_out,
+ grpc_resolved_address* wild6_out);
/* Writes 0.0.0.0:port. */
-void grpc_sockaddr_make_wildcard4(int port, grpc_resolved_address* wild_out);
+void grpc_sockaddr_make_wildcard4(int port, grpc_resolved_address* wild_out);
/* Writes [::]:port. */
-void grpc_sockaddr_make_wildcard6(int port, grpc_resolved_address* wild_out);
+void grpc_sockaddr_make_wildcard6(int port, grpc_resolved_address* wild_out);
/* Return the IP port number of a sockaddr */
-int grpc_sockaddr_get_port(const grpc_resolved_address* addr);
+int grpc_sockaddr_get_port(const grpc_resolved_address* addr);
/* Set IP port number of a sockaddr */
-int grpc_sockaddr_set_port(const grpc_resolved_address* addr, int port);
+int grpc_sockaddr_set_port(const grpc_resolved_address* addr, int port);
// Converts a sockaddr into a newly-allocated human-readable string.
//
@@ -69,12 +69,12 @@ TString grpc_sockaddr_to_string(const grpc_resolved_address* addr,
void grpc_string_to_sockaddr(grpc_resolved_address* out, const char* addr,
int port);
-/* Returns the URI string corresponding to \a addr */
+/* Returns the URI string corresponding to \a addr */
TString grpc_sockaddr_to_uri(const grpc_resolved_address* addr);
-
-/* Returns the URI scheme corresponding to \a addr */
-const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* addr);
-
-int grpc_sockaddr_get_family(const grpc_resolved_address* resolved_addr);
-
+
+/* Returns the URI scheme corresponding to \a addr */
+const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* addr);
+
+int grpc_sockaddr_get_family(const grpc_resolved_address* resolved_addr);
+
#endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_UTILS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_windows.h
index 9faebbc254f..235d1dc3135 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_windows.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_windows.h
@@ -1,30 +1,30 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SOCKADDR_WINDOWS_H
#define GRPC_CORE_LIB_IOMGR_SOCKADDR_WINDOWS_H
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
#define OPTIONAL
#include <winsock2.h>
@@ -35,25 +35,25 @@
#undef OPTIONAL
-typedef struct sockaddr grpc_sockaddr;
-typedef struct sockaddr_in grpc_sockaddr_in;
-typedef struct in_addr grpc_in_addr;
-typedef struct sockaddr_in6 grpc_sockaddr_in6;
-typedef struct in6_addr grpc_in6_addr;
-
-#define GRPC_INET_ADDRSTRLEN INET_ADDRSTRLEN
-#define GRPC_INET6_ADDRSTRLEN INET6_ADDRSTRLEN
-
-#define GRPC_SOCK_STREAM SOCK_STREAM
-#define GRPC_SOCK_DGRAM SOCK_DGRAM
-
-#define GRPC_AF_UNSPEC AF_UNSPEC
-#define GRPC_AF_UNIX AF_UNIX
-#define GRPC_AF_INET AF_INET
-#define GRPC_AF_INET6 AF_INET6
-
-#define GRPC_AI_PASSIVE AI_PASSIVE
-
-#endif
-
+typedef struct sockaddr grpc_sockaddr;
+typedef struct sockaddr_in grpc_sockaddr_in;
+typedef struct in_addr grpc_in_addr;
+typedef struct sockaddr_in6 grpc_sockaddr_in6;
+typedef struct in6_addr grpc_in6_addr;
+
+#define GRPC_INET_ADDRSTRLEN INET_ADDRSTRLEN
+#define GRPC_INET6_ADDRSTRLEN INET6_ADDRSTRLEN
+
+#define GRPC_SOCK_STREAM SOCK_STREAM
+#define GRPC_SOCK_DGRAM SOCK_DGRAM
+
+#define GRPC_AF_UNSPEC AF_UNSPEC
+#define GRPC_AF_UNIX AF_UNIX
+#define GRPC_AF_INET AF_INET
+#define GRPC_AF_INET6 AF_INET6
+
+#define GRPC_AI_PASSIVE AI_PASSIVE
+
+#endif
+
#endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc
index 57137769c83..25b1a303d9e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_SOCKET_FACTORY
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/socket_factory_posix.h"
-
-#include <grpc/impl/codegen/grpc_types.h>
-#include <grpc/support/sync.h>
-
-void grpc_socket_factory_init(grpc_socket_factory* factory,
- const grpc_socket_factory_vtable* vtable) {
- factory->vtable = vtable;
- gpr_ref_init(&factory->refcount, 1);
-}
-
-int grpc_socket_factory_socket(grpc_socket_factory* factory, int domain,
- int type, int protocol) {
- return factory->vtable->socket(factory, domain, type, protocol);
-}
-
-int grpc_socket_factory_bind(grpc_socket_factory* factory, int sockfd,
- const grpc_resolved_address* addr) {
- return factory->vtable->bind(factory, sockfd, addr);
-}
-
-int grpc_socket_factory_compare(grpc_socket_factory* a,
- grpc_socket_factory* b) {
- int c = GPR_ICMP(a, b);
- if (c != 0) {
- grpc_socket_factory* sma = a;
- grpc_socket_factory* smb = b;
- c = GPR_ICMP(sma->vtable, smb->vtable);
- if (c == 0) {
- c = sma->vtable->compare(sma, smb);
- }
- }
- return c;
-}
-
-grpc_socket_factory* grpc_socket_factory_ref(grpc_socket_factory* factory) {
- gpr_ref(&factory->refcount);
- return factory;
-}
-
-void grpc_socket_factory_unref(grpc_socket_factory* factory) {
- if (gpr_unref(&factory->refcount)) {
- factory->vtable->destroy(factory);
- }
-}
-
-static void* socket_factory_arg_copy(void* p) {
- return grpc_socket_factory_ref(static_cast<grpc_socket_factory*>(p));
-}
-
-static void socket_factory_arg_destroy(void* p) {
- grpc_socket_factory_unref(static_cast<grpc_socket_factory*>(p));
-}
-
-static int socket_factory_cmp(void* a, void* b) {
- return grpc_socket_factory_compare(static_cast<grpc_socket_factory*>(a),
- static_cast<grpc_socket_factory*>(b));
-}
-
-static const grpc_arg_pointer_vtable socket_factory_arg_vtable = {
- socket_factory_arg_copy, socket_factory_arg_destroy, socket_factory_cmp};
-
-grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory* factory) {
- return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SOCKET_FACTORY,
- factory, &socket_factory_arg_vtable);
-}
-
-#endif
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/socket_factory_posix.h"
+
+#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/support/sync.h>
+
+void grpc_socket_factory_init(grpc_socket_factory* factory,
+ const grpc_socket_factory_vtable* vtable) {
+ factory->vtable = vtable;
+ gpr_ref_init(&factory->refcount, 1);
+}
+
+int grpc_socket_factory_socket(grpc_socket_factory* factory, int domain,
+ int type, int protocol) {
+ return factory->vtable->socket(factory, domain, type, protocol);
+}
+
+int grpc_socket_factory_bind(grpc_socket_factory* factory, int sockfd,
+ const grpc_resolved_address* addr) {
+ return factory->vtable->bind(factory, sockfd, addr);
+}
+
+int grpc_socket_factory_compare(grpc_socket_factory* a,
+ grpc_socket_factory* b) {
+ int c = GPR_ICMP(a, b);
+ if (c != 0) {
+ grpc_socket_factory* sma = a;
+ grpc_socket_factory* smb = b;
+ c = GPR_ICMP(sma->vtable, smb->vtable);
+ if (c == 0) {
+ c = sma->vtable->compare(sma, smb);
+ }
+ }
+ return c;
+}
+
+grpc_socket_factory* grpc_socket_factory_ref(grpc_socket_factory* factory) {
+ gpr_ref(&factory->refcount);
+ return factory;
+}
+
+void grpc_socket_factory_unref(grpc_socket_factory* factory) {
+ if (gpr_unref(&factory->refcount)) {
+ factory->vtable->destroy(factory);
+ }
+}
+
+static void* socket_factory_arg_copy(void* p) {
+ return grpc_socket_factory_ref(static_cast<grpc_socket_factory*>(p));
+}
+
+static void socket_factory_arg_destroy(void* p) {
+ grpc_socket_factory_unref(static_cast<grpc_socket_factory*>(p));
+}
+
+static int socket_factory_cmp(void* a, void* b) {
+ return grpc_socket_factory_compare(static_cast<grpc_socket_factory*>(a),
+ static_cast<grpc_socket_factory*>(b));
+}
+
+static const grpc_arg_pointer_vtable socket_factory_arg_vtable = {
+ socket_factory_arg_copy, socket_factory_arg_destroy, socket_factory_cmp};
+
+grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory* factory) {
+ return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SOCKET_FACTORY,
+ factory, &socket_factory_arg_vtable);
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.h
index 92ea6c16b70..d29f0a72519 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.h
@@ -1,68 +1,68 @@
-/*
- *
- * 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_IOMGR_SOCKET_FACTORY_POSIX_H
-#define GRPC_CORE_LIB_IOMGR_SOCKET_FACTORY_POSIX_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/impl/codegen/grpc_types.h>
-#include <grpc/support/sync.h>
-#include "src/core/lib/iomgr/resolve_address.h"
-
-/** The virtual table of grpc_socket_factory */
+/*
+ *
+ * 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_IOMGR_SOCKET_FACTORY_POSIX_H
+#define GRPC_CORE_LIB_IOMGR_SOCKET_FACTORY_POSIX_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/support/sync.h>
+#include "src/core/lib/iomgr/resolve_address.h"
+
+/** The virtual table of grpc_socket_factory */
struct grpc_socket_factory_vtable {
- /** Replacement for socket(2) */
- int (*socket)(grpc_socket_factory* factory, int domain, int type,
- int protocol);
- /** Replacement for bind(2) */
- int (*bind)(grpc_socket_factory* factory, int sockfd,
- const grpc_resolved_address* addr);
- /** Compare socket factory \a a and \a b */
- int (*compare)(grpc_socket_factory* a, grpc_socket_factory* b);
- /** Destroys the socket factory instance */
- void (*destroy)(grpc_socket_factory* factory);
+ /** Replacement for socket(2) */
+ int (*socket)(grpc_socket_factory* factory, int domain, int type,
+ int protocol);
+ /** Replacement for bind(2) */
+ int (*bind)(grpc_socket_factory* factory, int sockfd,
+ const grpc_resolved_address* addr);
+ /** Compare socket factory \a a and \a b */
+ int (*compare)(grpc_socket_factory* a, grpc_socket_factory* b);
+ /** Destroys the socket factory instance */
+ void (*destroy)(grpc_socket_factory* factory);
};
-/** The Socket Factory interface allows changes on socket options */
-struct grpc_socket_factory {
- const grpc_socket_factory_vtable* vtable;
- gpr_refcount refcount;
-};
-
-/** called by concrete implementations to initialize the base struct */
-void grpc_socket_factory_init(grpc_socket_factory* factory,
- const grpc_socket_factory_vtable* vtable);
-
-/** Wrap \a factory as a grpc_arg */
-grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory* factory);
-
-/** Perform the equivalent of a socket(2) operation using \a factory */
-int grpc_socket_factory_socket(grpc_socket_factory* factory, int domain,
- int type, int protocol);
-
-/** Perform the equivalent of a bind(2) operation using \a factory */
-int grpc_socket_factory_bind(grpc_socket_factory* factory, int sockfd,
- const grpc_resolved_address* addr);
-
-/** Compare if \a a and \a b are the same factory or have same settings */
-int grpc_socket_factory_compare(grpc_socket_factory* a, grpc_socket_factory* b);
-
-grpc_socket_factory* grpc_socket_factory_ref(grpc_socket_factory* factory);
-void grpc_socket_factory_unref(grpc_socket_factory* factory);
-
-#endif /* GRPC_CORE_LIB_IOMGR_SOCKET_FACTORY_POSIX_H */
+/** The Socket Factory interface allows changes on socket options */
+struct grpc_socket_factory {
+ const grpc_socket_factory_vtable* vtable;
+ gpr_refcount refcount;
+};
+
+/** called by concrete implementations to initialize the base struct */
+void grpc_socket_factory_init(grpc_socket_factory* factory,
+ const grpc_socket_factory_vtable* vtable);
+
+/** Wrap \a factory as a grpc_arg */
+grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory* factory);
+
+/** Perform the equivalent of a socket(2) operation using \a factory */
+int grpc_socket_factory_socket(grpc_socket_factory* factory, int domain,
+ int type, int protocol);
+
+/** Perform the equivalent of a bind(2) operation using \a factory */
+int grpc_socket_factory_bind(grpc_socket_factory* factory, int sockfd,
+ const grpc_resolved_address* addr);
+
+/** Compare if \a a and \a b are the same factory or have same settings */
+int grpc_socket_factory_compare(grpc_socket_factory* a, grpc_socket_factory* b);
+
+grpc_socket_factory* grpc_socket_factory_ref(grpc_socket_factory* factory);
+void grpc_socket_factory_unref(grpc_socket_factory* factory);
+
+#endif /* GRPC_CORE_LIB_IOMGR_SOCKET_FACTORY_POSIX_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc
index a448c9f61c3..45cf9b3f21d 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc
@@ -1,83 +1,83 @@
-/*
- *
- * 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/iomgr/socket_mutator.h"
-
-#include <grpc/impl/codegen/grpc_types.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/useful.h"
-
-void grpc_socket_mutator_init(grpc_socket_mutator* mutator,
- const grpc_socket_mutator_vtable* vtable) {
- mutator->vtable = vtable;
- gpr_ref_init(&mutator->refcount, 1);
-}
-
-grpc_socket_mutator* grpc_socket_mutator_ref(grpc_socket_mutator* mutator) {
- gpr_ref(&mutator->refcount);
- return mutator;
-}
-
-bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator* mutator, int fd) {
- return mutator->vtable->mutate_fd(fd, mutator);
-}
-
-int grpc_socket_mutator_compare(grpc_socket_mutator* a,
- grpc_socket_mutator* b) {
- int c = GPR_ICMP(a, b);
- if (c != 0) {
- grpc_socket_mutator* sma = a;
- grpc_socket_mutator* smb = b;
- c = GPR_ICMP(sma->vtable, smb->vtable);
- if (c == 0) {
- c = sma->vtable->compare(sma, smb);
- }
- }
- return c;
-}
-
-void grpc_socket_mutator_unref(grpc_socket_mutator* mutator) {
- if (gpr_unref(&mutator->refcount)) {
+/*
+ *
+ * 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/iomgr/socket_mutator.h"
+
+#include <grpc/impl/codegen/grpc_types.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/useful.h"
+
+void grpc_socket_mutator_init(grpc_socket_mutator* mutator,
+ const grpc_socket_mutator_vtable* vtable) {
+ mutator->vtable = vtable;
+ gpr_ref_init(&mutator->refcount, 1);
+}
+
+grpc_socket_mutator* grpc_socket_mutator_ref(grpc_socket_mutator* mutator) {
+ gpr_ref(&mutator->refcount);
+ return mutator;
+}
+
+bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator* mutator, int fd) {
+ return mutator->vtable->mutate_fd(fd, mutator);
+}
+
+int grpc_socket_mutator_compare(grpc_socket_mutator* a,
+ grpc_socket_mutator* b) {
+ int c = GPR_ICMP(a, b);
+ if (c != 0) {
+ grpc_socket_mutator* sma = a;
+ grpc_socket_mutator* smb = b;
+ c = GPR_ICMP(sma->vtable, smb->vtable);
+ if (c == 0) {
+ c = sma->vtable->compare(sma, smb);
+ }
+ }
+ return c;
+}
+
+void grpc_socket_mutator_unref(grpc_socket_mutator* mutator) {
+ if (gpr_unref(&mutator->refcount)) {
mutator->vtable->destroy(mutator);
- }
-}
-
-static void* socket_mutator_arg_copy(void* p) {
- return grpc_socket_mutator_ref(static_cast<grpc_socket_mutator*>(p));
-}
-
-static void socket_mutator_arg_destroy(void* p) {
- grpc_socket_mutator_unref(static_cast<grpc_socket_mutator*>(p));
-}
-
-static int socket_mutator_cmp(void* a, void* b) {
- return grpc_socket_mutator_compare(static_cast<grpc_socket_mutator*>(a),
- static_cast<grpc_socket_mutator*>(b));
-}
-
-static const grpc_arg_pointer_vtable socket_mutator_arg_vtable = {
- socket_mutator_arg_copy, socket_mutator_arg_destroy, socket_mutator_cmp};
-
-grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator* mutator) {
- return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SOCKET_MUTATOR,
- mutator, &socket_mutator_arg_vtable);
-}
+ }
+}
+
+static void* socket_mutator_arg_copy(void* p) {
+ return grpc_socket_mutator_ref(static_cast<grpc_socket_mutator*>(p));
+}
+
+static void socket_mutator_arg_destroy(void* p) {
+ grpc_socket_mutator_unref(static_cast<grpc_socket_mutator*>(p));
+}
+
+static int socket_mutator_cmp(void* a, void* b) {
+ return grpc_socket_mutator_compare(static_cast<grpc_socket_mutator*>(a),
+ static_cast<grpc_socket_mutator*>(b));
+}
+
+static const grpc_arg_pointer_vtable socket_mutator_arg_vtable = {
+ socket_mutator_arg_copy, socket_mutator_arg_destroy, socket_mutator_cmp};
+
+grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator* mutator) {
+ return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SOCKET_MUTATOR,
+ mutator, &socket_mutator_arg_vtable);
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h
index 9f77a3b2661..72898297e07 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h
@@ -1,60 +1,60 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SOCKET_MUTATOR_H
#define GRPC_CORE_LIB_IOMGR_SOCKET_MUTATOR_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/sync.h>
-#include <stdbool.h>
+#include <stdbool.h>
/** The virtual table of grpc_socket_mutator */
struct grpc_socket_mutator_vtable {
- /** Mutates the socket options of \a fd */
- bool (*mutate_fd)(int fd, grpc_socket_mutator* mutator);
+ /** Mutates the socket options of \a fd */
+ bool (*mutate_fd)(int fd, grpc_socket_mutator* mutator);
/** Compare socket mutator \a a and \a b */
- int (*compare)(grpc_socket_mutator* a, grpc_socket_mutator* b);
+ int (*compare)(grpc_socket_mutator* a, grpc_socket_mutator* b);
/** Destroys the socket mutator instance */
void (*destroy)(grpc_socket_mutator* mutator);
};
/** The Socket Mutator interface allows changes on socket options */
struct grpc_socket_mutator {
- const grpc_socket_mutator_vtable* vtable;
+ const grpc_socket_mutator_vtable* vtable;
gpr_refcount refcount;
};
/** called by concrete implementations to initialize the base struct */
-void grpc_socket_mutator_init(grpc_socket_mutator* mutator,
- const grpc_socket_mutator_vtable* vtable);
+void grpc_socket_mutator_init(grpc_socket_mutator* mutator,
+ const grpc_socket_mutator_vtable* vtable);
/** Wrap \a mutator as a grpc_arg */
-grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator* mutator);
+grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator* mutator);
/** Perform the file descriptor mutation operation of \a mutator on \a fd */
-bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator* mutator, int fd);
+bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator* mutator, int fd);
/** Compare if \a a and \a b are the same mutator or have same settings */
-int grpc_socket_mutator_compare(grpc_socket_mutator* a, grpc_socket_mutator* b);
+int grpc_socket_mutator_compare(grpc_socket_mutator* a, grpc_socket_mutator* b);
-grpc_socket_mutator* grpc_socket_mutator_ref(grpc_socket_mutator* mutator);
-void grpc_socket_mutator_unref(grpc_socket_mutator* mutator);
+grpc_socket_mutator* grpc_socket_mutator_ref(grpc_socket_mutator* mutator);
+void grpc_socket_mutator_unref(grpc_socket_mutator* mutator);
#endif /* GRPC_CORE_LIB_IOMGR_SOCKET_MUTATOR_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h
index 14bb081e935..bcc9cd02d49 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h
@@ -1,47 +1,47 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SOCKET_UTILS_H
#define GRPC_CORE_LIB_IOMGR_SOCKET_UTILS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stddef.h>
// TODO(juanlishen): The following functions might be simple enough to implement
// ourselves, so that they don't cause any portability hassle.
-/* A wrapper for htons on POSIX and Windows */
-uint16_t grpc_htons(uint16_t hostshort);
-
-/* A wrapper for ntohs on POSIX and WINDOWS */
-uint16_t grpc_ntohs(uint16_t netshort);
-
+/* A wrapper for htons on POSIX and Windows */
+uint16_t grpc_htons(uint16_t hostshort);
+
+/* A wrapper for ntohs on POSIX and WINDOWS */
+uint16_t grpc_ntohs(uint16_t netshort);
+
/* A wrapper for htonl on POSIX and Windows */
uint32_t grpc_htonl(uint32_t hostlong);
/* A wrapper for ntohl on POSIX and WINDOWS */
uint32_t grpc_ntohl(uint32_t netlong);
-/* A wrapper for inet_pton on POSIX and WINDOWS */
-int grpc_inet_pton(int af, const char* src, void* dst);
-
+/* A wrapper for inet_pton on POSIX and WINDOWS */
+int grpc_inet_pton(int af, const char* src, void* dst);
+
/* A wrapper for inet_ntop on POSIX systems and InetNtop on Windows systems */
-const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size);
+const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size);
#endif /* GRPC_CORE_LIB_IOMGR_SOCKET_UTILS_H */
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 8a8d4d3a22f..25d848df936 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
@@ -1,64 +1,64 @@
-/*
- *
- * 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/iomgr/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/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_UTILS_COMMON
-
-#include "src/core/lib/iomgr/socket_utils.h"
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-
-#include <arpa/inet.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <netinet/in.h>
+
+#include "src/core/lib/iomgr/socket_utils.h"
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <netinet/in.h>
#ifdef GRPC_LINUX_TCP_H
#include <linux/tcp.h>
#else
-#include <netinet/tcp.h>
+#include <netinet/tcp.h>
#endif
-#include <stdio.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
+#include <stdio.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+
#include <util/generic/string.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-
-#include <stdbool.h>
-extern "C" bool IsReusePortAvailable();
-
-#ifndef SO_REUSEPORT
-#define SO_REUSEPORT 15
-#endif
-
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+
+#include <stdbool.h>
+extern "C" bool IsReusePortAvailable();
+
+#ifndef SO_REUSEPORT
+#define SO_REUSEPORT 15
+#endif
+
#ifndef TCP_USER_TIMEOUT
#define TCP_USER_TIMEOUT 18 /* How long for loss retry before timeout */
#endif
@@ -77,186 +77,186 @@ grpc_error* grpc_set_socket_zerocopy(int fd) {
#endif
}
-/* set a socket to non blocking mode */
-grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking) {
- int oldflags = fcntl(fd, F_GETFL, 0);
- if (oldflags < 0) {
- return GRPC_OS_ERROR(errno, "fcntl");
- }
-
- if (non_blocking) {
- oldflags |= O_NONBLOCK;
- } else {
- oldflags &= ~O_NONBLOCK;
- }
-
- if (fcntl(fd, F_SETFL, oldflags) != 0) {
- return GRPC_OS_ERROR(errno, "fcntl");
- }
-
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd) {
-#ifdef GRPC_HAVE_SO_NOSIGPIPE
- int val = 1;
- int newval;
- socklen_t intlen = sizeof(newval);
- if (0 != setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val))) {
- return GRPC_OS_ERROR(errno, "setsockopt(SO_NOSIGPIPE)");
- }
- if (0 != getsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &newval, &intlen)) {
- return GRPC_OS_ERROR(errno, "getsockopt(SO_NOSIGPIPE)");
- }
- if ((newval != 0) != (val != 0)) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_NOSIGPIPE");
- }
+/* set a socket to non blocking mode */
+grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking) {
+ int oldflags = fcntl(fd, F_GETFL, 0);
+ if (oldflags < 0) {
+ return GRPC_OS_ERROR(errno, "fcntl");
+ }
+
+ if (non_blocking) {
+ oldflags |= O_NONBLOCK;
+ } else {
+ oldflags &= ~O_NONBLOCK;
+ }
+
+ if (fcntl(fd, F_SETFL, oldflags) != 0) {
+ return GRPC_OS_ERROR(errno, "fcntl");
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd) {
+#ifdef GRPC_HAVE_SO_NOSIGPIPE
+ int val = 1;
+ int newval;
+ socklen_t intlen = sizeof(newval);
+ if (0 != setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val))) {
+ return GRPC_OS_ERROR(errno, "setsockopt(SO_NOSIGPIPE)");
+ }
+ if (0 != getsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &newval, &intlen)) {
+ return GRPC_OS_ERROR(errno, "getsockopt(SO_NOSIGPIPE)");
+ }
+ 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;
-#endif
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int 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;
-#ifdef GRPC_HAVE_IP_PKTINFO
- int get_local_ip = 1;
- if (0 != setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip,
- sizeof(get_local_ip))) {
- return GRPC_OS_ERROR(errno, "setsockopt(IP_PKTINFO)");
- }
-#endif
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) {
+#ifdef GRPC_HAVE_IP_PKTINFO
+ int get_local_ip = 1;
+ if (0 != setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip,
+ sizeof(get_local_ip))) {
+ return GRPC_OS_ERROR(errno, "setsockopt(IP_PKTINFO)");
+ }
+#endif
+ return GRPC_ERROR_NONE;
+}
+
+grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int 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,
- sizeof(get_local_ip))) {
- return GRPC_OS_ERROR(errno, "setsockopt(IPV6_RECVPKTINFO)");
- }
-#endif
- return GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes) {
- return 0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffer_size_bytes,
- sizeof(buffer_size_bytes))
- ? GRPC_ERROR_NONE
- : GRPC_OS_ERROR(errno, "setsockopt(SO_SNDBUF)");
-}
-
-grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) {
- return 0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buffer_size_bytes,
- sizeof(buffer_size_bytes))
- ? GRPC_ERROR_NONE
- : GRPC_OS_ERROR(errno, "setsockopt(SO_RCVBUF)");
-}
-
-/* set a socket to close on exec */
-grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec) {
- int oldflags = fcntl(fd, F_GETFD, 0);
- if (oldflags < 0) {
- return GRPC_OS_ERROR(errno, "fcntl");
- }
-
- if (close_on_exec) {
- oldflags |= FD_CLOEXEC;
- } else {
- oldflags &= ~FD_CLOEXEC;
- }
-
- if (fcntl(fd, F_SETFD, oldflags) != 0) {
- return GRPC_OS_ERROR(errno, "fcntl");
- }
-
- return GRPC_ERROR_NONE;
-}
-
-/* set a socket to reuse old addresses */
-grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse) {
- int val = (reuse != 0);
- int newval;
- socklen_t intlen = sizeof(newval);
- if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) {
- return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEADDR)");
- }
- if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &newval, &intlen)) {
- return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEADDR)");
- }
- if ((newval != 0) != val) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEADDR");
- }
-
- return GRPC_ERROR_NONE;
-}
-
-/* set a socket to reuse old addresses */
-grpc_error *grpc_set_socket_reuse_port(int fd, int reuse) {
- if (!IsReusePortAvailable()) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "SO_REUSEPORT unavailable on host system");
- }
- int val = (reuse != 0);
- int newval;
- socklen_t intlen = sizeof(newval);
- if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val))) {
- return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEPORT)");
- }
- if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &newval, &intlen)) {
- return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEPORT)");
- }
- if ((newval != 0) != val) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEPORT");
- }
-
- return GRPC_ERROR_NONE;
-}
-
-static gpr_once g_probe_so_reuesport_once = GPR_ONCE_INIT;
-static int g_support_so_reuseport = false;
-
-void probe_so_reuseport_once(void) {
- int s = socket(AF_INET, SOCK_STREAM, 0);
- if (s < 0) {
- /* This might be an ipv6-only environment in which case 'socket(AF_INET,..)'
- call would fail. Try creating IPv6 socket in that case */
- s = socket(AF_INET6, SOCK_STREAM, 0);
- }
- if (s >= 0) {
- g_support_so_reuseport = GRPC_LOG_IF_ERROR(
- "check for SO_REUSEPORT", grpc_set_socket_reuse_port(s, 1));
- close(s);
- }
-}
-
-bool grpc_is_socket_reuse_port_supported() {
- gpr_once_init(&g_probe_so_reuesport_once, probe_so_reuseport_once);
- return g_support_so_reuseport;
-}
-
-/* disable nagle */
-grpc_error* grpc_set_socket_low_latency(int fd, int low_latency) {
- int val = (low_latency != 0);
- int newval;
- socklen_t intlen = sizeof(newval);
- if (0 != setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val))) {
- return GRPC_OS_ERROR(errno, "setsockopt(TCP_NODELAY)");
- }
- if (0 != getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &newval, &intlen)) {
- return GRPC_OS_ERROR(errno, "getsockopt(TCP_NODELAY)");
- }
- if ((newval != 0) != val) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set TCP_NODELAY");
- }
- return GRPC_ERROR_NONE;
-}
-
+#ifdef GRPC_HAVE_IPV6_RECVPKTINFO
+ int get_local_ip = 1;
+ if (0 != setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &get_local_ip,
+ sizeof(get_local_ip))) {
+ return GRPC_OS_ERROR(errno, "setsockopt(IPV6_RECVPKTINFO)");
+ }
+#endif
+ return GRPC_ERROR_NONE;
+}
+
+grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes) {
+ return 0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffer_size_bytes,
+ sizeof(buffer_size_bytes))
+ ? GRPC_ERROR_NONE
+ : GRPC_OS_ERROR(errno, "setsockopt(SO_SNDBUF)");
+}
+
+grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) {
+ return 0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buffer_size_bytes,
+ sizeof(buffer_size_bytes))
+ ? GRPC_ERROR_NONE
+ : GRPC_OS_ERROR(errno, "setsockopt(SO_RCVBUF)");
+}
+
+/* set a socket to close on exec */
+grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec) {
+ int oldflags = fcntl(fd, F_GETFD, 0);
+ if (oldflags < 0) {
+ return GRPC_OS_ERROR(errno, "fcntl");
+ }
+
+ if (close_on_exec) {
+ oldflags |= FD_CLOEXEC;
+ } else {
+ oldflags &= ~FD_CLOEXEC;
+ }
+
+ if (fcntl(fd, F_SETFD, oldflags) != 0) {
+ return GRPC_OS_ERROR(errno, "fcntl");
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+/* set a socket to reuse old addresses */
+grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse) {
+ int val = (reuse != 0);
+ int newval;
+ socklen_t intlen = sizeof(newval);
+ if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) {
+ return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEADDR)");
+ }
+ if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &newval, &intlen)) {
+ return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEADDR)");
+ }
+ if ((newval != 0) != val) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEADDR");
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+/* set a socket to reuse old addresses */
+grpc_error *grpc_set_socket_reuse_port(int fd, int reuse) {
+ if (!IsReusePortAvailable()) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "SO_REUSEPORT unavailable on host system");
+ }
+ int val = (reuse != 0);
+ int newval;
+ socklen_t intlen = sizeof(newval);
+ if (0 != setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val))) {
+ return GRPC_OS_ERROR(errno, "setsockopt(SO_REUSEPORT)");
+ }
+ if (0 != getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &newval, &intlen)) {
+ return GRPC_OS_ERROR(errno, "getsockopt(SO_REUSEPORT)");
+ }
+ if ((newval != 0) != val) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set SO_REUSEPORT");
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+static gpr_once g_probe_so_reuesport_once = GPR_ONCE_INIT;
+static int g_support_so_reuseport = false;
+
+void probe_so_reuseport_once(void) {
+ int s = socket(AF_INET, SOCK_STREAM, 0);
+ if (s < 0) {
+ /* This might be an ipv6-only environment in which case 'socket(AF_INET,..)'
+ call would fail. Try creating IPv6 socket in that case */
+ s = socket(AF_INET6, SOCK_STREAM, 0);
+ }
+ if (s >= 0) {
+ g_support_so_reuseport = GRPC_LOG_IF_ERROR(
+ "check for SO_REUSEPORT", grpc_set_socket_reuse_port(s, 1));
+ close(s);
+ }
+}
+
+bool grpc_is_socket_reuse_port_supported() {
+ gpr_once_init(&g_probe_so_reuesport_once, probe_so_reuseport_once);
+ return g_support_so_reuseport;
+}
+
+/* disable nagle */
+grpc_error* grpc_set_socket_low_latency(int fd, int low_latency) {
+ int val = (low_latency != 0);
+ int newval;
+ socklen_t intlen = sizeof(newval);
+ if (0 != setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val))) {
+ return GRPC_OS_ERROR(errno, "setsockopt(TCP_NODELAY)");
+ }
+ if (0 != getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &newval, &intlen)) {
+ return GRPC_OS_ERROR(errno, "getsockopt(TCP_NODELAY)");
+ }
+ if ((newval != 0) != val) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set TCP_NODELAY");
+ }
+ return GRPC_ERROR_NONE;
+}
+
/* The default values for TCP_USER_TIMEOUT are currently configured to be in
* line with the default values of KEEPALIVE_TIMEOUT as proposed in
* https://github.com/grpc/proposal/blob/master/A18-tcp-user-timeout.md */
@@ -396,15 +396,15 @@ grpc_error* grpc_set_socket_tcp_user_timeout(
return GRPC_ERROR_NONE;
}
-/* set a socket using a grpc_socket_mutator */
-grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator) {
- GPR_ASSERT(mutator);
- if (!grpc_socket_mutator_mutate_fd(mutator, fd)) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("grpc_socket_mutator failed.");
- }
- return GRPC_ERROR_NONE;
-}
-
+/* set a socket using a grpc_socket_mutator */
+grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator) {
+ GPR_ASSERT(mutator);
+ if (!grpc_socket_mutator_mutate_fd(mutator, fd)) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("grpc_socket_mutator failed.");
+ }
+ 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 =
@@ -418,106 +418,106 @@ grpc_error* grpc_apply_socket_mutator_in_args(int fd,
return grpc_set_socket_with_mutator(fd, mutator);
}
-static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT;
-static int g_ipv6_loopback_available;
-
-static void probe_ipv6_once(void) {
- int fd = socket(AF_INET6, SOCK_STREAM, 0);
- g_ipv6_loopback_available = 0;
- if (fd < 0) {
- gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed.");
- } else {
- grpc_sockaddr_in6 addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin6_family = AF_INET6;
- addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */
- if (bind(fd, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) {
- g_ipv6_loopback_available = 1;
- } else {
- gpr_log(GPR_INFO,
- "Disabling AF_INET6 sockets because ::1 is not available.");
- }
- close(fd);
- }
-}
-
-int grpc_ipv6_loopback_available(void) {
- gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once);
- return g_ipv6_loopback_available;
-}
-
-static grpc_error* error_for_fd(int fd, const grpc_resolved_address* addr) {
- if (fd >= 0) return GRPC_ERROR_NONE;
+static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT;
+static int g_ipv6_loopback_available;
+
+static void probe_ipv6_once(void) {
+ int fd = socket(AF_INET6, SOCK_STREAM, 0);
+ g_ipv6_loopback_available = 0;
+ if (fd < 0) {
+ gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed.");
+ } else {
+ grpc_sockaddr_in6 addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sin6_family = AF_INET6;
+ addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */
+ if (bind(fd, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) {
+ g_ipv6_loopback_available = 1;
+ } else {
+ gpr_log(GPR_INFO,
+ "Disabling AF_INET6 sockets because ::1 is not available.");
+ }
+ close(fd);
+ }
+}
+
+int grpc_ipv6_loopback_available(void) {
+ gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once);
+ return g_ipv6_loopback_available;
+}
+
+static grpc_error* error_for_fd(int fd, const grpc_resolved_address* addr) {
+ if (fd >= 0) return GRPC_ERROR_NONE;
TString addr_str = grpc_sockaddr_to_string(addr, false);
grpc_error* err = grpc_error_set_str(
GRPC_OS_ERROR(errno, "socket"), GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_copied_string(addr_str.c_str()));
- return err;
-}
-
-grpc_error* grpc_create_dualstack_socket(
- const grpc_resolved_address* resolved_addr, int type, int protocol,
- grpc_dualstack_mode* dsmode, int* newfd) {
- return grpc_create_dualstack_socket_using_factory(
- nullptr, resolved_addr, type, protocol, dsmode, newfd);
-}
-
-static int create_socket(grpc_socket_factory* factory, int domain, int type,
- int protocol) {
- return (factory != nullptr)
- ? grpc_socket_factory_socket(factory, domain, type, protocol)
- : socket(domain, type, protocol);
-}
-
-grpc_error* grpc_create_dualstack_socket_using_factory(
- grpc_socket_factory* factory, const grpc_resolved_address* resolved_addr,
- int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- int family = addr->sa_family;
- if (family == AF_INET6) {
- if (grpc_ipv6_loopback_available()) {
- *newfd = create_socket(factory, family, type, protocol);
- } else {
- *newfd = -1;
- errno = EAFNOSUPPORT;
- }
- /* Check if we've got a valid dualstack socket. */
+ return err;
+}
+
+grpc_error* grpc_create_dualstack_socket(
+ const grpc_resolved_address* resolved_addr, int type, int protocol,
+ grpc_dualstack_mode* dsmode, int* newfd) {
+ return grpc_create_dualstack_socket_using_factory(
+ nullptr, resolved_addr, type, protocol, dsmode, newfd);
+}
+
+static int create_socket(grpc_socket_factory* factory, int domain, int type,
+ int protocol) {
+ return (factory != nullptr)
+ ? grpc_socket_factory_socket(factory, domain, type, protocol)
+ : socket(domain, type, protocol);
+}
+
+grpc_error* grpc_create_dualstack_socket_using_factory(
+ grpc_socket_factory* factory, const grpc_resolved_address* resolved_addr,
+ int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ int family = addr->sa_family;
+ if (family == AF_INET6) {
+ if (grpc_ipv6_loopback_available()) {
+ *newfd = create_socket(factory, family, type, protocol);
+ } else {
+ *newfd = -1;
+ errno = EAFNOSUPPORT;
+ }
+ /* Check if we've got a valid dualstack socket. */
if (*newfd >= 0 && grpc_set_socket_dualstack(*newfd)) {
- *dsmode = GRPC_DSMODE_DUALSTACK;
- return GRPC_ERROR_NONE;
- }
- /* If this isn't an IPv4 address, then return whatever we've got. */
- if (!grpc_sockaddr_is_v4mapped(resolved_addr, nullptr)) {
- *dsmode = GRPC_DSMODE_IPV6;
- return error_for_fd(*newfd, resolved_addr);
- }
- /* Fall back to AF_INET. */
- if (*newfd >= 0) {
- close(*newfd);
- }
- family = AF_INET;
- }
- *dsmode = family == AF_INET ? GRPC_DSMODE_IPV4 : GRPC_DSMODE_NONE;
- *newfd = create_socket(factory, family, type, protocol);
- return error_for_fd(*newfd, resolved_addr);
-}
-
-uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); }
-
-uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); }
-
+ *dsmode = GRPC_DSMODE_DUALSTACK;
+ return GRPC_ERROR_NONE;
+ }
+ /* If this isn't an IPv4 address, then return whatever we've got. */
+ if (!grpc_sockaddr_is_v4mapped(resolved_addr, nullptr)) {
+ *dsmode = GRPC_DSMODE_IPV6;
+ return error_for_fd(*newfd, resolved_addr);
+ }
+ /* Fall back to AF_INET. */
+ if (*newfd >= 0) {
+ close(*newfd);
+ }
+ family = AF_INET;
+ }
+ *dsmode = family == AF_INET ? GRPC_DSMODE_IPV4 : GRPC_DSMODE_NONE;
+ *newfd = create_socket(factory, family, type, protocol);
+ return error_for_fd(*newfd, resolved_addr);
+}
+
+uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); }
+
+uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); }
+
uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); }
uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); }
-int grpc_inet_pton(int af, const char* src, void* dst) {
- return inet_pton(af, src, dst);
-}
-
-const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) {
- GPR_ASSERT(size <= (socklen_t)-1);
- return inet_ntop(af, src, dst, static_cast<socklen_t>(size));
-}
-
-#endif
+int grpc_inet_pton(int af, const char* src, void* dst) {
+ return inet_pton(af, src, dst);
+}
+
+const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) {
+ GPR_ASSERT(size <= (socklen_t)-1);
+ return inet_ntop(af, src, dst, static_cast<socklen_t>(size));
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_linux.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_linux.cc
index 34f93cc4b09..446a09c0222 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_linux.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_LINUX_SOCKETUTILS
-
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-
-#include <grpc/support/log.h>
-
-#include <sys/socket.h>
-#include <sys/types.h>
-
-int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock,
- int cloexec) {
- int flags = 0;
- flags |= nonblock ? SOCK_NONBLOCK : 0;
- flags |= cloexec ? SOCK_CLOEXEC : 0;
- return accept4(sockfd, reinterpret_cast<grpc_sockaddr*>(resolved_addr->addr),
- &resolved_addr->len, flags);
-}
-
-#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 <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_LINUX_SOCKETUTILS
+
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+
+#include <grpc/support/log.h>
+
+#include <sys/socket.h>
+#include <sys/types.h>
+
+int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock,
+ int cloexec) {
+ int flags = 0;
+ flags |= nonblock ? SOCK_NONBLOCK : 0;
+ flags |= cloexec ? SOCK_CLOEXEC : 0;
+ return accept4(sockfd, reinterpret_cast<grpc_sockaddr*>(resolved_addr->addr),
+ &resolved_addr->len, flags);
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.cc
index c48da52ffb2..66cf5704d68 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.cc
@@ -1,58 +1,58 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_POSIX_SOCKETUTILS
-
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-
-#include <fcntl.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
-#include <grpc/support/log.h>
-#include "src/core/lib/iomgr/sockaddr.h"
-
-int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock,
- int cloexec) {
- int fd, flags;
- fd = accept(sockfd, reinterpret_cast<grpc_sockaddr*>(resolved_addr->addr),
- &resolved_addr->len);
- if (fd >= 0) {
- if (nonblock) {
- flags = fcntl(fd, F_GETFL, 0);
- if (flags < 0) goto close_and_error;
- if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) goto close_and_error;
- }
- if (cloexec) {
- flags = fcntl(fd, F_GETFD, 0);
- if (flags < 0) goto close_and_error;
- if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != 0) goto close_and_error;
- }
- }
- return fd;
-
-close_and_error:
- close(fd);
- return -1;
-}
-
-#endif /* GRPC_POSIX_SOCKETUTILS */
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_POSIX_SOCKETUTILS
+
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include <grpc/support/log.h>
+#include "src/core/lib/iomgr/sockaddr.h"
+
+int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock,
+ int cloexec) {
+ int fd, flags;
+ fd = accept(sockfd, reinterpret_cast<grpc_sockaddr*>(resolved_addr->addr),
+ &resolved_addr->len);
+ if (fd >= 0) {
+ if (nonblock) {
+ flags = fcntl(fd, F_GETFL, 0);
+ if (flags < 0) goto close_and_error;
+ if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) goto close_and_error;
+ }
+ if (cloexec) {
+ flags = fcntl(fd, F_GETFD, 0);
+ if (flags < 0) goto close_and_error;
+ if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != 0) goto close_and_error;
+ }
+ }
+ return fd;
+
+close_and_error:
+ close(fd);
+ return -1;
+}
+
+#endif /* GRPC_POSIX_SOCKETUTILS */
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 b4dc909d1e0..0d202ef8bbf 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SOCKET_UTILS_POSIX_H
#define GRPC_CORE_LIB_IOMGR_SOCKET_UTILS_POSIX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/resolve_address.h"
#include <sys/socket.h>
@@ -28,7 +28,7 @@
#include <grpc/impl/codegen/grpc_types.h>
#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/socket_factory_posix.h"
+#include "src/core/lib/iomgr/socket_factory_posix.h"
#include "src/core/lib/iomgr/socket_mutator.h"
#ifdef GRPC_LINUX_ERRQUEUE
@@ -41,29 +41,29 @@
#endif /* ifdef GRPC_LINUX_ERRQUEUE */
/* a wrapper for accept or accept4 */
-int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock,
+int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock,
int cloexec);
/* set a socket to use zerocopy */
grpc_error* grpc_set_socket_zerocopy(int fd);
/* set a socket to non blocking mode */
-grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking);
+grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking);
/* set a socket to close on exec */
-grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec);
+grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec);
/* set a socket to reuse old addresses */
-grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse);
-
-/* return true if SO_REUSEPORT is supported */
-bool grpc_is_socket_reuse_port_supported();
+grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse);
+/* return true if SO_REUSEPORT is supported */
+bool grpc_is_socket_reuse_port_supported();
+
/* disable nagle */
-grpc_error* grpc_set_socket_low_latency(int fd, int low_latency);
+grpc_error* grpc_set_socket_low_latency(int fd, int low_latency);
/* set SO_REUSEPORT */
-grpc_error* grpc_set_socket_reuse_port(int fd, int reuse);
+grpc_error* grpc_set_socket_reuse_port(int fd, int reuse);
/* Configure the default values for TCP_USER_TIMEOUT */
void config_default_tcp_user_timeout(bool enable, int timeout, bool is_client);
@@ -84,24 +84,24 @@ int grpc_ipv6_loopback_available(void);
/* Tries to set SO_NOSIGPIPE if available on this platform.
If SO_NO_SIGPIPE is not available, returns 1. */
-grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd);
+grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd);
/* Tries to set IP_PKTINFO if available on this platform.
If IP_PKTINFO is not available, returns 1. */
-grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd);
+grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd);
/* Tries to set IPV6_RECVPKTINFO if available on this platform.
If IPV6_RECVPKTINFO is not available, returns 1. */
-grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd);
+grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd);
/* Tries to set the socket's send buffer to given size. */
-grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes);
+grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes);
/* Tries to set the socket's receive buffer to given size. */
-grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes);
+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);
+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,
@@ -149,15 +149,15 @@ int grpc_set_socket_dualstack(int fd);
IPv4, so that bind() or connect() see the correct family.
Also, it's important to distinguish between DUALSTACK and IPV6 when
listening on the [::] wildcard address. */
-grpc_error* grpc_create_dualstack_socket(const grpc_resolved_address* addr,
+grpc_error* grpc_create_dualstack_socket(const grpc_resolved_address* addr,
int type, int protocol,
- grpc_dualstack_mode* dsmode,
- int* newfd);
-
-/* Same as grpc_create_dualstack_socket(), but use the given socket factory (if
- non-null) to create the socket, rather than calling socket() directly. */
-grpc_error* grpc_create_dualstack_socket_using_factory(
- grpc_socket_factory* factory, const grpc_resolved_address* addr, int type,
- int protocol, grpc_dualstack_mode* dsmode, int* newfd);
-
+ grpc_dualstack_mode* dsmode,
+ int* newfd);
+
+/* Same as grpc_create_dualstack_socket(), but use the given socket factory (if
+ non-null) to create the socket, rather than calling socket() directly. */
+grpc_error* grpc_create_dualstack_socket_using_factory(
+ grpc_socket_factory* factory, const grpc_resolved_address* addr, int type,
+ int protocol, grpc_dualstack_mode* dsmode, int* newfd);
+
#endif /* GRPC_CORE_LIB_IOMGR_SOCKET_UTILS_POSIX_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc
index 96f193ddcc1..fb3f1e53459 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc
@@ -1,49 +1,49 @@
-/*
- *
- * 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"
-
-#ifdef GRPC_UV
-
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/socket_utils.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 <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_UV
+
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/socket_utils.h"
+
+#include <grpc/support/log.h>
+
#error #include <uv.h>
-
-uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); }
-
-uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); }
-
+
+uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); }
+
+uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); }
+
uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); }
uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); }
-int grpc_inet_pton(int af, const char* src, void* dst) {
- return inet_pton(af, src, dst);
-}
-
-const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) {
- uv_inet_ntop(af, src, dst, size);
- return dst;
-}
-
-#endif /* GRPC_UV */
+int grpc_inet_pton(int af, const char* src, void* dst) {
+ return inet_pton(af, src, dst);
+}
+
+const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) {
+ uv_inet_ntop(af, src, dst, size);
+ return dst;
+}
+
+#endif /* GRPC_UV */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc
index 9137ab98e60..b23023f34df 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINDOWS_SOCKETUTILS
-
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/socket_utils.h"
-
-#include <grpc/support/log.h>
-
-uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); }
-
-uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); }
-
+/*
+ *
+ * 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"
+
+#ifdef GRPC_WINDOWS_SOCKETUTILS
+
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/socket_utils.h"
+
+#include <grpc/support/log.h>
+
+uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); }
+
+uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); }
+
uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); }
uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); }
-int grpc_inet_pton(int af, const char* src, void* dst) {
- return inet_pton(af, src, dst);
-}
-
-const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) {
- /* Windows InetNtopA wants a mutable ip pointer */
- return InetNtopA(af, (void*)src, dst, size);
-}
-
-#endif /* GRPC_WINDOWS_SOCKETUTILS */
+int grpc_inet_pton(int af, const char* src, void* dst) {
+ return inet_pton(af, src, dst);
+}
+
+const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) {
+ /* Windows InetNtopA wants a mutable ip pointer */
+ return InetNtopA(af, (void*)src, dst, size);
+}
+
+#endif /* GRPC_WINDOWS_SOCKETUTILS */
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 f117653c490..d1bf6ad64ef 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
#define OPTIONAL
-#include <winsock2.h>
-
-// must be included after winsock2.h
-#include <mswsock.h>
-
+#include <winsock2.h>
+
+// must be included after winsock2.h
+#include <mswsock.h>
+
#undef OPTIONAL
#include "y_absl/strings/str_format.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/log_windows.h>
-
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/iomgr_internal.h"
-#include "src/core/lib/iomgr/pollset.h"
-#include "src/core/lib/iomgr/pollset_windows.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_windows.h>
+
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/iomgr_internal.h"
+#include "src/core/lib/iomgr/pollset.h"
+#include "src/core/lib/iomgr/pollset_windows.h"
#include "src/core/lib/iomgr/sockaddr_windows.h"
-#include "src/core/lib/iomgr/socket_windows.h"
-
+#include "src/core/lib/iomgr/socket_windows.h"
+
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));
- r->socket = socket;
- gpr_mu_init(&r->state_mu);
+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));
+ r->socket = socket;
+ gpr_mu_init(&r->state_mu);
grpc_iomgr_register_object(
&r->iomgr_object, y_absl::StrFormat("%s:socket=0x%p", name, r).c_str());
- grpc_iocp_add_socket(r);
- return r;
-}
-
+ grpc_iocp_add_socket(r);
+ return r;
+}
+
SOCKET grpc_winsocket_wrapped_socket(grpc_winsocket* socket) {
return socket->socket;
}
-/* Schedule a shutdown of the socket operations. Will call the pending
- operations to abort them. We need to do that this way because of the
- various callsites of that function, which happens to be in various
- mutex hold states, and that'd be unsafe to call them directly. */
-void grpc_winsocket_shutdown(grpc_winsocket* winsocket) {
- /* Grab the function pointer for DisconnectEx for that specific socket.
- It may change depending on the interface. */
- int status;
- GUID guid = WSAID_DISCONNECTEX;
- LPFN_DISCONNECTEX DisconnectEx;
- DWORD ioctl_num_bytes;
-
- gpr_mu_lock(&winsocket->state_mu);
- if (winsocket->shutdown_called) {
- gpr_mu_unlock(&winsocket->state_mu);
- return;
- }
- winsocket->shutdown_called = true;
- gpr_mu_unlock(&winsocket->state_mu);
-
- status = WSAIoctl(winsocket->socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
- &guid, sizeof(guid), &DisconnectEx, sizeof(DisconnectEx),
- &ioctl_num_bytes, NULL, NULL);
-
- if (status == 0) {
- DisconnectEx(winsocket->socket, NULL, 0, 0);
- } else {
- char* utf8_message = gpr_format_message(WSAGetLastError());
- gpr_log(GPR_INFO, "Unable to retrieve DisconnectEx pointer : %s",
- utf8_message);
- gpr_free(utf8_message);
- }
- closesocket(winsocket->socket);
-}
-
-static void destroy(grpc_winsocket* winsocket) {
- grpc_iomgr_unregister_object(&winsocket->iomgr_object);
- gpr_mu_destroy(&winsocket->state_mu);
- gpr_free(winsocket);
-}
-
-static bool check_destroyable(grpc_winsocket* winsocket) {
- return winsocket->destroy_called == true &&
- winsocket->write_info.closure == NULL &&
- winsocket->read_info.closure == NULL;
-}
-
-void grpc_winsocket_destroy(grpc_winsocket* winsocket) {
- gpr_mu_lock(&winsocket->state_mu);
- GPR_ASSERT(!winsocket->destroy_called);
- winsocket->destroy_called = true;
- bool should_destroy = check_destroyable(winsocket);
- gpr_mu_unlock(&winsocket->state_mu);
- if (should_destroy) destroy(winsocket);
-}
-
-/* Calling notify_on_read or write means either of two things:
--) The IOCP already completed in the background, and we need to call
-the callback now.
--) The IOCP hasn't completed yet, and we're queuing it for later. */
-static void socket_notify_on_iocp(grpc_winsocket* socket, grpc_closure* closure,
- grpc_winsocket_callback_info* info) {
- GPR_ASSERT(info->closure == NULL);
- gpr_mu_lock(&socket->state_mu);
- if (info->has_pending_iocp) {
- info->has_pending_iocp = 0;
+/* Schedule a shutdown of the socket operations. Will call the pending
+ operations to abort them. We need to do that this way because of the
+ various callsites of that function, which happens to be in various
+ mutex hold states, and that'd be unsafe to call them directly. */
+void grpc_winsocket_shutdown(grpc_winsocket* winsocket) {
+ /* Grab the function pointer for DisconnectEx for that specific socket.
+ It may change depending on the interface. */
+ int status;
+ GUID guid = WSAID_DISCONNECTEX;
+ LPFN_DISCONNECTEX DisconnectEx;
+ DWORD ioctl_num_bytes;
+
+ gpr_mu_lock(&winsocket->state_mu);
+ if (winsocket->shutdown_called) {
+ gpr_mu_unlock(&winsocket->state_mu);
+ return;
+ }
+ winsocket->shutdown_called = true;
+ gpr_mu_unlock(&winsocket->state_mu);
+
+ status = WSAIoctl(winsocket->socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
+ &guid, sizeof(guid), &DisconnectEx, sizeof(DisconnectEx),
+ &ioctl_num_bytes, NULL, NULL);
+
+ if (status == 0) {
+ DisconnectEx(winsocket->socket, NULL, 0, 0);
+ } else {
+ char* utf8_message = gpr_format_message(WSAGetLastError());
+ gpr_log(GPR_INFO, "Unable to retrieve DisconnectEx pointer : %s",
+ utf8_message);
+ gpr_free(utf8_message);
+ }
+ closesocket(winsocket->socket);
+}
+
+static void destroy(grpc_winsocket* winsocket) {
+ grpc_iomgr_unregister_object(&winsocket->iomgr_object);
+ gpr_mu_destroy(&winsocket->state_mu);
+ gpr_free(winsocket);
+}
+
+static bool check_destroyable(grpc_winsocket* winsocket) {
+ return winsocket->destroy_called == true &&
+ winsocket->write_info.closure == NULL &&
+ winsocket->read_info.closure == NULL;
+}
+
+void grpc_winsocket_destroy(grpc_winsocket* winsocket) {
+ gpr_mu_lock(&winsocket->state_mu);
+ GPR_ASSERT(!winsocket->destroy_called);
+ winsocket->destroy_called = true;
+ bool should_destroy = check_destroyable(winsocket);
+ gpr_mu_unlock(&winsocket->state_mu);
+ if (should_destroy) destroy(winsocket);
+}
+
+/* Calling notify_on_read or write means either of two things:
+-) The IOCP already completed in the background, and we need to call
+the callback now.
+-) The IOCP hasn't completed yet, and we're queuing it for later. */
+static void socket_notify_on_iocp(grpc_winsocket* socket, grpc_closure* closure,
+ grpc_winsocket_callback_info* info) {
+ GPR_ASSERT(info->closure == NULL);
+ 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);
- } else {
- info->closure = closure;
- }
- gpr_mu_unlock(&socket->state_mu);
-}
-
-void grpc_socket_notify_on_write(grpc_winsocket* socket,
- grpc_closure* closure) {
- socket_notify_on_iocp(socket, closure, &socket->write_info);
-}
-
-void grpc_socket_notify_on_read(grpc_winsocket* socket, grpc_closure* closure) {
- socket_notify_on_iocp(socket, closure, &socket->read_info);
-}
-
-void grpc_socket_become_ready(grpc_winsocket* socket,
- grpc_winsocket_callback_info* info) {
- GPR_ASSERT(!info->has_pending_iocp);
- gpr_mu_lock(&socket->state_mu);
- if (info->closure) {
+ } else {
+ info->closure = closure;
+ }
+ gpr_mu_unlock(&socket->state_mu);
+}
+
+void grpc_socket_notify_on_write(grpc_winsocket* socket,
+ grpc_closure* closure) {
+ socket_notify_on_iocp(socket, closure, &socket->write_info);
+}
+
+void grpc_socket_notify_on_read(grpc_winsocket* socket, grpc_closure* closure) {
+ socket_notify_on_iocp(socket, closure, &socket->read_info);
+}
+
+void grpc_socket_become_ready(grpc_winsocket* socket,
+ grpc_winsocket_callback_info* info) {
+ 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);
- info->closure = NULL;
- } else {
- info->has_pending_iocp = 1;
- }
- bool should_destroy = check_destroyable(socket);
- gpr_mu_unlock(&socket->state_mu);
- if (should_destroy) destroy(socket);
-}
-
+ info->closure = NULL;
+ } else {
+ info->has_pending_iocp = 1;
+ }
+ bool should_destroy = check_destroyable(socket);
+ gpr_mu_unlock(&socket->state_mu);
+ if (should_destroy) destroy(socket);
+}
+
static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT;
static bool g_ipv6_loopback_available = false;
@@ -203,4 +203,4 @@ void grpc_wsa_socket_flags_init() {
}
}
-#endif /* GRPC_WINSOCK_SOCKET */
+#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 78f79453c6c..f01ea5bae91 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -20,16 +20,16 @@
#define GRPC_CORE_LIB_IOMGR_SOCKET_WINDOWS_H
#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
#include <winsock2.h>
#include <grpc/support/atm.h>
#include <grpc/support/sync.h>
-#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#ifndef WSA_FLAG_NO_HANDLE_INHERIT
@@ -48,7 +48,7 @@ typedef struct grpc_winsocket_callback_info {
OVERLAPPED overlapped;
/* The callback information for the pending operation. May be empty if the
caller hasn't registered a callback yet. */
- grpc_closure* closure;
+ grpc_closure* closure;
/* A boolean to describe if the IO Completion Port got a notification for
that operation. This will happen if the operation completed before the
called had time to register a callback. We could avoid that behavior
@@ -94,25 +94,25 @@ typedef struct grpc_winsocket {
/* Create a wrapped windows handle. This takes ownership of it, meaning that
it will be responsible for closing it. */
-grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name);
+grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name);
SOCKET grpc_winsocket_wrapped_socket(grpc_winsocket* socket);
/* Initiate an asynchronous shutdown of the socket. Will call off any pending
operation to cancel them. */
-void grpc_winsocket_shutdown(grpc_winsocket* socket);
+void grpc_winsocket_shutdown(grpc_winsocket* socket);
/* Destroy a socket. Should only be called if there's no pending operation. */
-void grpc_winsocket_destroy(grpc_winsocket* socket);
+void grpc_winsocket_destroy(grpc_winsocket* socket);
-void grpc_socket_notify_on_write(grpc_winsocket* winsocket,
- grpc_closure* closure);
+void grpc_socket_notify_on_write(grpc_winsocket* winsocket,
+ grpc_closure* closure);
-void grpc_socket_notify_on_read(grpc_winsocket* winsocket,
- grpc_closure* closure);
+void grpc_socket_notify_on_read(grpc_winsocket* winsocket,
+ grpc_closure* closure);
-void grpc_socket_become_ready(grpc_winsocket* winsocket,
- grpc_winsocket_callback_info* ci);
+void grpc_socket_become_ready(grpc_winsocket* winsocket,
+ grpc_winsocket_callback_info* ci);
/* Returns true if this system can create AF_INET6 sockets bound to ::1.
The value is probed once, and cached for the life of the process. */
@@ -122,6 +122,6 @@ void grpc_wsa_socket_flags_init();
DWORD grpc_get_default_wsa_socket_flags();
-#endif
-
+#endif
+
#endif /* GRPC_CORE_LIB_IOMGR_SOCKET_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/sys_epoll_wrapper.h b/contrib/libs/grpc/src/core/lib/iomgr/sys_epoll_wrapper.h
index d21d853665b..a11ee925aa0 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/sys_epoll_wrapper.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/sys_epoll_wrapper.h
@@ -1,30 +1,30 @@
-/*
- *
- * 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_IOMGR_SYS_EPOLL_WRAPPER_H
-#define GRPC_CORE_LIB_IOMGR_SYS_EPOLL_WRAPPER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <sys/epoll.h>
-
-#ifndef EPOLLEXCLUSIVE
-#define EPOLLEXCLUSIVE (1 << 28)
-#endif
-
-#endif /* GRPC_CORE_LIB_IOMGR_SYS_EPOLL_WRAPPER_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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_SYS_EPOLL_WRAPPER_H
+#define GRPC_CORE_LIB_IOMGR_SYS_EPOLL_WRAPPER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <sys/epoll.h>
+
+#ifndef EPOLLEXCLUSIVE
+#define EPOLLEXCLUSIVE (1 << 28)
+#endif
+
+#endif /* GRPC_CORE_LIB_IOMGR_SYS_EPOLL_WRAPPER_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.cc
index 6c0ba40781b..d8ba703bcd5 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.cc
@@ -1,36 +1,36 @@
-/*
- *
- * 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/lib/iomgr/tcp_client.h"
-
-grpc_tcp_client_vtable* grpc_tcp_client_impl;
-
-void grpc_tcp_client_connect(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) {
- grpc_tcp_client_impl->connect(closure, ep, interested_parties, channel_args,
- addr, deadline);
-}
-
-void grpc_set_tcp_client_impl(grpc_tcp_client_vtable* impl) {
- grpc_tcp_client_impl = impl;
-}
+/*
+ *
+ * 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/lib/iomgr/tcp_client.h"
+
+grpc_tcp_client_vtable* grpc_tcp_client_impl;
+
+void grpc_tcp_client_connect(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) {
+ grpc_tcp_client_impl->connect(closure, ep, interested_parties, channel_args,
+ addr, deadline);
+}
+
+void grpc_set_tcp_client_impl(grpc_tcp_client_vtable* impl) {
+ grpc_tcp_client_impl = impl;
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.h
index d209eeb8c23..fa0457a8153 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client.h
@@ -1,52 +1,52 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TCP_CLIENT_H
#define GRPC_CORE_LIB_IOMGR_TCP_CLIENT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/time.h>
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/pollset_set.h"
#include "src/core/lib/iomgr/resolve_address.h"
-typedef struct grpc_tcp_client_vtable {
- void (*connect)(grpc_closure* on_connect, grpc_endpoint** endpoint,
- grpc_pollset_set* interested_parties,
- const grpc_channel_args* channel_args,
- const grpc_resolved_address* addr, grpc_millis deadline);
-} grpc_tcp_client_vtable;
+typedef struct grpc_tcp_client_vtable {
+ void (*connect)(grpc_closure* on_connect, grpc_endpoint** endpoint,
+ grpc_pollset_set* interested_parties,
+ const grpc_channel_args* channel_args,
+ const grpc_resolved_address* addr, grpc_millis deadline);
+} grpc_tcp_client_vtable;
/* Asynchronously connect to an address (specified as (addr, len)), and call
cb with arg and the completed connection when done (or call cb with arg and
NULL on failure).
interested_parties points to a set of pollsets that would be interested
in this connection being established (in order to continue their work) */
-void grpc_tcp_client_connect(grpc_closure* on_connect, grpc_endpoint** endpoint,
- grpc_pollset_set* interested_parties,
- const grpc_channel_args* channel_args,
- const grpc_resolved_address* addr,
- grpc_millis deadline);
-
-void grpc_tcp_client_global_init();
-
-void grpc_set_tcp_client_impl(grpc_tcp_client_vtable* impl);
-
+void grpc_tcp_client_connect(grpc_closure* on_connect, grpc_endpoint** endpoint,
+ grpc_pollset_set* interested_parties,
+ const grpc_channel_args* channel_args,
+ const grpc_resolved_address* addr,
+ grpc_millis deadline);
+
+void grpc_tcp_client_global_init();
+
+void grpc_set_tcp_client_impl(grpc_tcp_client_vtable* impl);
+
#endif /* GRPC_CORE_LIB_IOMGR_TCP_CLIENT_H */
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 dbcf62c94f5..8d92e35f171 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/iomgr/tcp_custom.h"
-#include "src/core/lib/iomgr/timer.h"
-
-extern grpc_core::TraceFlag grpc_tcp_trace;
-extern grpc_socket_vtable* grpc_custom_socket_vtable;
-
-struct grpc_custom_tcp_connect {
- grpc_custom_socket* socket;
- grpc_timer alarm;
- grpc_closure on_alarm;
- grpc_closure* closure;
- grpc_endpoint** endpoint;
- int refs;
+/*
+ *
+ * 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/lib/iomgr/port.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/iomgr/tcp_custom.h"
+#include "src/core/lib/iomgr/timer.h"
+
+extern grpc_core::TraceFlag grpc_tcp_trace;
+extern grpc_socket_vtable* grpc_custom_socket_vtable;
+
+struct grpc_custom_tcp_connect {
+ grpc_custom_socket* socket;
+ grpc_timer alarm;
+ grpc_closure on_alarm;
+ grpc_closure* closure;
+ grpc_endpoint** endpoint;
+ int refs;
TString addr_name;
- grpc_resource_quota* resource_quota;
-};
-
-static void custom_tcp_connect_cleanup(grpc_custom_tcp_connect* connect) {
- grpc_custom_socket* socket = connect->socket;
- grpc_resource_quota_unref_internal(connect->resource_quota);
+ grpc_resource_quota* resource_quota;
+};
+
+static void custom_tcp_connect_cleanup(grpc_custom_tcp_connect* connect) {
+ grpc_custom_socket* socket = connect->socket;
+ grpc_resource_quota_unref_internal(connect->resource_quota);
delete connect;
- socket->refs--;
- if (socket->refs == 0) {
- grpc_custom_socket_vtable->destroy(socket);
- gpr_free(socket);
- }
-}
-
+ socket->refs--;
+ if (socket->refs == 0) {
+ grpc_custom_socket_vtable->destroy(socket);
+ gpr_free(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;
+
+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)) {
- const char* str = grpc_error_string(error);
- gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
+ const char* str = grpc_error_string(error);
+ gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
connect->addr_name.c_str(), str);
- }
- if (error == GRPC_ERROR_NONE) {
- /* error == NONE implies that the timer ran out, and wasn't cancelled. If
- it was cancelled, then the handler that cancelled it also should close
- the handle, if applicable */
- grpc_custom_socket_vtable->close(socket, custom_close_callback);
- }
- done = (--connect->refs == 0);
- if (done) {
- custom_tcp_connect_cleanup(connect);
- }
-}
-
+ }
+ if (error == GRPC_ERROR_NONE) {
+ /* error == NONE implies that the timer ran out, and wasn't cancelled. If
+ it was cancelled, then the handler that cancelled it also should close
+ the handle, if applicable */
+ grpc_custom_socket_vtable->close(socket, custom_close_callback);
+ }
+ done = (--connect->refs == 0);
+ if (done) {
+ custom_tcp_connect_cleanup(connect);
+ }
+}
+
static void custom_connect_callback_internal(grpc_custom_socket* socket,
grpc_error* error) {
- grpc_custom_tcp_connect* connect = socket->connector;
- int done;
- grpc_closure* closure = connect->closure;
- grpc_timer_cancel(&connect->alarm);
- if (error == GRPC_ERROR_NONE) {
- *connect->endpoint = custom_tcp_endpoint_create(
+ grpc_custom_tcp_connect* connect = socket->connector;
+ int done;
+ grpc_closure* closure = connect->closure;
+ grpc_timer_cancel(&connect->alarm);
+ if (error == GRPC_ERROR_NONE) {
+ *connect->endpoint = custom_tcp_endpoint_create(
socket, connect->resource_quota, connect->addr_name.c_str());
- }
- done = (--connect->refs == 0);
- if (done) {
- grpc_core::ExecCtx::Get()->Flush();
- custom_tcp_connect_cleanup(connect);
- }
+ }
+ done = (--connect->refs == 0);
+ if (done) {
+ grpc_core::ExecCtx::Get()->Flush();
+ custom_tcp_connect_cleanup(connect);
+ }
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;
@@ -111,50 +111,50 @@ static void custom_connect_callback(grpc_custom_socket* socket,
}
}
-static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
- grpc_pollset_set* interested_parties,
- const grpc_channel_args* channel_args,
- const grpc_resolved_address* resolved_addr,
- grpc_millis deadline) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- (void)channel_args;
- (void)interested_parties;
- grpc_resource_quota* resource_quota = grpc_resource_quota_create(nullptr);
- if (channel_args != nullptr) {
- for (size_t i = 0; i < channel_args->num_args; i++) {
- if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
- grpc_resource_quota_unref_internal(resource_quota);
- resource_quota = grpc_resource_quota_ref_internal(
- (grpc_resource_quota*)channel_args->args[i].value.pointer.p);
- }
- }
- }
- grpc_custom_socket* socket =
- (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
- socket->refs = 2;
- grpc_custom_socket_vtable->init(socket, GRPC_AF_UNSPEC);
+static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
+ grpc_pollset_set* interested_parties,
+ const grpc_channel_args* channel_args,
+ const grpc_resolved_address* resolved_addr,
+ grpc_millis deadline) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ (void)channel_args;
+ (void)interested_parties;
+ grpc_resource_quota* resource_quota = grpc_resource_quota_create(nullptr);
+ if (channel_args != nullptr) {
+ for (size_t i = 0; i < channel_args->num_args; i++) {
+ if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
+ grpc_resource_quota_unref_internal(resource_quota);
+ resource_quota = grpc_resource_quota_ref_internal(
+ (grpc_resource_quota*)channel_args->args[i].value.pointer.p);
+ }
+ }
+ }
+ grpc_custom_socket* socket =
+ (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
+ socket->refs = 2;
+ grpc_custom_socket_vtable->init(socket, GRPC_AF_UNSPEC);
grpc_custom_tcp_connect* connect = new grpc_custom_tcp_connect();
- connect->closure = closure;
- connect->endpoint = ep;
- connect->addr_name = grpc_sockaddr_to_uri(resolved_addr);
- connect->resource_quota = resource_quota;
- connect->socket = socket;
- socket->connector = connect;
- socket->endpoint = nullptr;
- socket->listener = nullptr;
- connect->refs = 2;
-
+ connect->closure = closure;
+ connect->endpoint = ep;
+ connect->addr_name = grpc_sockaddr_to_uri(resolved_addr);
+ connect->resource_quota = resource_quota;
+ connect->socket = socket;
+ socket->connector = connect;
+ socket->endpoint = nullptr;
+ socket->listener = nullptr;
+ connect->refs = 2;
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "CLIENT_CONNECT: %p %s: asynchronously connecting",
+ gpr_log(GPR_INFO, "CLIENT_CONNECT: %p %s: asynchronously connecting",
socket, connect->addr_name.c_str());
- }
-
+ }
+
GRPC_CLOSURE_INIT(&connect->on_alarm, on_alarm, socket,
grpc_schedule_on_exec_ctx);
grpc_timer_init(&connect->alarm, deadline, &connect->on_alarm);
- grpc_custom_socket_vtable->connect(
- socket, (const grpc_sockaddr*)resolved_addr->addr, resolved_addr->len,
- custom_connect_callback);
-}
-
-grpc_tcp_client_vtable custom_tcp_client_vtable = {tcp_connect};
+ grpc_custom_socket_vtable->connect(
+ socket, (const grpc_sockaddr*)resolved_addr->addr, resolved_addr->len,
+ custom_connect_callback);
+}
+
+grpc_tcp_client_vtable custom_tcp_client_vtable = {tcp_connect};
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 401ddd2f683..0d2bb2e764f 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
@@ -1,351 +1,351 @@
-/*
- *
- * 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/iomgr/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/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_TCP_CLIENT
-
-#include "src/core/lib/iomgr/tcp_client_posix.h"
-
-#include <errno.h>
-#include <netinet/in.h>
-#include <string.h>
-#include <unistd.h>
-
+
+#include "src/core/lib/iomgr/tcp_client_posix.h"
+
+#include <errno.h>
+#include <netinet/in.h>
+#include <string.h>
+#include <unistd.h>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/iomgr_posix.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/socket_mutator.h"
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-#include "src/core/lib/iomgr/tcp_posix.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/iomgr_posix.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/socket_mutator.h"
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+#include "src/core/lib/iomgr/tcp_posix.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include "src/core/lib/slice/slice_internal.h"
-
-extern grpc_core::TraceFlag grpc_tcp_trace;
-
+
+extern grpc_core::TraceFlag grpc_tcp_trace;
+
struct async_connect {
- gpr_mu mu;
- grpc_fd* fd;
- grpc_timer alarm;
- grpc_closure on_alarm;
- int refs;
- grpc_closure write_closure;
- grpc_pollset_set* interested_parties;
+ gpr_mu mu;
+ grpc_fd* fd;
+ grpc_timer alarm;
+ grpc_closure on_alarm;
+ int refs;
+ grpc_closure write_closure;
+ grpc_pollset_set* interested_parties;
TString addr_str;
- grpc_endpoint** ep;
- grpc_closure* closure;
- grpc_channel_args* channel_args;
+ grpc_endpoint** ep;
+ grpc_closure* closure;
+ grpc_channel_args* channel_args;
};
-static grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd,
- const grpc_channel_args* channel_args) {
- grpc_error* err = GRPC_ERROR_NONE;
-
- GPR_ASSERT(fd >= 0);
-
- err = grpc_set_socket_nonblocking(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
- err = grpc_set_socket_cloexec(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
- if (!grpc_is_unix_socket(addr)) {
- err = grpc_set_socket_low_latency(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
+static grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd,
+ const grpc_channel_args* channel_args) {
+ grpc_error* err = GRPC_ERROR_NONE;
+
+ GPR_ASSERT(fd >= 0);
+
+ err = grpc_set_socket_nonblocking(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
+ err = grpc_set_socket_cloexec(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
+ if (!grpc_is_unix_socket(addr)) {
+ err = grpc_set_socket_low_latency(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
err = grpc_set_socket_reuse_addr(fd, 1);
if (err != GRPC_ERROR_NONE) goto error;
err = grpc_set_socket_tcp_user_timeout(fd, channel_args,
true /* is_client */);
if (err != GRPC_ERROR_NONE) goto error;
- }
- err = grpc_set_socket_no_sigpipe_if_possible(fd);
- if (err != GRPC_ERROR_NONE) goto error;
+ }
+ 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;
- goto done;
-
-error:
- if (fd >= 0) {
- close(fd);
- }
-done:
- return err;
-}
-
-static void tc_on_alarm(void* acp, grpc_error* error) {
- int done;
- async_connect* ac = static_cast<async_connect*>(acp);
+ goto done;
+
+error:
+ if (fd >= 0) {
+ close(fd);
+ }
+done:
+ return err;
+}
+
+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)) {
- const char* str = grpc_error_string(error);
+ const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
ac->addr_str.c_str(), str);
- }
- gpr_mu_lock(&ac->mu);
- if (ac->fd != nullptr) {
- grpc_fd_shutdown(
- ac->fd, GRPC_ERROR_CREATE_FROM_STATIC_STRING("connect() timed out"));
- }
- done = (--ac->refs == 0);
- gpr_mu_unlock(&ac->mu);
- if (done) {
- gpr_mu_destroy(&ac->mu);
- grpc_channel_args_destroy(ac->channel_args);
+ }
+ gpr_mu_lock(&ac->mu);
+ if (ac->fd != nullptr) {
+ grpc_fd_shutdown(
+ ac->fd, GRPC_ERROR_CREATE_FROM_STATIC_STRING("connect() timed out"));
+ }
+ done = (--ac->refs == 0);
+ gpr_mu_unlock(&ac->mu);
+ if (done) {
+ gpr_mu_destroy(&ac->mu);
+ grpc_channel_args_destroy(ac->channel_args);
delete ac;
- }
-}
-
-grpc_endpoint* grpc_tcp_client_create_from_fd(
- grpc_fd* fd, const grpc_channel_args* channel_args, const char* addr_str) {
- return grpc_tcp_create(fd, channel_args, addr_str);
-}
-
-static void on_writable(void* acp, grpc_error* error) {
- async_connect* ac = static_cast<async_connect*>(acp);
- int so_error = 0;
- socklen_t so_error_size;
- int err;
- int done;
- grpc_endpoint** ep = ac->ep;
- grpc_closure* closure = ac->closure;
- grpc_fd* fd;
-
- GRPC_ERROR_REF(error);
-
+ }
+}
+
+grpc_endpoint* grpc_tcp_client_create_from_fd(
+ grpc_fd* fd, const grpc_channel_args* channel_args, const char* addr_str) {
+ return grpc_tcp_create(fd, channel_args, addr_str);
+}
+
+static void on_writable(void* acp, grpc_error* error) {
+ async_connect* ac = static_cast<async_connect*>(acp);
+ int so_error = 0;
+ socklen_t so_error_size;
+ int err;
+ int done;
+ grpc_endpoint** ep = ac->ep;
+ grpc_closure* closure = ac->closure;
+ grpc_fd* fd;
+
+ GRPC_ERROR_REF(error);
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- const char* str = grpc_error_string(error);
+ const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_writable: error=%s",
ac->addr_str.c_str(), str);
- }
-
- gpr_mu_lock(&ac->mu);
- GPR_ASSERT(ac->fd);
- fd = ac->fd;
- ac->fd = nullptr;
- gpr_mu_unlock(&ac->mu);
-
- grpc_timer_cancel(&ac->alarm);
-
- gpr_mu_lock(&ac->mu);
- if (error != GRPC_ERROR_NONE) {
- error =
- grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,
- grpc_slice_from_static_string("Timeout occurred"));
- goto finish;
- }
-
- do {
- so_error_size = sizeof(so_error);
- err = getsockopt(grpc_fd_wrapped_fd(fd), SOL_SOCKET, SO_ERROR, &so_error,
- &so_error_size);
- } while (err < 0 && errno == EINTR);
- if (err < 0) {
- error = GRPC_OS_ERROR(errno, "getsockopt");
- goto finish;
- }
-
- switch (so_error) {
- case 0:
- grpc_pollset_set_del_fd(ac->interested_parties, fd);
+ }
+
+ gpr_mu_lock(&ac->mu);
+ GPR_ASSERT(ac->fd);
+ fd = ac->fd;
+ ac->fd = nullptr;
+ gpr_mu_unlock(&ac->mu);
+
+ grpc_timer_cancel(&ac->alarm);
+
+ gpr_mu_lock(&ac->mu);
+ if (error != GRPC_ERROR_NONE) {
+ error =
+ grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,
+ grpc_slice_from_static_string("Timeout occurred"));
+ goto finish;
+ }
+
+ do {
+ so_error_size = sizeof(so_error);
+ err = getsockopt(grpc_fd_wrapped_fd(fd), SOL_SOCKET, SO_ERROR, &so_error,
+ &so_error_size);
+ } while (err < 0 && errno == EINTR);
+ if (err < 0) {
+ error = GRPC_OS_ERROR(errno, "getsockopt");
+ goto finish;
+ }
+
+ switch (so_error) {
+ case 0:
+ grpc_pollset_set_del_fd(ac->interested_parties, fd);
*ep = grpc_tcp_client_create_from_fd(fd, ac->channel_args,
ac->addr_str.c_str());
- fd = nullptr;
- break;
- case ENOBUFS:
- /* We will get one of these errors if we have run out of
- memory in the kernel for the data structures allocated
- when you connect a socket. If this happens it is very
- likely that if we wait a little bit then try again the
- connection will work (since other programs or this
- program will close their network connections and free up
- memory). This does _not_ indicate that there is anything
- wrong with the server we are connecting to, this is a
- local problem.
-
- If you are looking at this code, then chances are that
- your program or another program on the same computer
- opened too many network connections. The "easy" fix:
- don't do that! */
- gpr_log(GPR_ERROR, "kernel out of buffers");
- gpr_mu_unlock(&ac->mu);
- grpc_fd_notify_on_write(fd, &ac->write_closure);
- return;
- case ECONNREFUSED:
- /* This error shouldn't happen for anything other than connect(). */
- error = GRPC_OS_ERROR(so_error, "connect");
- break;
- default:
- /* We don't really know which syscall triggered the problem here,
- so punt by reporting getsockopt(). */
- error = GRPC_OS_ERROR(so_error, "getsockopt(SO_ERROR)");
- break;
- }
-
-finish:
- if (fd != nullptr) {
- grpc_pollset_set_del_fd(ac->interested_parties, fd);
+ fd = nullptr;
+ break;
+ case ENOBUFS:
+ /* We will get one of these errors if we have run out of
+ memory in the kernel for the data structures allocated
+ when you connect a socket. If this happens it is very
+ likely that if we wait a little bit then try again the
+ connection will work (since other programs or this
+ program will close their network connections and free up
+ memory). This does _not_ indicate that there is anything
+ wrong with the server we are connecting to, this is a
+ local problem.
+
+ If you are looking at this code, then chances are that
+ your program or another program on the same computer
+ opened too many network connections. The "easy" fix:
+ don't do that! */
+ gpr_log(GPR_ERROR, "kernel out of buffers");
+ gpr_mu_unlock(&ac->mu);
+ grpc_fd_notify_on_write(fd, &ac->write_closure);
+ return;
+ case ECONNREFUSED:
+ /* This error shouldn't happen for anything other than connect(). */
+ error = GRPC_OS_ERROR(so_error, "connect");
+ break;
+ default:
+ /* We don't really know which syscall triggered the problem here,
+ so punt by reporting getsockopt(). */
+ error = GRPC_OS_ERROR(so_error, "getsockopt(SO_ERROR)");
+ break;
+ }
+
+finish:
+ if (fd != nullptr) {
+ grpc_pollset_set_del_fd(ac->interested_parties, fd);
grpc_fd_orphan(fd, nullptr, nullptr, "tcp_client_orphan");
- fd = nullptr;
- }
- done = (--ac->refs == 0);
- // Create a copy of the data from "ac" to be accessed after the unlock, as
- // "ac" and its contents may be deallocated by the time they are read.
+ fd = nullptr;
+ }
+ done = (--ac->refs == 0);
+ // Create a copy of the data from "ac" to be accessed after the unlock, as
+ // "ac" and its contents may be deallocated by the time they are read.
const grpc_slice addr_str_slice = grpc_slice_from_cpp_string(ac->addr_str);
- gpr_mu_unlock(&ac->mu);
- if (error != GRPC_ERROR_NONE) {
- grpc_slice str;
- bool ret = grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &str);
- GPR_ASSERT(ret);
+ gpr_mu_unlock(&ac->mu);
+ if (error != GRPC_ERROR_NONE) {
+ grpc_slice str;
+ bool ret = grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &str);
+ GPR_ASSERT(ret);
TString description = y_absl::StrCat("Failed to connect to remote host: ",
grpc_core::StringViewFromSlice(str));
error =
grpc_error_set_str(error, GRPC_ERROR_STR_DESCRIPTION,
grpc_slice_from_cpp_string(std::move(description)));
- error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,
- addr_str_slice /* takes ownership */);
- } else {
+ error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,
+ addr_str_slice /* takes ownership */);
+ } else {
grpc_slice_unref_internal(addr_str_slice);
- }
- if (done) {
- // This is safe even outside the lock, because "done", the sentinel, is
- // populated *inside* the lock.
- gpr_mu_destroy(&ac->mu);
- grpc_channel_args_destroy(ac->channel_args);
+ }
+ if (done) {
+ // This is safe even outside the lock, because "done", the sentinel, is
+ // populated *inside* the lock.
+ gpr_mu_destroy(&ac->mu);
+ grpc_channel_args_destroy(ac->channel_args);
delete ac;
- }
+ }
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
-}
-
-grpc_error* grpc_tcp_client_prepare_fd(const grpc_channel_args* channel_args,
- const grpc_resolved_address* addr,
- grpc_resolved_address* mapped_addr,
+}
+
+grpc_error* grpc_tcp_client_prepare_fd(const grpc_channel_args* channel_args,
+ const grpc_resolved_address* addr,
+ grpc_resolved_address* mapped_addr,
int* fd) {
- grpc_dualstack_mode dsmode;
- grpc_error* error;
+ grpc_dualstack_mode dsmode;
+ grpc_error* error;
*fd = -1;
- /* Use dualstack sockets where available. Set mapped to v6 or v4 mapped to
- v6. */
- if (!grpc_sockaddr_to_v4mapped(addr, mapped_addr)) {
- /* addr is v4 mapped to v6 or v6. */
- memcpy(mapped_addr, addr, sizeof(*mapped_addr));
- }
- error =
+ /* Use dualstack sockets where available. Set mapped to v6 or v4 mapped to
+ v6. */
+ if (!grpc_sockaddr_to_v4mapped(addr, mapped_addr)) {
+ /* addr is v4 mapped to v6 or v6. */
+ memcpy(mapped_addr, addr, sizeof(*mapped_addr));
+ }
+ error =
grpc_create_dualstack_socket(mapped_addr, SOCK_STREAM, 0, &dsmode, fd);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
- if (dsmode == GRPC_DSMODE_IPV4) {
- /* Original addr is either v4 or v4 mapped to v6. Set mapped_addr to v4. */
- if (!grpc_sockaddr_is_v4mapped(addr, mapped_addr)) {
- memcpy(mapped_addr, addr, sizeof(*mapped_addr));
- }
- }
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+ if (dsmode == GRPC_DSMODE_IPV4) {
+ /* Original addr is either v4 or v4 mapped to v6. Set mapped_addr to v4. */
+ if (!grpc_sockaddr_is_v4mapped(addr, mapped_addr)) {
+ memcpy(mapped_addr, addr, sizeof(*mapped_addr));
+ }
+ }
if ((error = prepare_socket(mapped_addr, *fd, channel_args)) !=
- GRPC_ERROR_NONE) {
- return error;
- }
- return GRPC_ERROR_NONE;
-}
-
-void grpc_tcp_client_create_from_prepared_fd(
+ GRPC_ERROR_NONE) {
+ return error;
+ }
+ return GRPC_ERROR_NONE;
+}
+
+void grpc_tcp_client_create_from_prepared_fd(
grpc_pollset_set* interested_parties, grpc_closure* closure, const int fd,
- const grpc_channel_args* channel_args, const grpc_resolved_address* addr,
- grpc_millis deadline, grpc_endpoint** ep) {
- int err;
- do {
- err = connect(fd, reinterpret_cast<const grpc_sockaddr*>(addr->addr),
- addr->len);
- } while (err < 0 && errno == EINTR);
+ const grpc_channel_args* channel_args, const grpc_resolved_address* addr,
+ grpc_millis deadline, grpc_endpoint** ep) {
+ int err;
+ do {
+ err = connect(fd, reinterpret_cast<const grpc_sockaddr*>(addr->addr),
+ addr->len);
+ } while (err < 0 && errno == EINTR);
TString name = y_absl::StrCat("tcp-client:", grpc_sockaddr_to_uri(addr));
grpc_fd* fdobj = grpc_fd_create(fd, name.c_str(), true);
- if (err >= 0) {
+ 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);
- return;
- }
- if (errno != EWOULDBLOCK && errno != EINPROGRESS) {
+ return;
+ }
+ if (errno != EWOULDBLOCK && errno != EINPROGRESS) {
grpc_error* error = GRPC_OS_ERROR(errno, "connect");
error = grpc_error_set_str(
error, GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_cpp_string(grpc_sockaddr_to_uri(addr)));
grpc_fd_orphan(fdobj, nullptr, nullptr, "tcp_client_connect_error");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
- return;
- }
-
- grpc_pollset_set_add_fd(interested_parties, fdobj);
-
+ return;
+ }
+
+ grpc_pollset_set_add_fd(interested_parties, fdobj);
+
async_connect* ac = new async_connect();
- ac->closure = closure;
- ac->ep = ep;
- ac->fd = fdobj;
- ac->interested_parties = interested_parties;
- ac->addr_str = grpc_sockaddr_to_uri(addr);
- gpr_mu_init(&ac->mu);
- ac->refs = 2;
- GRPC_CLOSURE_INIT(&ac->write_closure, on_writable, ac,
- grpc_schedule_on_exec_ctx);
- ac->channel_args = grpc_channel_args_copy(channel_args);
-
+ ac->closure = closure;
+ ac->ep = ep;
+ ac->fd = fdobj;
+ ac->interested_parties = interested_parties;
+ ac->addr_str = grpc_sockaddr_to_uri(addr);
+ gpr_mu_init(&ac->mu);
+ ac->refs = 2;
+ GRPC_CLOSURE_INIT(&ac->write_closure, on_writable, ac,
+ grpc_schedule_on_exec_ctx);
+ ac->channel_args = grpc_channel_args_copy(channel_args);
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: asynchronously connecting fd %p",
+ gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: asynchronously connecting fd %p",
ac->addr_str.c_str(), fdobj);
- }
-
- gpr_mu_lock(&ac->mu);
- GRPC_CLOSURE_INIT(&ac->on_alarm, tc_on_alarm, ac, grpc_schedule_on_exec_ctx);
- grpc_timer_init(&ac->alarm, deadline, &ac->on_alarm);
- grpc_fd_notify_on_write(ac->fd, &ac->write_closure);
- gpr_mu_unlock(&ac->mu);
-}
-
-static void tcp_connect(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) {
- grpc_resolved_address mapped_addr;
+ }
+
+ gpr_mu_lock(&ac->mu);
+ GRPC_CLOSURE_INIT(&ac->on_alarm, tc_on_alarm, ac, grpc_schedule_on_exec_ctx);
+ grpc_timer_init(&ac->alarm, deadline, &ac->on_alarm);
+ grpc_fd_notify_on_write(ac->fd, &ac->write_closure);
+ gpr_mu_unlock(&ac->mu);
+}
+
+static void tcp_connect(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) {
+ grpc_resolved_address mapped_addr;
int fd = -1;
- grpc_error* error;
- *ep = nullptr;
- if ((error = grpc_tcp_client_prepare_fd(channel_args, addr, &mapped_addr,
+ grpc_error* error;
+ *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);
- return;
- }
+ return;
+ }
grpc_tcp_client_create_from_prepared_fd(interested_parties, closure, fd,
- channel_args, &mapped_addr, deadline,
- ep);
-}
-
-grpc_tcp_client_vtable grpc_posix_tcp_client_vtable = {tcp_connect};
-#endif
+ channel_args, &mapped_addr, deadline,
+ ep);
+}
+
+grpc_tcp_client_vtable grpc_posix_tcp_client_vtable = {tcp_connect};
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.h
index 6f61866fc4f..1e3ff806e98 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.h
@@ -1,68 +1,68 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TCP_CLIENT_POSIX_H
#define GRPC_CORE_LIB_IOMGR_TCP_CLIENT_POSIX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/ev_posix.h"
#include "src/core/lib/iomgr/tcp_client.h"
-/* Create an endpoint from a connected grpc_fd.
-
- fd: a connected FD. Ownership is taken.
- channel_args: may contain custom settings for the endpoint
- addr_str: destination address in printable format
- Returns: a new endpoint
-*/
-grpc_endpoint* grpc_tcp_client_create_from_fd(
- grpc_fd* fd, const grpc_channel_args* channel_args, const char* addr_str);
+/* Create an endpoint from a connected grpc_fd.
+ fd: a connected FD. Ownership is taken.
+ channel_args: may contain custom settings for the endpoint
+ addr_str: destination address in printable format
+ Returns: a new endpoint
+*/
+grpc_endpoint* grpc_tcp_client_create_from_fd(
+ grpc_fd* fd, const grpc_channel_args* channel_args, const char* addr_str);
+
/* Return a configured, unbound, unconnected TCP client fd.
-
- channel_args: may contain custom settings for the fd
- addr: the destination address
- mapped_addr: out parameter. addr mapped to an address appropriate to the
- type of socket FD created. For example, if addr is IPv4 and dual stack
- sockets are available, mapped_addr will be an IPv4-mapped IPv6 address
+
+ channel_args: may contain custom settings for the fd
+ addr: the destination address
+ mapped_addr: out parameter. addr mapped to an address appropriate to the
+ type of socket FD created. For example, if addr is IPv4 and dual stack
+ sockets are available, mapped_addr will be an IPv4-mapped IPv6 address
fd: out parameter. The new FD
- Returns: error, if any. Out parameters are not set on error
-*/
-grpc_error* grpc_tcp_client_prepare_fd(const grpc_channel_args* channel_args,
- const grpc_resolved_address* addr,
- grpc_resolved_address* mapped_addr,
+ Returns: error, if any. Out parameters are not set on error
+*/
+grpc_error* grpc_tcp_client_prepare_fd(const grpc_channel_args* channel_args,
+ const grpc_resolved_address* addr,
+ grpc_resolved_address* mapped_addr,
int* fd);
-
+
/* Connect a configured TCP client fd.
-
- interested_parties: a set of pollsets that would be interested in this
- connection being established (in order to continue their work
- closure: called when complete. On success, *ep will be set.
+
+ interested_parties: a set of pollsets that would be interested in this
+ connection being established (in order to continue their work
+ closure: called when complete. On success, *ep will be set.
fd: an FD returned from grpc_tcp_client_prepare_fd().
- channel_args: may contain custom settings for the endpoint
- deadline: connection deadline
- ep: out parameter. Set before closure is called if successful
-*/
-void grpc_tcp_client_create_from_prepared_fd(
+ channel_args: may contain custom settings for the endpoint
+ deadline: connection deadline
+ ep: out parameter. Set before closure is called if successful
+*/
+void grpc_tcp_client_create_from_prepared_fd(
grpc_pollset_set* interested_parties, grpc_closure* closure, const int fd,
- const grpc_channel_args* channel_args, const grpc_resolved_address* addr,
- grpc_millis deadline, grpc_endpoint** ep);
-
+ const grpc_channel_args* channel_args, const grpc_resolved_address* addr,
+ grpc_millis deadline, grpc_endpoint** ep);
+
#endif /* GRPC_CORE_LIB_IOMGR_TCP_CLIENT_POSIX_H */
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 a57e7539f2a..22c6c3abaa2 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
@@ -1,232 +1,232 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#include <inttypes.h>
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include "src/core/lib/iomgr/sockaddr_windows.h"
-
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/log_windows.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/socket_windows.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/iomgr/tcp_windows.h"
-#include "src/core/lib/iomgr/timer.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/iomgr/port.h"
+
+#include <inttypes.h>
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/iomgr/sockaddr_windows.h"
+
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_windows.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/socket_windows.h"
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/iomgr/tcp_windows.h"
+#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/slice/slice_internal.h"
-
+
struct async_connect {
- grpc_closure* on_done;
- gpr_mu mu;
- grpc_winsocket* socket;
- grpc_timer alarm;
- grpc_closure on_alarm;
+ grpc_closure* on_done;
+ gpr_mu mu;
+ grpc_winsocket* socket;
+ grpc_timer alarm;
+ grpc_closure on_alarm;
TString addr_name;
- int refs;
- grpc_closure on_connect;
- grpc_endpoint** endpoint;
- grpc_channel_args* channel_args;
+ int refs;
+ grpc_closure on_connect;
+ grpc_endpoint** endpoint;
+ grpc_channel_args* channel_args;
};
-static void async_connect_unlock_and_cleanup(async_connect* ac,
- grpc_winsocket* socket) {
- int done = (--ac->refs == 0);
- gpr_mu_unlock(&ac->mu);
- if (done) {
- grpc_channel_args_destroy(ac->channel_args);
- gpr_mu_destroy(&ac->mu);
+static void async_connect_unlock_and_cleanup(async_connect* ac,
+ grpc_winsocket* socket) {
+ int done = (--ac->refs == 0);
+ gpr_mu_unlock(&ac->mu);
+ if (done) {
+ grpc_channel_args_destroy(ac->channel_args);
+ gpr_mu_destroy(&ac->mu);
delete ac;
- }
- if (socket != NULL) grpc_winsocket_destroy(socket);
-}
-
-static void on_alarm(void* acp, grpc_error* error) {
- async_connect* ac = (async_connect*)acp;
- gpr_mu_lock(&ac->mu);
- grpc_winsocket* socket = ac->socket;
- ac->socket = NULL;
- if (socket != NULL) {
- grpc_winsocket_shutdown(socket);
- }
- async_connect_unlock_and_cleanup(ac, socket);
-}
-
-static void on_connect(void* acp, grpc_error* error) {
- async_connect* ac = (async_connect*)acp;
- grpc_endpoint** ep = ac->endpoint;
- GPR_ASSERT(*ep == NULL);
- grpc_closure* on_done = ac->on_done;
-
- GRPC_ERROR_REF(error);
-
- gpr_mu_lock(&ac->mu);
- grpc_winsocket* socket = ac->socket;
- ac->socket = NULL;
- gpr_mu_unlock(&ac->mu);
-
- grpc_timer_cancel(&ac->alarm);
-
- gpr_mu_lock(&ac->mu);
-
- if (error == GRPC_ERROR_NONE) {
- if (socket != NULL) {
- DWORD transfered_bytes = 0;
- DWORD flags;
- BOOL wsa_success =
- WSAGetOverlappedResult(socket->socket, &socket->write_info.overlapped,
- &transfered_bytes, FALSE, &flags);
- GPR_ASSERT(transfered_bytes == 0);
- if (!wsa_success) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "ConnectEx");
- closesocket(socket->socket);
- } else {
+ }
+ if (socket != NULL) grpc_winsocket_destroy(socket);
+}
+
+static void on_alarm(void* acp, grpc_error* error) {
+ async_connect* ac = (async_connect*)acp;
+ gpr_mu_lock(&ac->mu);
+ grpc_winsocket* socket = ac->socket;
+ ac->socket = NULL;
+ if (socket != NULL) {
+ grpc_winsocket_shutdown(socket);
+ }
+ async_connect_unlock_and_cleanup(ac, socket);
+}
+
+static void on_connect(void* acp, grpc_error* error) {
+ async_connect* ac = (async_connect*)acp;
+ grpc_endpoint** ep = ac->endpoint;
+ GPR_ASSERT(*ep == NULL);
+ grpc_closure* on_done = ac->on_done;
+
+ GRPC_ERROR_REF(error);
+
+ gpr_mu_lock(&ac->mu);
+ grpc_winsocket* socket = ac->socket;
+ ac->socket = NULL;
+ gpr_mu_unlock(&ac->mu);
+
+ grpc_timer_cancel(&ac->alarm);
+
+ gpr_mu_lock(&ac->mu);
+
+ if (error == GRPC_ERROR_NONE) {
+ if (socket != NULL) {
+ DWORD transfered_bytes = 0;
+ DWORD flags;
+ BOOL wsa_success =
+ WSAGetOverlappedResult(socket->socket, &socket->write_info.overlapped,
+ &transfered_bytes, FALSE, &flags);
+ GPR_ASSERT(transfered_bytes == 0);
+ if (!wsa_success) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "ConnectEx");
+ closesocket(socket->socket);
+ } else {
*ep = grpc_tcp_create(socket, ac->channel_args, ac->addr_name.c_str());
- socket = NULL;
- }
- } else {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("socket is null");
- }
- }
-
- async_connect_unlock_and_cleanup(ac, socket);
- /* If the connection was aborted, the callback was already called when
- the deadline was met. */
+ socket = NULL;
+ }
+ } else {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("socket is null");
+ }
+ }
+
+ 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);
-}
-
-/* Tries to issue one async connection, then schedules both an IOCP
- notification request for the connection, and one timeout alert. */
-static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
- grpc_pollset_set* interested_parties,
- const grpc_channel_args* channel_args,
- const grpc_resolved_address* addr,
- grpc_millis deadline) {
- SOCKET sock = INVALID_SOCKET;
- BOOL success;
- int status;
- grpc_resolved_address addr6_v4mapped;
- grpc_resolved_address local_address;
- grpc_winsocket* socket = NULL;
- LPFN_CONNECTEX ConnectEx;
- GUID guid = WSAID_CONNECTEX;
- DWORD ioctl_num_bytes;
- grpc_winsocket_callback_info* info;
- grpc_error* error = GRPC_ERROR_NONE;
+}
+
+/* Tries to issue one async connection, then schedules both an IOCP
+ notification request for the connection, and one timeout alert. */
+static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
+ grpc_pollset_set* interested_parties,
+ const grpc_channel_args* channel_args,
+ const grpc_resolved_address* addr,
+ grpc_millis deadline) {
+ SOCKET sock = INVALID_SOCKET;
+ BOOL success;
+ int status;
+ grpc_resolved_address addr6_v4mapped;
+ grpc_resolved_address local_address;
+ grpc_winsocket* socket = NULL;
+ LPFN_CONNECTEX ConnectEx;
+ GUID guid = WSAID_CONNECTEX;
+ DWORD ioctl_num_bytes;
+ grpc_winsocket_callback_info* info;
+ grpc_error* error = GRPC_ERROR_NONE;
async_connect* ac = NULL;
-
- *endpoint = NULL;
-
- /* Use dualstack sockets where available. */
- if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
- addr = &addr6_v4mapped;
- }
-
- sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
+
+ *endpoint = NULL;
+
+ /* Use dualstack sockets where available. */
+ if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
+ addr = &addr6_v4mapped;
+ }
+
+ sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
grpc_get_default_wsa_socket_flags());
- if (sock == INVALID_SOCKET) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
- goto failure;
- }
-
- error = grpc_tcp_prepare_socket(sock);
- if (error != GRPC_ERROR_NONE) {
- goto failure;
- }
-
- /* Grab the function pointer for ConnectEx for that specific socket.
- It may change depending on the interface. */
- status =
- WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
- &ConnectEx, sizeof(ConnectEx), &ioctl_num_bytes, NULL, NULL);
-
- if (status != 0) {
- error = GRPC_WSA_ERROR(WSAGetLastError(),
- "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER)");
- goto failure;
- }
-
- grpc_sockaddr_make_wildcard6(0, &local_address);
-
- status =
- bind(sock, (grpc_sockaddr*)&local_address.addr, (int)local_address.len);
- if (status != 0) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "bind");
- goto failure;
- }
-
- socket = grpc_winsocket_create(sock, "client");
- info = &socket->write_info;
- success = ConnectEx(sock, (grpc_sockaddr*)&addr->addr, (int)addr->len, NULL,
- 0, NULL, &info->overlapped);
-
- /* It wouldn't be unusual to get a success immediately. But we'll still get
- an IOCP notification, so let's ignore it. */
- if (!success) {
- int last_error = WSAGetLastError();
- if (last_error != ERROR_IO_PENDING) {
- error = GRPC_WSA_ERROR(last_error, "ConnectEx");
- goto failure;
- }
- }
-
+ if (sock == INVALID_SOCKET) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
+ goto failure;
+ }
+
+ error = grpc_tcp_prepare_socket(sock);
+ if (error != GRPC_ERROR_NONE) {
+ goto failure;
+ }
+
+ /* Grab the function pointer for ConnectEx for that specific socket.
+ It may change depending on the interface. */
+ status =
+ WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
+ &ConnectEx, sizeof(ConnectEx), &ioctl_num_bytes, NULL, NULL);
+
+ if (status != 0) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(),
+ "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER)");
+ goto failure;
+ }
+
+ grpc_sockaddr_make_wildcard6(0, &local_address);
+
+ status =
+ bind(sock, (grpc_sockaddr*)&local_address.addr, (int)local_address.len);
+ if (status != 0) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "bind");
+ goto failure;
+ }
+
+ socket = grpc_winsocket_create(sock, "client");
+ info = &socket->write_info;
+ success = ConnectEx(sock, (grpc_sockaddr*)&addr->addr, (int)addr->len, NULL,
+ 0, NULL, &info->overlapped);
+
+ /* It wouldn't be unusual to get a success immediately. But we'll still get
+ an IOCP notification, so let's ignore it. */
+ if (!success) {
+ int last_error = WSAGetLastError();
+ if (last_error != ERROR_IO_PENDING) {
+ error = GRPC_WSA_ERROR(last_error, "ConnectEx");
+ goto failure;
+ }
+ }
+
ac = new async_connect();
- ac->on_done = on_done;
- ac->socket = socket;
- gpr_mu_init(&ac->mu);
- ac->refs = 2;
- ac->addr_name = grpc_sockaddr_to_uri(addr);
- ac->endpoint = endpoint;
- ac->channel_args = grpc_channel_args_copy(channel_args);
- GRPC_CLOSURE_INIT(&ac->on_connect, on_connect, ac, grpc_schedule_on_exec_ctx);
-
- GRPC_CLOSURE_INIT(&ac->on_alarm, on_alarm, ac, grpc_schedule_on_exec_ctx);
- grpc_timer_init(&ac->alarm, deadline, &ac->on_alarm);
- grpc_socket_notify_on_write(socket, &ac->on_connect);
- return;
-
-failure:
- GPR_ASSERT(error != GRPC_ERROR_NONE);
+ ac->on_done = on_done;
+ ac->socket = socket;
+ gpr_mu_init(&ac->mu);
+ ac->refs = 2;
+ ac->addr_name = grpc_sockaddr_to_uri(addr);
+ ac->endpoint = endpoint;
+ ac->channel_args = grpc_channel_args_copy(channel_args);
+ GRPC_CLOSURE_INIT(&ac->on_connect, on_connect, ac, grpc_schedule_on_exec_ctx);
+
+ GRPC_CLOSURE_INIT(&ac->on_alarm, on_alarm, ac, grpc_schedule_on_exec_ctx);
+ grpc_timer_init(&ac->alarm, deadline, &ac->on_alarm);
+ grpc_socket_notify_on_write(socket, &ac->on_connect);
+ return;
+
+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_slice_from_cpp_string(std::move(target_uri)));
- GRPC_ERROR_UNREF(error);
- if (socket != NULL) {
- grpc_winsocket_destroy(socket);
- } else if (sock != INVALID_SOCKET) {
- closesocket(sock);
- }
+ GRPC_ERROR_UNREF(error);
+ if (socket != NULL) {
+ grpc_winsocket_destroy(socket);
+ } else if (sock != INVALID_SOCKET) {
+ closesocket(sock);
+ }
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, final_error);
-}
-
-grpc_tcp_client_vtable grpc_windows_tcp_client_vtable = {tcp_connect};
-
-#endif /* GRPC_WINSOCK_SOCKET */
+}
+
+grpc_tcp_client_vtable grpc_windows_tcp_client_vtable = {tcp_connect};
+
+#endif /* GRPC_WINSOCK_SOCKET */
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 3e562da508d..8726ea896ca 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc
@@ -1,371 +1,371 @@
-/*
- *
- * 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/lib/iomgr/port.h"
-
-#include <limits.h>
-#include <string.h>
-
-#include <grpc/slice_buffer.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/resource_quota.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 "src/core/lib/iomgr/port.h"
+
+#include <limits.h>
+#include <string.h>
+
+#include <grpc/slice_buffer.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/resource_quota.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/iomgr/tcp_custom.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-
-#define GRPC_TCP_DEFAULT_READ_SLICE_SIZE 8192
-
-extern grpc_core::TraceFlag grpc_tcp_trace;
-
-grpc_socket_vtable* grpc_custom_socket_vtable = nullptr;
-extern grpc_tcp_server_vtable custom_tcp_server_vtable;
-extern grpc_tcp_client_vtable custom_tcp_client_vtable;
-
-void grpc_custom_endpoint_init(grpc_socket_vtable* impl) {
- grpc_custom_socket_vtable = impl;
- grpc_set_tcp_client_impl(&custom_tcp_client_vtable);
- grpc_set_tcp_server_impl(&custom_tcp_server_vtable);
-}
-
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/iomgr/tcp_custom.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+
+#define GRPC_TCP_DEFAULT_READ_SLICE_SIZE 8192
+
+extern grpc_core::TraceFlag grpc_tcp_trace;
+
+grpc_socket_vtable* grpc_custom_socket_vtable = nullptr;
+extern grpc_tcp_server_vtable custom_tcp_server_vtable;
+extern grpc_tcp_client_vtable custom_tcp_client_vtable;
+
+void grpc_custom_endpoint_init(grpc_socket_vtable* impl) {
+ grpc_custom_socket_vtable = impl;
+ grpc_set_tcp_client_impl(&custom_tcp_client_vtable);
+ grpc_set_tcp_server_impl(&custom_tcp_server_vtable);
+}
+
struct custom_tcp_endpoint {
- grpc_endpoint base;
- gpr_refcount refcount;
- grpc_custom_socket* socket;
-
+ grpc_endpoint base;
+ gpr_refcount refcount;
+ grpc_custom_socket* socket;
+
grpc_closure* read_cb = nullptr;
grpc_closure* write_cb = nullptr;
-
+
grpc_slice_buffer* read_slices = nullptr;
grpc_slice_buffer* write_slices = nullptr;
-
- grpc_resource_user* resource_user;
- grpc_resource_user_slice_allocator slice_allocator;
-
- bool shutting_down;
-
+
+ grpc_resource_user* resource_user;
+ grpc_resource_user_slice_allocator slice_allocator;
+
+ bool shutting_down;
+
TString peer_string;
TString local_address;
};
-static void tcp_free(grpc_custom_socket* s) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)s->endpoint;
- grpc_resource_user_unref(tcp->resource_user);
+static void tcp_free(grpc_custom_socket* s) {
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)s->endpoint;
+ grpc_resource_user_unref(tcp->resource_user);
delete tcp;
- s->refs--;
- if (s->refs == 0) {
- grpc_custom_socket_vtable->destroy(s);
- gpr_free(s);
- }
-}
-
-#ifndef NDEBUG
-#define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), __FILE__, __LINE__)
-#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) {
+ s->refs--;
+ if (s->refs == 0) {
+ grpc_custom_socket_vtable->destroy(s);
+ gpr_free(s);
+ }
+}
+
+#ifndef NDEBUG
+#define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), __FILE__, __LINE__)
+#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)) {
- 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,
- val, val - 1);
- }
- if (gpr_unref(&tcp->refcount)) {
- tcp_free(tcp->socket);
- }
-}
-
-static void tcp_ref(custom_tcp_endpoint* tcp, const char* reason,
- const char* file, int line) {
+ 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,
+ val, val - 1);
+ }
+ if (gpr_unref(&tcp->refcount)) {
+ tcp_free(tcp->socket);
+ }
+}
+
+static void tcp_ref(custom_tcp_endpoint* tcp, const char* reason,
+ const char* file, int line) {
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,
- val, val + 1);
- }
- gpr_ref(&tcp->refcount);
-}
-#else
-#define TCP_UNREF(tcp, reason) tcp_unref((tcp))
-#define TCP_REF(tcp, reason) tcp_ref((tcp))
-static void tcp_unref(custom_tcp_endpoint* tcp) {
- if (gpr_unref(&tcp->refcount)) {
- tcp_free(tcp->socket);
- }
-}
-
-static void tcp_ref(custom_tcp_endpoint* tcp) { gpr_ref(&tcp->refcount); }
-#endif
-
-static void call_read_cb(custom_tcp_endpoint* tcp, grpc_error* error) {
- grpc_closure* cb = tcp->read_cb;
+ 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,
+ val, val + 1);
+ }
+ gpr_ref(&tcp->refcount);
+}
+#else
+#define TCP_UNREF(tcp, reason) tcp_unref((tcp))
+#define TCP_REF(tcp, reason) tcp_ref((tcp))
+static void tcp_unref(custom_tcp_endpoint* tcp) {
+ if (gpr_unref(&tcp->refcount)) {
+ tcp_free(tcp->socket);
+ }
+}
+
+static void tcp_ref(custom_tcp_endpoint* tcp) { gpr_ref(&tcp->refcount); }
+#endif
+
+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)) {
- gpr_log(GPR_INFO, "TCP:%p call_cb %p %p:%p", tcp->socket, cb, cb->cb,
- cb->cb_arg);
- size_t i;
- const char* str = grpc_error_string(error);
- gpr_log(GPR_INFO, "read: error=%s", str);
-
- for (i = 0; i < tcp->read_slices->count; i++) {
- char* dump = grpc_dump_slice(tcp->read_slices->slices[i],
- GPR_DUMP_HEX | GPR_DUMP_ASCII);
+ gpr_log(GPR_INFO, "TCP:%p call_cb %p %p:%p", tcp->socket, cb, cb->cb,
+ cb->cb_arg);
+ size_t i;
+ const char* str = grpc_error_string(error);
+ gpr_log(GPR_INFO, "read: error=%s", str);
+
+ for (i = 0; i < tcp->read_slices->count; i++) {
+ char* dump = grpc_dump_slice(tcp->read_slices->slices[i],
+ GPR_DUMP_HEX | GPR_DUMP_ASCII);
gpr_log(GPR_INFO, "READ %p (peer=%s): %s", tcp, tcp->peer_string.c_str(),
dump);
- gpr_free(dump);
- }
- }
- TCP_UNREF(tcp, "read");
- tcp->read_slices = nullptr;
- tcp->read_cb = nullptr;
+ gpr_free(dump);
+ }
+ }
+ TCP_UNREF(tcp, "read");
+ tcp->read_slices = nullptr;
+ tcp->read_cb = nullptr;
grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
-}
-
-static void custom_read_callback(grpc_custom_socket* socket, size_t nread,
- grpc_error* error) {
+}
+
+static void custom_read_callback(grpc_custom_socket* socket, size_t nread,
+ grpc_error* error) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_slice_buffer garbage;
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
- if (error == GRPC_ERROR_NONE && nread == 0) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF");
- }
- if (error == GRPC_ERROR_NONE) {
- // Successful read
- if ((size_t)nread < tcp->read_slices->length) {
- /* TODO(murgatroid99): Instead of discarding the unused part of the read
- * buffer, reuse it as the next read buffer. */
- grpc_slice_buffer_init(&garbage);
- grpc_slice_buffer_trim_end(
- tcp->read_slices, tcp->read_slices->length - (size_t)nread, &garbage);
- grpc_slice_buffer_reset_and_unref_internal(&garbage);
- }
- } else {
- grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
- }
- call_read_cb(tcp, error);
-}
-
-static void tcp_read_allocation_done(void* tcpp, grpc_error* error) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)tcpp;
+ grpc_core::ExecCtx exec_ctx;
+ grpc_slice_buffer garbage;
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
+ if (error == GRPC_ERROR_NONE && nread == 0) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF");
+ }
+ if (error == GRPC_ERROR_NONE) {
+ // Successful read
+ if ((size_t)nread < tcp->read_slices->length) {
+ /* TODO(murgatroid99): Instead of discarding the unused part of the read
+ * buffer, reuse it as the next read buffer. */
+ grpc_slice_buffer_init(&garbage);
+ grpc_slice_buffer_trim_end(
+ tcp->read_slices, tcp->read_slices->length - (size_t)nread, &garbage);
+ grpc_slice_buffer_reset_and_unref_internal(&garbage);
+ }
+ } else {
+ grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
+ }
+ call_read_cb(tcp, error);
+}
+
+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)) {
- gpr_log(GPR_INFO, "TCP:%p read_allocation_done: %s", tcp->socket,
- grpc_error_string(error));
- }
- if (error == GRPC_ERROR_NONE) {
- /* Before calling read, we allocate a buffer with exactly one slice
- * to tcp->read_slices and wait for the callback indicating that the
- * allocation was successful. So slices[0] should always exist here */
- char* buffer = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[0]);
- size_t len = GRPC_SLICE_LENGTH(tcp->read_slices->slices[0]);
- grpc_custom_socket_vtable->read(tcp->socket, buffer, len,
- custom_read_callback);
- } else {
- grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
- call_read_cb(tcp, GRPC_ERROR_REF(error));
- }
+ gpr_log(GPR_INFO, "TCP:%p read_allocation_done: %s", tcp->socket,
+ grpc_error_string(error));
+ }
+ if (error == GRPC_ERROR_NONE) {
+ /* Before calling read, we allocate a buffer with exactly one slice
+ * to tcp->read_slices and wait for the callback indicating that the
+ * allocation was successful. So slices[0] should always exist here */
+ char* buffer = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[0]);
+ size_t len = GRPC_SLICE_LENGTH(tcp->read_slices->slices[0]);
+ grpc_custom_socket_vtable->read(tcp->socket, buffer, len,
+ custom_read_callback);
+ } else {
+ 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)) {
- 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,
+ 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*/) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- GPR_ASSERT(tcp->read_cb == nullptr);
- tcp->read_cb = cb;
- tcp->read_slices = read_slices;
- grpc_slice_buffer_reset_and_unref_internal(read_slices);
- TCP_REF(tcp, "read");
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ GPR_ASSERT(tcp->read_cb == nullptr);
+ tcp->read_cb = cb;
+ 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);
}
-}
-
-static void custom_write_callback(grpc_custom_socket* socket,
- grpc_error* error) {
+}
+
+static void custom_write_callback(grpc_custom_socket* socket,
+ grpc_error* error) {
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;
+ 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)) {
- const char* str = grpc_error_string(error);
- gpr_log(GPR_INFO, "write complete on %p: error=%s", tcp->socket, str);
- }
- TCP_UNREF(tcp, "write");
+ 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);
-}
-
-static void endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* write_slices,
+}
+
+static void endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* write_slices,
grpc_closure* cb, void* /*arg*/) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
-
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- size_t j;
-
- for (j = 0; j < write_slices->count; j++) {
- char* data = grpc_dump_slice(write_slices->slices[j],
- GPR_DUMP_HEX | GPR_DUMP_ASCII);
+ size_t j;
+
+ for (j = 0; j < write_slices->count; j++) {
+ char* data = grpc_dump_slice(write_slices->slices[j],
+ GPR_DUMP_HEX | GPR_DUMP_ASCII);
gpr_log(GPR_INFO, "WRITE %p (peer=%s): %s", tcp->socket,
tcp->peer_string.c_str(), data);
- gpr_free(data);
- }
- }
-
- if (tcp->shutting_down) {
+ gpr_free(data);
+ }
+ }
+
+ if (tcp->shutting_down) {
grpc_core::ExecCtx::Run(
DEBUG_LOCATION, cb,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP socket is shutting down"));
- return;
- }
-
- GPR_ASSERT(tcp->write_cb == nullptr);
- tcp->write_slices = write_slices;
- GPR_ASSERT(tcp->write_slices->count <= UINT_MAX);
- if (tcp->write_slices->count == 0) {
- // No slices means we don't have to do anything,
- // and libuv doesn't like empty writes
+ return;
+ }
+
+ GPR_ASSERT(tcp->write_cb == nullptr);
+ tcp->write_slices = write_slices;
+ GPR_ASSERT(tcp->write_slices->count <= UINT_MAX);
+ 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);
- return;
- }
- tcp->write_cb = cb;
- TCP_REF(tcp, "write");
- grpc_custom_socket_vtable->write(tcp->socket, tcp->write_slices,
- custom_write_callback);
-}
-
-static void endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
- // No-op. We're ignoring pollsets currently
- (void)ep;
- (void)pollset;
-}
-
-static void endpoint_add_to_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset) {
- // No-op. We're ignoring pollsets currently
- (void)ep;
- (void)pollset;
-}
-
-static void endpoint_delete_from_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset) {
- // No-op. We're ignoring pollsets currently
- (void)ep;
- (void)pollset;
-}
-
-static void endpoint_shutdown(grpc_endpoint* ep, grpc_error* why) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
- if (!tcp->shutting_down) {
+ return;
+ }
+ tcp->write_cb = cb;
+ TCP_REF(tcp, "write");
+ grpc_custom_socket_vtable->write(tcp->socket, tcp->write_slices,
+ custom_write_callback);
+}
+
+static void endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
+ // No-op. We're ignoring pollsets currently
+ (void)ep;
+ (void)pollset;
+}
+
+static void endpoint_add_to_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset) {
+ // No-op. We're ignoring pollsets currently
+ (void)ep;
+ (void)pollset;
+}
+
+static void endpoint_delete_from_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset) {
+ // No-op. We're ignoring pollsets currently
+ (void)ep;
+ (void)pollset;
+}
+
+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)) {
- const char* str = grpc_error_string(why);
- gpr_log(GPR_INFO, "TCP %p shutdown why=%s", tcp->socket, str);
- }
- tcp->shutting_down = true;
+ 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_resource_user_shutdown(tcp->resource_user);
- grpc_custom_socket_vtable->shutdown(tcp->socket);
- }
- GRPC_ERROR_UNREF(why);
-}
-
-static void custom_close_callback(grpc_custom_socket* socket) {
- socket->refs--;
- if (socket->refs == 0) {
- grpc_custom_socket_vtable->destroy(socket);
- gpr_free(socket);
- } else if (socket->endpoint) {
+ grpc_resource_user_shutdown(tcp->resource_user);
+ grpc_custom_socket_vtable->shutdown(tcp->socket);
+ }
+ GRPC_ERROR_UNREF(why);
+}
+
+static void custom_close_callback(grpc_custom_socket* socket) {
+ socket->refs--;
+ if (socket->refs == 0) {
+ grpc_custom_socket_vtable->destroy(socket);
+ gpr_free(socket);
+ } else if (socket->endpoint) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
- TCP_UNREF(tcp, "destroy");
- }
-}
-
-static void endpoint_destroy(grpc_endpoint* ep) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
- grpc_custom_socket_vtable->close(tcp->socket, custom_close_callback);
-}
-
+ grpc_core::ExecCtx exec_ctx;
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
+ TCP_UNREF(tcp, "destroy");
+ }
+}
+
+static void endpoint_destroy(grpc_endpoint* ep) {
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
+ grpc_custom_socket_vtable->close(tcp->socket, custom_close_callback);
+}
+
static y_absl::string_view endpoint_get_peer(grpc_endpoint* ep) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
return tcp->peer_string;
-}
-
+}
+
static y_absl::string_view endpoint_get_local_address(grpc_endpoint* ep) {
custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
return tcp->local_address;
}
-static grpc_resource_user* endpoint_get_resource_user(grpc_endpoint* ep) {
- custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
- return tcp->resource_user;
-}
-
+static grpc_resource_user* endpoint_get_resource_user(grpc_endpoint* ep) {
+ custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
+ return tcp->resource_user;
+}
+
static int endpoint_get_fd(grpc_endpoint* /*ep*/) { return -1; }
-
+
static bool endpoint_can_track_err(grpc_endpoint* /*ep*/) { return false; }
-static grpc_endpoint_vtable vtable = {endpoint_read,
- endpoint_write,
- endpoint_add_to_pollset,
- endpoint_add_to_pollset_set,
- endpoint_delete_from_pollset_set,
- endpoint_shutdown,
- endpoint_destroy,
- endpoint_get_resource_user,
- endpoint_get_peer,
+static grpc_endpoint_vtable vtable = {endpoint_read,
+ endpoint_write,
+ endpoint_add_to_pollset,
+ endpoint_add_to_pollset_set,
+ endpoint_delete_from_pollset_set,
+ endpoint_shutdown,
+ endpoint_destroy,
+ endpoint_get_resource_user,
+ endpoint_get_peer,
endpoint_get_local_address,
endpoint_get_fd,
endpoint_can_track_err};
-
-grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
- grpc_resource_quota* resource_quota,
+
+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::ExecCtx exec_ctx;
-
+ grpc_core::ExecCtx exec_ctx;
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "Creating TCP endpoint %p", socket);
- }
- socket->refs++;
- socket->endpoint = (grpc_endpoint*)tcp;
- tcp->socket = socket;
- tcp->base.vtable = &vtable;
- gpr_ref_init(&tcp->refcount, 1);
+ gpr_log(GPR_INFO, "Creating TCP endpoint %p", socket);
+ }
+ socket->refs++;
+ socket->endpoint = (grpc_endpoint*)tcp;
+ tcp->socket = socket;
+ tcp->base.vtable = &vtable;
+ gpr_ref_init(&tcp->refcount, 1);
tcp->peer_string = peer_string;
grpc_resolved_address resolved_local_addr;
resolved_local_addr.len = sizeof(resolved_local_addr.addr);
@@ -377,10 +377,10 @@ grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
} else {
tcp->local_address = grpc_sockaddr_to_uri(&resolved_local_addr);
}
- tcp->shutting_down = false;
- tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
- grpc_resource_user_slice_allocator_init(
- &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp);
-
- return &tcp->base;
-}
+ tcp->shutting_down = false;
+ tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
+ grpc_resource_user_slice_allocator_init(
+ &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp);
+
+ return &tcp->base;
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.h
index d32ed2b4b61..f611742a2f2 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_IOMGR_TCP_CUSTOM_H
-#define GRPC_CORE_LIB_IOMGR_TCP_CUSTOM_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/endpoint.h"
-#include "src/core/lib/iomgr/sockaddr.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_LIB_IOMGR_TCP_CUSTOM_H
+#define GRPC_CORE_LIB_IOMGR_TCP_CUSTOM_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+
// Same number as the micro of SO_REUSEPORT in kernel
#define GRPC_CUSTOM_SOCKET_OPT_SO_REUSEPORT (0x00000200u)
-typedef struct grpc_tcp_listener grpc_tcp_listener;
-typedef struct grpc_custom_tcp_connect grpc_custom_tcp_connect;
-
-typedef struct grpc_custom_socket {
- // Implementation defined
- void* impl;
- grpc_endpoint* endpoint;
- grpc_tcp_listener* listener;
- grpc_custom_tcp_connect* connector;
- int refs;
-} grpc_custom_socket;
-
-typedef void (*grpc_custom_connect_callback)(grpc_custom_socket* socket,
- grpc_error* error);
-typedef void (*grpc_custom_write_callback)(grpc_custom_socket* socket,
- grpc_error* error);
-typedef void (*grpc_custom_read_callback)(grpc_custom_socket* socket,
- size_t nread, grpc_error* error);
-typedef void (*grpc_custom_accept_callback)(grpc_custom_socket* socket,
- grpc_custom_socket* client,
- grpc_error* error);
-typedef void (*grpc_custom_close_callback)(grpc_custom_socket* socket);
-
-typedef 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);
-} grpc_socket_vtable;
-
-/* Internal APIs */
-void grpc_custom_endpoint_init(grpc_socket_vtable* impl);
-
-void grpc_custom_close_server_callback(grpc_tcp_listener* listener);
-
-grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
- grpc_resource_quota* resource_quota,
+typedef struct grpc_tcp_listener grpc_tcp_listener;
+typedef struct grpc_custom_tcp_connect grpc_custom_tcp_connect;
+
+typedef struct grpc_custom_socket {
+ // Implementation defined
+ void* impl;
+ grpc_endpoint* endpoint;
+ grpc_tcp_listener* listener;
+ grpc_custom_tcp_connect* connector;
+ int refs;
+} grpc_custom_socket;
+
+typedef void (*grpc_custom_connect_callback)(grpc_custom_socket* socket,
+ grpc_error* error);
+typedef void (*grpc_custom_write_callback)(grpc_custom_socket* socket,
+ grpc_error* error);
+typedef void (*grpc_custom_read_callback)(grpc_custom_socket* socket,
+ size_t nread, grpc_error* error);
+typedef void (*grpc_custom_accept_callback)(grpc_custom_socket* socket,
+ grpc_custom_socket* client,
+ grpc_error* error);
+typedef void (*grpc_custom_close_callback)(grpc_custom_socket* socket);
+
+typedef 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);
+} grpc_socket_vtable;
+
+/* Internal APIs */
+void grpc_custom_endpoint_init(grpc_socket_vtable* impl);
+
+void grpc_custom_close_server_callback(grpc_tcp_listener* listener);
+
+grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
+ grpc_resource_quota* resource_quota,
const char* peer_string);
-
-#endif /* GRPC_CORE_LIB_IOMGR_TCP_CUSTOM_H */
+
+#endif /* GRPC_CORE_LIB_IOMGR_TCP_CUSTOM_H */
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 b1cd892964d..edb3e5d794c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc
@@ -1,65 +1,65 @@
-/*
- *
- * 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/iomgr/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/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_TCP
-
-#include "src/core/lib/iomgr/tcp_posix.h"
-
-#include <errno.h>
+
+#include "src/core/lib/iomgr/tcp_posix.h"
+
+#include <errno.h>
#include <limits.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
-#include <stdbool.h>
+#include <stdbool.h>
#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
#include <algorithm>
#include <unordered_map>
-
-#include <grpc/slice.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/channel/channel_args.h"
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
+
+#include <grpc/slice.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/channel/channel_args.h"
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/buffer_list.h"
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/iomgr/socket_utils_posix.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/profiling/timers.h"
+#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
@@ -69,12 +69,12 @@
#define TCP_CM_INQ TCP_INQ
#endif
-#ifdef GRPC_HAVE_MSG_NOSIGNAL
-#define SENDMSG_FLAGS MSG_NOSIGNAL
-#else
-#define SENDMSG_FLAGS 0
-#endif
-
+#ifdef GRPC_HAVE_MSG_NOSIGNAL
+#define SENDMSG_FLAGS MSG_NOSIGNAL
+#else
+#define SENDMSG_FLAGS 0
+#endif
+
// TCP zero copy sendmsg flag.
// NB: We define this here as a fallback in case we're using an older set of
// library headers that has not defined MSG_ZEROCOPY. Since this constant is
@@ -84,14 +84,14 @@
#define MSG_ZEROCOPY 0x4000000
#endif
-#ifdef GRPC_MSG_IOVLEN_TYPE
-typedef GRPC_MSG_IOVLEN_TYPE msg_iovlen_type;
-#else
-typedef size_t msg_iovlen_type;
-#endif
-
-extern grpc_core::TraceFlag grpc_tcp_trace;
-
+#ifdef GRPC_MSG_IOVLEN_TYPE
+typedef GRPC_MSG_IOVLEN_TYPE msg_iovlen_type;
+#else
+typedef size_t msg_iovlen_type;
+#endif
+
+extern grpc_core::TraceFlag grpc_tcp_trace;
+
namespace grpc_core {
class TcpZerocopySendRecord {
@@ -350,49 +350,49 @@ class TcpZerocopySendCtx {
using grpc_core::TcpZerocopySendCtx;
using grpc_core::TcpZerocopySendRecord;
-namespace {
-struct grpc_tcp {
+namespace {
+struct grpc_tcp {
grpc_tcp(int max_sends, size_t send_bytes_threshold)
: tcp_zerocopy_send_ctx(max_sends, send_bytes_threshold) {}
- grpc_endpoint base;
- grpc_fd* em_fd;
- int fd;
+ grpc_endpoint base;
+ grpc_fd* em_fd;
+ int fd;
/* Used by the endpoint read function to distinguish the very first read call
* from the rest */
bool is_first_read;
- double target_length;
- double bytes_read_this_round;
+ double target_length;
+ double bytes_read_this_round;
grpc_core::RefCount refcount;
- gpr_atm shutdown_count;
-
- int min_read_chunk_size;
- int max_read_chunk_size;
-
- /* garbage after the last read */
- grpc_slice_buffer last_read_buffer;
-
- grpc_slice_buffer* incoming_buffer;
+ gpr_atm shutdown_count;
+
+ int min_read_chunk_size;
+ int max_read_chunk_size;
+
+ /* garbage after the last read */
+ 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 */
- grpc_slice_buffer* outgoing_buffer;
+ grpc_slice_buffer* outgoing_buffer;
/* byte within outgoing_buffer->slices[0] to write next */
- size_t outgoing_byte_idx;
-
- grpc_closure* read_cb;
- grpc_closure* write_cb;
- grpc_closure* release_fd_cb;
- int* release_fd;
-
- grpc_closure read_done_closure;
- grpc_closure write_done_closure;
+ size_t outgoing_byte_idx;
+
+ grpc_closure* read_cb;
+ grpc_closure* write_cb;
+ grpc_closure* release_fd_cb;
+ int* release_fd;
+
+ grpc_closure read_done_closure;
+ grpc_closure write_done_closure;
grpc_closure error_closure;
-
+
TString peer_string;
TString local_address;
-
- grpc_resource_user* resource_user;
- grpc_resource_user_slice_allocator slice_allocator;
+
+ grpc_resource_user* resource_user;
+ grpc_resource_user_slice_allocator slice_allocator;
grpc_core::TracedBuffer* tb_head; /* List of traced buffers */
gpr_mu tb_mu; /* Lock for access to list of traced buffers */
@@ -418,85 +418,85 @@ struct grpc_tcp {
on errors anymore */
TcpZerocopySendCtx tcp_zerocopy_send_ctx;
TcpZerocopySendRecord* current_zerocopy_send = nullptr;
-};
-
-struct backup_poller {
- gpr_mu* pollset_mu;
- grpc_closure run_poller;
-};
-
-} // namespace
-
+};
+
+struct backup_poller {
+ gpr_mu* pollset_mu;
+ grpc_closure run_poller;
+};
+
+} // namespace
+
static void ZerocopyDisableAndWaitForRemaining(grpc_tcp* tcp);
-#define BACKUP_POLLER_POLLSET(b) ((grpc_pollset*)((b) + 1))
-
-static gpr_atm g_uncovered_notifications_pending;
-static gpr_atm g_backup_poller; /* backup_poller* */
-
-static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error* error);
-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);
-
+#define BACKUP_POLLER_POLLSET(b) ((grpc_pollset*)((b) + 1))
+
+static gpr_atm g_uncovered_notifications_pending;
+static gpr_atm g_backup_poller; /* backup_poller* */
+
+static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error* error);
+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*/) {
- backup_poller* p = static_cast<backup_poller*>(bp);
+ backup_poller* p = static_cast<backup_poller*>(bp);
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);
-}
-
+ 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*/) {
- backup_poller* p = static_cast<backup_poller*>(bp);
+ backup_poller* p = static_cast<backup_poller*>(bp);
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "BACKUP_POLLER:%p run", p);
- }
- gpr_mu_lock(p->pollset_mu);
- grpc_millis deadline = grpc_core::ExecCtx::Get()->Now() + 10 * GPR_MS_PER_SEC;
- GRPC_STATS_INC_TCP_BACKUP_POLLER_POLLS();
- GRPC_LOG_IF_ERROR(
- "backup_poller:pollset_work",
- grpc_pollset_work(BACKUP_POLLER_POLLSET(p), nullptr, deadline));
- gpr_mu_unlock(p->pollset_mu);
- /* last "uncovered" notification is the ref that keeps us polling, if we get
- * there try a cas to release it */
- if (gpr_atm_no_barrier_load(&g_uncovered_notifications_pending) == 1 &&
- 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);
+ gpr_log(GPR_INFO, "BACKUP_POLLER:%p run", p);
+ }
+ gpr_mu_lock(p->pollset_mu);
+ grpc_millis deadline = grpc_core::ExecCtx::Get()->Now() + 10 * GPR_MS_PER_SEC;
+ GRPC_STATS_INC_TCP_BACKUP_POLLER_POLLS();
+ GRPC_LOG_IF_ERROR(
+ "backup_poller:pollset_work",
+ grpc_pollset_work(BACKUP_POLLER_POLLSET(p), nullptr, deadline));
+ gpr_mu_unlock(p->pollset_mu);
+ /* last "uncovered" notification is the ref that keeps us polling, if we get
+ * there try a cas to release it */
+ if (gpr_atm_no_barrier_load(&g_uncovered_notifications_pending) == 1 &&
+ 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)) {
- gpr_log(GPR_INFO, "BACKUP_POLLER:%p done cas_ok=%d", p, cas_ok);
- }
- gpr_mu_unlock(p->pollset_mu);
+ 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)) {
- 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 {
+ 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)) {
- gpr_log(GPR_INFO, "BACKUP_POLLER:%p reschedule", p);
- }
+ 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);
- }
-}
-
+ }
+}
+
static void drop_uncovered(grpc_tcp* /*tcp*/) {
- backup_poller* p = (backup_poller*)gpr_atm_acq_load(&g_backup_poller);
- gpr_atm old_count =
+ 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)) {
- gpr_log(GPR_INFO, "BACKUP_POLLER:%p uncover cnt %d->%d", p,
- static_cast<int>(old_count), static_cast<int>(old_count) - 1);
- }
- GPR_ASSERT(old_count != 1);
-}
-
+ gpr_log(GPR_INFO, "BACKUP_POLLER:%p uncover cnt %d->%d", p,
+ static_cast<int>(old_count), static_cast<int>(old_count) - 1);
+ }
+ GPR_ASSERT(old_count != 1);
+}
+
// gRPC API considers a Write operation to be done the moment it clears ‘flow
// control’ i.e., not necessarily sent on the wire. This means that the
// application MIGHT not call `grpc_completion_queue_next/pluck` in a timely
@@ -504,129 +504,129 @@ static void drop_uncovered(grpc_tcp* /*tcp*/) {
//
// We need to ensure that the fd is 'covered' (i.e being monitored by some
// polling thread and progress is made) and hence add it to a backup poller here
-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);
+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)) {
- gpr_log(GPR_INFO, "BACKUP_POLLER: cover cnt %d->%d",
- static_cast<int>(old_count), 2 + static_cast<int>(old_count));
- }
- if (old_count == 0) {
- GRPC_STATS_INC_TCP_BACKUP_POLLERS_CREATED();
- p = static_cast<backup_poller*>(
- gpr_zalloc(sizeof(*p) + grpc_pollset_size()));
+ gpr_log(GPR_INFO, "BACKUP_POLLER: cover cnt %d->%d",
+ static_cast<int>(old_count), 2 + static_cast<int>(old_count));
+ }
+ if (old_count == 0) {
+ 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)) {
- 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);
+ 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);
- } else {
- while ((p = (backup_poller*)gpr_atm_acq_load(&g_backup_poller)) ==
- nullptr) {
- // spin waiting for backup poller
- }
- }
+ } 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)) {
- gpr_log(GPR_INFO, "BACKUP_POLLER:%p add %p", p, tcp);
- }
- grpc_pollset_add_fd(BACKUP_POLLER_POLLSET(p), tcp->em_fd);
- if (old_count != 0) {
- drop_uncovered(tcp);
- }
-}
-
-static void notify_on_read(grpc_tcp* tcp) {
+ gpr_log(GPR_INFO, "BACKUP_POLLER:%p add %p", p, tcp);
+ }
+ grpc_pollset_add_fd(BACKUP_POLLER_POLLSET(p), tcp->em_fd);
+ if (old_count != 0) {
+ drop_uncovered(tcp);
+ }
+}
+
+static void notify_on_read(grpc_tcp* tcp) {
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) {
+ 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)) {
- gpr_log(GPR_INFO, "TCP:%p notify_on_write", tcp);
- }
+ gpr_log(GPR_INFO, "TCP:%p notify_on_write", tcp);
+ }
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) {
+ 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)) {
- gpr_log(GPR_INFO, "TCP:%p got_write: %s", arg, grpc_error_string(error));
- }
- drop_uncovered(static_cast<grpc_tcp*>(arg));
- tcp_handle_write(arg, error);
-}
-
-static void add_to_estimate(grpc_tcp* tcp, size_t bytes) {
- tcp->bytes_read_this_round += static_cast<double>(bytes);
-}
-
-static void finish_estimate(grpc_tcp* tcp) {
- /* If we read >80% of the target buffer in one read loop, increase the size
- of the target buffer to either the amount read, or twice its previous
- value */
- if (tcp->bytes_read_this_round > tcp->target_length * 0.8) {
- tcp->target_length =
- GPR_MAX(2 * tcp->target_length, tcp->bytes_read_this_round);
- } else {
- tcp->target_length =
- 0.99 * tcp->target_length + 0.01 * tcp->bytes_read_this_round;
- }
- tcp->bytes_read_this_round = 0;
-}
-
-static size_t get_target_read_size(grpc_tcp* tcp) {
- grpc_resource_quota* rq = grpc_resource_user_quota(tcp->resource_user);
- double pressure = grpc_resource_quota_get_memory_pressure(rq);
- double target =
- tcp->target_length * (pressure > 0.8 ? (1.0 - pressure) / 0.2 : 1.0);
- size_t sz = ((static_cast<size_t> GPR_CLAMP(target, tcp->min_read_chunk_size,
- tcp->max_read_chunk_size)) +
- 255) &
- ~static_cast<size_t>(255);
- /* don't use more than 1/16th of the overall resource quota for a single read
- * alloc */
- size_t rqmax = grpc_resource_quota_peek_size(rq);
- if (sz > rqmax / 16 && rqmax > 1024) {
- sz = rqmax / 16;
- }
- return sz;
-}
-
-static grpc_error* tcp_annotate_error(grpc_error* src_error, grpc_tcp* tcp) {
- return grpc_error_set_str(
- grpc_error_set_int(
- grpc_error_set_int(src_error, GRPC_ERROR_INT_FD, tcp->fd),
- /* All tcp errors are marked with UNAVAILABLE so that application may
- * choose to retry. */
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE),
- GRPC_ERROR_STR_TARGET_ADDRESS,
+ gpr_log(GPR_INFO, "TCP:%p got_write: %s", arg, grpc_error_string(error));
+ }
+ drop_uncovered(static_cast<grpc_tcp*>(arg));
+ tcp_handle_write(arg, error);
+}
+
+static void add_to_estimate(grpc_tcp* tcp, size_t bytes) {
+ tcp->bytes_read_this_round += static_cast<double>(bytes);
+}
+
+static void finish_estimate(grpc_tcp* tcp) {
+ /* If we read >80% of the target buffer in one read loop, increase the size
+ of the target buffer to either the amount read, or twice its previous
+ value */
+ if (tcp->bytes_read_this_round > tcp->target_length * 0.8) {
+ tcp->target_length =
+ GPR_MAX(2 * tcp->target_length, tcp->bytes_read_this_round);
+ } else {
+ tcp->target_length =
+ 0.99 * tcp->target_length + 0.01 * tcp->bytes_read_this_round;
+ }
+ tcp->bytes_read_this_round = 0;
+}
+
+static size_t get_target_read_size(grpc_tcp* tcp) {
+ grpc_resource_quota* rq = grpc_resource_user_quota(tcp->resource_user);
+ double pressure = grpc_resource_quota_get_memory_pressure(rq);
+ double target =
+ tcp->target_length * (pressure > 0.8 ? (1.0 - pressure) / 0.2 : 1.0);
+ size_t sz = ((static_cast<size_t> GPR_CLAMP(target, tcp->min_read_chunk_size,
+ tcp->max_read_chunk_size)) +
+ 255) &
+ ~static_cast<size_t>(255);
+ /* don't use more than 1/16th of the overall resource quota for a single read
+ * alloc */
+ size_t rqmax = grpc_resource_quota_peek_size(rq);
+ if (sz > rqmax / 16 && rqmax > 1024) {
+ sz = rqmax / 16;
+ }
+ return sz;
+}
+
+static grpc_error* tcp_annotate_error(grpc_error* src_error, grpc_tcp* tcp) {
+ return grpc_error_set_str(
+ grpc_error_set_int(
+ grpc_error_set_int(src_error, GRPC_ERROR_INT_FD, tcp->fd),
+ /* All tcp errors are marked with UNAVAILABLE so that application may
+ * choose to retry. */
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE),
+ GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_copied_string(tcp->peer_string.c_str()));
-}
-
-static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error* error);
-static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error);
-
-static void tcp_shutdown(grpc_endpoint* ep, grpc_error* why) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+}
+
+static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error* error);
+static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error);
+
+static void tcp_shutdown(grpc_endpoint* ep, grpc_error* why) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
ZerocopyDisableAndWaitForRemaining(tcp);
- grpc_fd_shutdown(tcp->em_fd, why);
- grpc_resource_user_shutdown(tcp->resource_user);
-}
-
-static void tcp_free(grpc_tcp* tcp) {
- grpc_fd_orphan(tcp->em_fd, tcp->release_fd_cb, tcp->release_fd,
+ grpc_fd_shutdown(tcp->em_fd, why);
+ grpc_resource_user_shutdown(tcp->resource_user);
+}
+
+static void tcp_free(grpc_tcp* tcp) {
+ grpc_fd_orphan(tcp->em_fd, tcp->release_fd_cb, tcp->release_fd,
"tcp_unref_orphan");
- grpc_slice_buffer_destroy_internal(&tcp->last_read_buffer);
- grpc_resource_user_unref(tcp->resource_user);
+ grpc_slice_buffer_destroy_internal(&tcp->last_read_buffer);
+ grpc_resource_user_unref(tcp->resource_user);
/* The lock is not really necessary here, since all refs have been released */
gpr_mu_lock(&tcp->tb_mu);
grpc_core::TracedBuffer::Shutdown(
@@ -636,55 +636,55 @@ static void tcp_free(grpc_tcp* tcp) {
tcp->outgoing_buffer_arg = nullptr;
gpr_mu_destroy(&tcp->tb_mu);
delete tcp;
-}
-
-#ifndef NDEBUG
+}
+
+#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))) {
- tcp_free(tcp);
- }
-}
-
+ 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);
-}
-#else
-#define TCP_UNREF(tcp, reason) tcp_unref((tcp))
-#define TCP_REF(tcp, reason) tcp_ref((tcp))
-static void tcp_unref(grpc_tcp* tcp) {
+}
+#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())) {
- tcp_free(tcp);
- }
-}
-
+ tcp_free(tcp);
+ }
+}
+
static void tcp_ref(grpc_tcp* tcp) { tcp->refcount.Ref(); }
-#endif
-
-static void tcp_destroy(grpc_endpoint* ep) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer);
+#endif
+
+static void tcp_destroy(grpc_endpoint* ep) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer);
if (grpc_event_engine_can_track_errors()) {
ZerocopyDisableAndWaitForRemaining(tcp);
gpr_atm_no_barrier_store(&tcp->stop_error_notification, true);
grpc_fd_set_error(tcp->em_fd);
}
- TCP_UNREF(tcp, "destroy");
-}
-
-static void call_read_cb(grpc_tcp* tcp, grpc_error* error) {
- grpc_closure* cb = tcp->read_cb;
-
+ TCP_UNREF(tcp, "destroy");
+}
+
+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)) {
- 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);
+ 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);
gpr_log(GPR_INFO, "READ %p (peer=%s) error=%s", tcp,
tcp->peer_string.c_str(), str);
-
+
if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) {
for (i = 0; i < tcp->incoming_buffer->count; i++) {
char* dump = grpc_dump_slice(tcp->incoming_buffer->slices[i],
@@ -692,20 +692,20 @@ static void call_read_cb(grpc_tcp* tcp, grpc_error* error) {
gpr_log(GPR_DEBUG, "DATA: %s", dump);
gpr_free(dump);
}
- }
- }
-
- tcp->read_cb = nullptr;
- tcp->incoming_buffer = nullptr;
+ }
+ }
+
+ tcp->read_cb = nullptr;
+ tcp->incoming_buffer = nullptr;
grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
-}
-
-#define MAX_READ_IOVEC 4
-static void tcp_do_read(grpc_tcp* tcp) {
- GPR_TIMER_SCOPE("tcp_do_read", 0);
- struct msghdr msg;
- struct iovec iov[MAX_READ_IOVEC];
- ssize_t read_bytes;
+}
+
+#define MAX_READ_IOVEC 4
+static void tcp_do_read(grpc_tcp* tcp) {
+ GPR_TIMER_SCOPE("tcp_do_read", 0);
+ 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);
@@ -717,16 +717,16 @@ static void tcp_do_read(grpc_tcp* tcp) {
#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]);
- }
-
+ 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;
@@ -739,10 +739,10 @@ static void tcp_do_read(grpc_tcp* tcp) {
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();
@@ -778,16 +778,16 @@ static void tcp_do_read(grpc_tcp* tcp) {
* 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);
+ 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));
- TCP_UNREF(tcp, "read");
+ TCP_UNREF(tcp, "read");
return;
- }
+ }
- GRPC_STATS_INC_TCP_READ_SIZE(read_bytes);
- add_to_estimate(tcp, static_cast<size_t>(read_bytes));
+ 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);
@@ -802,7 +802,7 @@ static void tcp_do_read(grpc_tcp* tcp) {
break;
}
}
- }
+ }
#endif /* GRPC_HAVE_TCP_INQ */
total_read_bytes += read_bytes;
@@ -835,7 +835,7 @@ static void tcp_do_read(grpc_tcp* tcp) {
if (tcp->inq == 0) {
finish_estimate(tcp);
- }
+ }
GPR_DEBUG_ASSERT(total_read_bytes > 0);
if (total_read_bytes < tcp->incoming_buffer->length) {
@@ -845,81 +845,81 @@ static void tcp_do_read(grpc_tcp* tcp) {
}
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);
+}
+
+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)) {
- gpr_log(GPR_INFO, "TCP:%p read_allocation_done: %s", tcp,
- grpc_error_string(error));
- }
+ gpr_log(GPR_INFO, "TCP:%p read_allocation_done: %s", tcp,
+ grpc_error_string(error));
+ }
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));
- TCP_UNREF(tcp, "read");
- } else {
- tcp_do_read(tcp);
- }
-}
-
-static void tcp_continue_read(grpc_tcp* tcp) {
- size_t target_read_size = get_target_read_size(tcp);
+ 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));
+ TCP_UNREF(tcp, "read");
+ } else {
+ tcp_do_read(tcp);
+ }
+}
+
+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 &&
- tcp->incoming_buffer->count < MAX_READ_IOVEC) {
+ tcp->incoming_buffer->count < MAX_READ_IOVEC) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "TCP:%p alloc_slices", tcp);
- }
+ 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 (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);
+}
+
+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)) {
- gpr_log(GPR_INFO, "TCP:%p got_read: %s", tcp, grpc_error_string(error));
- }
-
+ gpr_log(GPR_INFO, "TCP:%p got_read: %s", tcp, grpc_error_string(error));
+ }
+
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));
- TCP_UNREF(tcp, "read");
- } else {
- tcp_continue_read(tcp);
- }
-}
-
-static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer,
+ 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));
+ TCP_UNREF(tcp, "read");
+ } else {
+ tcp_continue_read(tcp);
+ }
+}
+
+static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer,
grpc_closure* cb, bool urgent) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- GPR_ASSERT(tcp->read_cb == nullptr);
- tcp->read_cb = cb;
- tcp->incoming_buffer = incoming_buffer;
- grpc_slice_buffer_reset_and_unref_internal(incoming_buffer);
- grpc_slice_buffer_swap(incoming_buffer, &tcp->last_read_buffer);
- TCP_REF(tcp, "read");
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ GPR_ASSERT(tcp->read_cb == nullptr);
+ tcp->read_cb = cb;
+ tcp->incoming_buffer = incoming_buffer;
+ grpc_slice_buffer_reset_and_unref_internal(incoming_buffer);
+ grpc_slice_buffer_swap(incoming_buffer, &tcp->last_read_buffer);
+ TCP_REF(tcp, "read");
if (tcp->is_first_read) {
/* Endpoint read called for the very first time. Register read callback with
* the polling engine */
tcp->is_first_read = false;
- notify_on_read(tcp);
+ 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 {
+ } 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
@@ -927,9 +927,9 @@ static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer,
* available */
grpc_core::Closure::Run(DEBUG_LOCATION, &tcp->read_done_closure,
GRPC_ERROR_NONE);
- }
-}
-
+ }
+}
+
/* A wrapper around sendmsg. It sends \a msg over \a fd and returns the number
* of bytes sent. */
ssize_t tcp_send(int fd, const struct msghdr* msg, int additional_flags = 0) {
@@ -1276,7 +1276,7 @@ void tcp_shutdown_buffer_list(grpc_tcp* tcp) {
#if defined(IOV_MAX) && IOV_MAX < 1000
#define MAX_WRITE_IOVEC IOV_MAX
#else
-#define MAX_WRITE_IOVEC 1000
+#define MAX_WRITE_IOVEC 1000
#endif
msg_iovlen_type TcpZerocopySendRecord::PopulateIovs(size_t* unwind_slice_idx,
size_t* unwind_byte_idx,
@@ -1406,45 +1406,45 @@ static bool tcp_flush_zerocopy(grpc_tcp* tcp, TcpZerocopySendRecord* record,
return done;
}
-static bool tcp_flush(grpc_tcp* tcp, grpc_error** error) {
- struct msghdr msg;
- struct iovec iov[MAX_WRITE_IOVEC];
- msg_iovlen_type iov_size;
+static bool tcp_flush(grpc_tcp* tcp, grpc_error** error) {
+ struct msghdr msg;
+ struct iovec iov[MAX_WRITE_IOVEC];
+ msg_iovlen_type iov_size;
ssize_t sent_length = 0;
- size_t sending_length;
- size_t trailing;
- size_t unwind_slice_idx;
- size_t unwind_byte_idx;
-
- // We always start at zero, because we eagerly unref and trim the slice
- // buffer as we write
- size_t outgoing_slice_idx = 0;
-
+ size_t sending_length;
+ size_t trailing;
+ size_t unwind_slice_idx;
+ size_t unwind_byte_idx;
+
+ // We always start at zero, because we eagerly unref and trim the slice
+ // buffer as we write
+ size_t outgoing_slice_idx = 0;
+
while (true) {
- sending_length = 0;
- unwind_slice_idx = outgoing_slice_idx;
- unwind_byte_idx = tcp->outgoing_byte_idx;
- for (iov_size = 0; outgoing_slice_idx != tcp->outgoing_buffer->count &&
- iov_size != MAX_WRITE_IOVEC;
- iov_size++) {
- iov[iov_size].iov_base =
- GRPC_SLICE_START_PTR(
- tcp->outgoing_buffer->slices[outgoing_slice_idx]) +
- tcp->outgoing_byte_idx;
- iov[iov_size].iov_len =
- GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]) -
- tcp->outgoing_byte_idx;
- sending_length += iov[iov_size].iov_len;
- outgoing_slice_idx++;
- tcp->outgoing_byte_idx = 0;
- }
- GPR_ASSERT(iov_size > 0);
-
- msg.msg_name = nullptr;
- msg.msg_namelen = 0;
- msg.msg_iov = iov;
- msg.msg_iovlen = iov_size;
- msg.msg_flags = 0;
+ sending_length = 0;
+ unwind_slice_idx = outgoing_slice_idx;
+ unwind_byte_idx = tcp->outgoing_byte_idx;
+ for (iov_size = 0; outgoing_slice_idx != tcp->outgoing_buffer->count &&
+ iov_size != MAX_WRITE_IOVEC;
+ iov_size++) {
+ iov[iov_size].iov_base =
+ GRPC_SLICE_START_PTR(
+ tcp->outgoing_buffer->slices[outgoing_slice_idx]) +
+ tcp->outgoing_byte_idx;
+ iov[iov_size].iov_len =
+ GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]) -
+ tcp->outgoing_byte_idx;
+ sending_length += iov[iov_size].iov_len;
+ outgoing_slice_idx++;
+ tcp->outgoing_byte_idx = 0;
+ }
+ GPR_ASSERT(iov_size > 0);
+
+ msg.msg_name = nullptr;
+ msg.msg_namelen = 0;
+ msg.msg_iov = iov;
+ msg.msg_iovlen = iov_size;
+ msg.msg_flags = 0;
bool tried_sending_message = false;
if (tcp->outgoing_buffer_arg != nullptr) {
if (!tcp->ts_capable ||
@@ -1460,112 +1460,112 @@ static bool tcp_flush(grpc_tcp* tcp, grpc_error** error) {
if (!tried_sending_message) {
msg.msg_control = nullptr;
msg.msg_controllen = 0;
-
+
GRPC_STATS_INC_TCP_WRITE_SIZE(sending_length);
GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(iov_size);
-
+
sent_length = tcp_send(tcp->fd, &msg);
}
-
- if (sent_length < 0) {
- if (errno == EAGAIN) {
- tcp->outgoing_byte_idx = unwind_byte_idx;
- // unref all and forget about all slices that have been written to this
- // point
- for (size_t idx = 0; idx < unwind_slice_idx; ++idx) {
+
+ if (sent_length < 0) {
+ if (errno == EAGAIN) {
+ tcp->outgoing_byte_idx = unwind_byte_idx;
+ // 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);
- }
- return false;
- } else if (errno == EPIPE) {
- *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp);
- grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer);
+ }
+ return false;
+ } else if (errno == EPIPE) {
+ *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp);
+ grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer);
tcp_shutdown_buffer_list(tcp);
- return true;
- } else {
- *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp);
- grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer);
+ return true;
+ } else {
+ *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp);
+ grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer);
tcp_shutdown_buffer_list(tcp);
- return true;
- }
- }
-
- GPR_ASSERT(tcp->outgoing_byte_idx == 0);
+ return true;
+ }
+ }
+
+ GPR_ASSERT(tcp->outgoing_byte_idx == 0);
tcp->bytes_counter += sent_length;
- trailing = sending_length - static_cast<size_t>(sent_length);
- while (trailing > 0) {
- size_t slice_length;
-
- outgoing_slice_idx--;
- slice_length =
- GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]);
- if (slice_length > trailing) {
- tcp->outgoing_byte_idx = slice_length - trailing;
- break;
- } else {
- trailing -= slice_length;
- }
- }
- if (outgoing_slice_idx == tcp->outgoing_buffer->count) {
- *error = GRPC_ERROR_NONE;
- grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer);
- return true;
- }
- }
-}
-
-static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error) {
- grpc_tcp* tcp = static_cast<grpc_tcp*>(arg);
- grpc_closure* cb;
-
- if (error != GRPC_ERROR_NONE) {
- cb = tcp->write_cb;
- tcp->write_cb = nullptr;
+ trailing = sending_length - static_cast<size_t>(sent_length);
+ while (trailing > 0) {
+ size_t slice_length;
+
+ outgoing_slice_idx--;
+ slice_length =
+ GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]);
+ if (slice_length > trailing) {
+ tcp->outgoing_byte_idx = slice_length - trailing;
+ break;
+ } else {
+ trailing -= slice_length;
+ }
+ }
+ if (outgoing_slice_idx == tcp->outgoing_buffer->count) {
+ *error = GRPC_ERROR_NONE;
+ grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer);
+ return true;
+ }
+ }
+}
+
+static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error) {
+ grpc_tcp* tcp = static_cast<grpc_tcp*>(arg);
+ grpc_closure* cb;
+
+ if (error != GRPC_ERROR_NONE) {
+ cb = tcp->write_cb;
+ tcp->write_cb = nullptr;
if (tcp->current_zerocopy_send != nullptr) {
UnrefMaybePutZerocopySendRecord(tcp, tcp->current_zerocopy_send, 0,
"handle_write_err");
tcp->current_zerocopy_send = nullptr;
}
grpc_core::Closure::Run(DEBUG_LOCATION, cb, GRPC_ERROR_REF(error));
- TCP_UNREF(tcp, "write");
- return;
- }
-
+ TCP_UNREF(tcp, "write");
+ return;
+ }
+
bool flush_result =
tcp->current_zerocopy_send != nullptr
? tcp_flush_zerocopy(tcp, tcp->current_zerocopy_send, &error)
: tcp_flush(tcp, &error);
if (!flush_result) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "write: delayed");
- }
- notify_on_write(tcp);
+ 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);
- } else {
- cb = tcp->write_cb;
- tcp->write_cb = nullptr;
+ } else {
+ cb = tcp->write_cb;
+ tcp->write_cb = nullptr;
tcp->current_zerocopy_send = nullptr;
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- const char* str = grpc_error_string(error);
- gpr_log(GPR_INFO, "write: %s", str);
- }
+ 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);
- TCP_UNREF(tcp, "write");
- }
-}
-
-static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
+ TCP_UNREF(tcp, "write");
+ }
+}
+
+static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
grpc_closure* cb, void* arg) {
- GPR_TIMER_SCOPE("tcp_write", 0);
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- grpc_error* error = GRPC_ERROR_NONE;
+ GPR_TIMER_SCOPE("tcp_write", 0);
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ grpc_error* error = GRPC_ERROR_NONE;
TcpZerocopySendRecord* zerocopy_send_record = nullptr;
-
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- size_t i;
-
- for (i = 0; i < buf->count; i++) {
+ size_t i;
+
+ for (i = 0; i < buf->count; i++) {
gpr_log(GPR_INFO, "WRITE %p (peer=%s)", tcp, tcp->peer_string.c_str());
if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) {
char* data =
@@ -1573,13 +1573,13 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
gpr_log(GPR_DEBUG, "DATA: %s", data);
gpr_free(data);
}
- }
- }
-
- GPR_ASSERT(tcp->write_cb == nullptr);
+ }
+ }
+
+ GPR_ASSERT(tcp->write_cb == nullptr);
GPR_DEBUG_ASSERT(tcp->current_zerocopy_send == nullptr);
-
- if (buf->length == 0) {
+
+ if (buf->length == 0) {
grpc_core::Closure::Run(
DEBUG_LOCATION, cb,
grpc_fd_is_shutdown(tcp->em_fd)
@@ -1587,8 +1587,8 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
tcp)
: GRPC_ERROR_NONE);
tcp_shutdown_buffer_list(tcp);
- return;
- }
+ return;
+ }
zerocopy_send_record = tcp_get_send_zerocopy_record(tcp, buf);
if (zerocopy_send_record == nullptr) {
@@ -1600,66 +1600,66 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
if (arg) {
GPR_ASSERT(grpc_event_engine_can_track_errors());
}
-
+
bool flush_result =
zerocopy_send_record != nullptr
? tcp_flush_zerocopy(tcp, zerocopy_send_record, &error)
: tcp_flush(tcp, &error);
if (!flush_result) {
- TCP_REF(tcp, "write");
- tcp->write_cb = cb;
+ TCP_REF(tcp, "write");
+ tcp->write_cb = cb;
tcp->current_zerocopy_send = zerocopy_send_record;
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- gpr_log(GPR_INFO, "write: delayed");
- }
- notify_on_write(tcp);
- } else {
+ gpr_log(GPR_INFO, "write: delayed");
+ }
+ notify_on_write(tcp);
+ } else {
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
- const char* str = grpc_error_string(error);
- gpr_log(GPR_INFO, "write: %s", str);
- }
+ const char* str = grpc_error_string(error);
+ gpr_log(GPR_INFO, "write: %s", str);
+ }
grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
- }
-}
-
-static void tcp_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- grpc_pollset_add_fd(pollset, tcp->em_fd);
-}
-
-static void tcp_add_to_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- grpc_pollset_set_add_fd(pollset_set, tcp->em_fd);
-}
-
-static void tcp_delete_from_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pollset_set) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ }
+}
+
+static void tcp_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ grpc_pollset_add_fd(pollset, tcp->em_fd);
+}
+
+static void tcp_add_to_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ grpc_pollset_set_add_fd(pollset_set, tcp->em_fd);
+}
+
+static void tcp_delete_from_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pollset_set) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
ZerocopyDisableAndWaitForRemaining(tcp);
- grpc_pollset_set_del_fd(pollset_set, tcp->em_fd);
-}
-
+ grpc_pollset_set_del_fd(pollset_set, tcp->em_fd);
+}
+
static y_absl::string_view tcp_get_peer(grpc_endpoint* ep) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
return tcp->peer_string;
-}
-
+}
+
static y_absl::string_view tcp_get_local_address(grpc_endpoint* ep) {
grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
return tcp->local_address;
}
-static int tcp_get_fd(grpc_endpoint* ep) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- return tcp->fd;
-}
-
-static grpc_resource_user* tcp_get_resource_user(grpc_endpoint* ep) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- return tcp->resource_user;
-}
-
+static int tcp_get_fd(grpc_endpoint* ep) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ return tcp->fd;
+}
+
+static grpc_resource_user* tcp_get_resource_user(grpc_endpoint* ep) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ return tcp->resource_user;
+}
+
static bool tcp_can_track_err(grpc_endpoint* ep) {
grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
if (!grpc_event_engine_can_track_errors()) {
@@ -1676,57 +1676,57 @@ static bool tcp_can_track_err(grpc_endpoint* ep) {
return false;
}
-static const grpc_endpoint_vtable vtable = {tcp_read,
- tcp_write,
- tcp_add_to_pollset,
- tcp_add_to_pollset_set,
- tcp_delete_from_pollset_set,
- tcp_shutdown,
- tcp_destroy,
- tcp_get_resource_user,
- tcp_get_peer,
+static const grpc_endpoint_vtable vtable = {tcp_read,
+ tcp_write,
+ tcp_add_to_pollset,
+ tcp_add_to_pollset_set,
+ tcp_delete_from_pollset_set,
+ tcp_shutdown,
+ tcp_destroy,
+ tcp_get_resource_user,
+ tcp_get_peer,
tcp_get_local_address,
tcp_get_fd,
tcp_can_track_err};
-
-#define MAX_CHUNK_SIZE 32 * 1024 * 1024
-
-grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
- const grpc_channel_args* channel_args,
- const char* peer_string) {
+
+#define MAX_CHUNK_SIZE 32 * 1024 * 1024
+
+grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
+ const grpc_channel_args* channel_args,
+ const char* peer_string) {
static constexpr bool kZerocpTxEnabledDefault = false;
- int tcp_read_chunk_size = GRPC_TCP_DEFAULT_READ_SLICE_SIZE;
- int tcp_max_read_chunk_size = 4 * 1024 * 1024;
- int tcp_min_read_chunk_size = 256;
+ int tcp_read_chunk_size = GRPC_TCP_DEFAULT_READ_SLICE_SIZE;
+ int tcp_max_read_chunk_size = 4 * 1024 * 1024;
+ int tcp_min_read_chunk_size = 256;
bool tcp_tx_zerocopy_enabled = kZerocpTxEnabledDefault;
int tcp_tx_zerocopy_send_bytes_thresh =
grpc_core::TcpZerocopySendCtx::kDefaultSendBytesThreshold;
int tcp_tx_zerocopy_max_simult_sends =
grpc_core::TcpZerocopySendCtx::kDefaultMaxSends;
- grpc_resource_quota* resource_quota = grpc_resource_quota_create(nullptr);
- if (channel_args != nullptr) {
- for (size_t i = 0; i < channel_args->num_args; i++) {
- if (0 ==
- strcmp(channel_args->args[i].key, GRPC_ARG_TCP_READ_CHUNK_SIZE)) {
- grpc_integer_options options = {tcp_read_chunk_size, 1, MAX_CHUNK_SIZE};
- tcp_read_chunk_size =
- grpc_channel_arg_get_integer(&channel_args->args[i], options);
- } else if (0 == strcmp(channel_args->args[i].key,
- GRPC_ARG_TCP_MIN_READ_CHUNK_SIZE)) {
- grpc_integer_options options = {tcp_read_chunk_size, 1, MAX_CHUNK_SIZE};
- tcp_min_read_chunk_size =
- grpc_channel_arg_get_integer(&channel_args->args[i], options);
- } else if (0 == strcmp(channel_args->args[i].key,
- GRPC_ARG_TCP_MAX_READ_CHUNK_SIZE)) {
- grpc_integer_options options = {tcp_read_chunk_size, 1, MAX_CHUNK_SIZE};
- tcp_max_read_chunk_size =
- grpc_channel_arg_get_integer(&channel_args->args[i], options);
- } else if (0 ==
- strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
- grpc_resource_quota_unref_internal(resource_quota);
- resource_quota =
- grpc_resource_quota_ref_internal(static_cast<grpc_resource_quota*>(
- channel_args->args[i].value.pointer.p));
+ grpc_resource_quota* resource_quota = grpc_resource_quota_create(nullptr);
+ if (channel_args != nullptr) {
+ for (size_t i = 0; i < channel_args->num_args; i++) {
+ if (0 ==
+ strcmp(channel_args->args[i].key, GRPC_ARG_TCP_READ_CHUNK_SIZE)) {
+ grpc_integer_options options = {tcp_read_chunk_size, 1, MAX_CHUNK_SIZE};
+ tcp_read_chunk_size =
+ grpc_channel_arg_get_integer(&channel_args->args[i], options);
+ } else if (0 == strcmp(channel_args->args[i].key,
+ GRPC_ARG_TCP_MIN_READ_CHUNK_SIZE)) {
+ grpc_integer_options options = {tcp_read_chunk_size, 1, MAX_CHUNK_SIZE};
+ tcp_min_read_chunk_size =
+ grpc_channel_arg_get_integer(&channel_args->args[i], options);
+ } else if (0 == strcmp(channel_args->args[i].key,
+ GRPC_ARG_TCP_MAX_READ_CHUNK_SIZE)) {
+ grpc_integer_options options = {tcp_read_chunk_size, 1, MAX_CHUNK_SIZE};
+ tcp_max_read_chunk_size =
+ grpc_channel_arg_get_integer(&channel_args->args[i], options);
+ } else if (0 ==
+ strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
+ grpc_resource_quota_unref_internal(resource_quota);
+ resource_quota =
+ grpc_resource_quota_ref_internal(static_cast<grpc_resource_quota*>(
+ channel_args->args[i].value.pointer.p));
} else if (0 == strcmp(channel_args->args[i].key,
GRPC_ARG_TCP_TX_ZEROCOPY_ENABLED)) {
tcp_tx_zerocopy_enabled = grpc_channel_arg_get_bool(
@@ -1744,21 +1744,21 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
grpc_core::TcpZerocopySendCtx::kDefaultMaxSends, 0, INT_MAX};
tcp_tx_zerocopy_max_simult_sends =
grpc_channel_arg_get_integer(&channel_args->args[i], options);
- }
- }
- }
-
- if (tcp_min_read_chunk_size > tcp_max_read_chunk_size) {
- tcp_min_read_chunk_size = tcp_max_read_chunk_size;
- }
- tcp_read_chunk_size = GPR_CLAMP(tcp_read_chunk_size, tcp_min_read_chunk_size,
- tcp_max_read_chunk_size);
-
+ }
+ }
+ }
+
+ if (tcp_min_read_chunk_size > tcp_max_read_chunk_size) {
+ tcp_min_read_chunk_size = tcp_max_read_chunk_size;
+ }
+ tcp_read_chunk_size = GPR_CLAMP(tcp_read_chunk_size, tcp_min_read_chunk_size,
+ tcp_max_read_chunk_size);
+
grpc_tcp* tcp = new grpc_tcp(tcp_tx_zerocopy_max_simult_sends,
tcp_tx_zerocopy_send_bytes_thresh);
- tcp->base.vtable = &vtable;
+ tcp->base.vtable = &vtable;
tcp->peer_string = peer_string;
- tcp->fd = grpc_fd_wrapped_fd(em_fd);
+ tcp->fd = grpc_fd_wrapped_fd(em_fd);
grpc_resolved_address resolved_local_addr;
memset(&resolved_local_addr, 0, sizeof(resolved_local_addr));
resolved_local_addr.len = sizeof(resolved_local_addr.addr);
@@ -1769,16 +1769,16 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
} else {
tcp->local_address = grpc_sockaddr_to_uri(&resolved_local_addr);
}
- tcp->read_cb = nullptr;
- tcp->write_cb = nullptr;
+ tcp->read_cb = nullptr;
+ tcp->write_cb = nullptr;
tcp->current_zerocopy_send = nullptr;
- tcp->release_fd_cb = nullptr;
- tcp->release_fd = nullptr;
- tcp->incoming_buffer = nullptr;
- tcp->target_length = static_cast<double>(tcp_read_chunk_size);
- tcp->min_read_chunk_size = tcp_min_read_chunk_size;
- tcp->max_read_chunk_size = tcp_max_read_chunk_size;
- tcp->bytes_read_this_round = 0;
+ tcp->release_fd_cb = nullptr;
+ tcp->release_fd = nullptr;
+ tcp->incoming_buffer = nullptr;
+ tcp->target_length = static_cast<double>(tcp_read_chunk_size);
+ tcp->min_read_chunk_size = tcp_min_read_chunk_size;
+ tcp->max_read_chunk_size = tcp_max_read_chunk_size;
+ tcp->bytes_read_this_round = 0;
/* Will be set to false by the very first endpoint read function */
tcp->is_first_read = true;
tcp->bytes_counter = -1;
@@ -1797,15 +1797,15 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
}
#endif
}
- /* paired with unref in grpc_tcp_destroy */
+ /* paired with unref in grpc_tcp_destroy */
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);
- tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
- grpc_resource_user_slice_allocator_init(
- &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp);
- grpc_resource_quota_unref_internal(resource_quota);
+ gpr_atm_no_barrier_store(&tcp->shutdown_count, 0);
+ tcp->em_fd = em_fd;
+ grpc_slice_buffer_init(&tcp->last_read_buffer);
+ tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
+ grpc_resource_user_slice_allocator_init(
+ &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp);
+ 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,
@@ -1844,30 +1844,30 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
grpc_schedule_on_exec_ctx);
grpc_fd_notify_on_error(tcp->em_fd, &tcp->error_closure);
}
-
- return &tcp->base;
-}
-
-int grpc_tcp_fd(grpc_endpoint* ep) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- GPR_ASSERT(ep->vtable == &vtable);
- return grpc_fd_wrapped_fd(tcp->em_fd);
-}
-
-void grpc_tcp_destroy_and_release_fd(grpc_endpoint* ep, int* fd,
- grpc_closure* done) {
- grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
- GPR_ASSERT(ep->vtable == &vtable);
- tcp->release_fd = fd;
- tcp->release_fd_cb = done;
- grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer);
+
+ return &tcp->base;
+}
+
+int grpc_tcp_fd(grpc_endpoint* ep) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ GPR_ASSERT(ep->vtable == &vtable);
+ return grpc_fd_wrapped_fd(tcp->em_fd);
+}
+
+void grpc_tcp_destroy_and_release_fd(grpc_endpoint* ep, int* fd,
+ grpc_closure* done) {
+ grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
+ GPR_ASSERT(ep->vtable == &vtable);
+ tcp->release_fd = fd;
+ tcp->release_fd_cb = done;
+ grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer);
if (grpc_event_engine_can_track_errors()) {
/* Stop errors notification. */
ZerocopyDisableAndWaitForRemaining(tcp);
gpr_atm_no_barrier_store(&tcp->stop_error_notification, true);
grpc_fd_set_error(tcp->em_fd);
}
- TCP_UNREF(tcp, "destroy");
-}
-
+ TCP_UNREF(tcp, "destroy");
+}
+
#endif /* GRPC_POSIX_SOCKET_TCP */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h
index eff825cb925..914c89c82ad 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -29,32 +29,32 @@
otherwise specified.
*/
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/port.h"
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.h"
#include "src/core/lib/iomgr/buffer_list.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/ev_posix.h"
-extern grpc_core::TraceFlag grpc_tcp_trace;
+extern grpc_core::TraceFlag grpc_tcp_trace;
/* Create a tcp endpoint given a file desciptor and a read slice size.
Takes ownership of fd. */
-grpc_endpoint* grpc_tcp_create(grpc_fd* fd, const grpc_channel_args* args,
- const char* peer_string);
+grpc_endpoint* grpc_tcp_create(grpc_fd* fd, const grpc_channel_args* args,
+ const char* peer_string);
/* Return the tcp endpoint's fd, or -1 if this is not available. Does not
release the fd.
Requires: ep must be a tcp endpoint.
*/
-int grpc_tcp_fd(grpc_endpoint* ep);
+int grpc_tcp_fd(grpc_endpoint* ep);
/* Destroy the tcp endpoint without closing its fd. *fd will be set and done
* will be called when the endpoint is destroyed.
* Requires: ep must be a tcp endpoint and fd must not be NULL. */
-void grpc_tcp_destroy_and_release_fd(grpc_endpoint* ep, int* fd,
- grpc_closure* done);
+void grpc_tcp_destroy_and_release_fd(grpc_endpoint* ep, int* fd,
+ grpc_closure* done);
#endif /* GRPC_CORE_LIB_IOMGR_TCP_POSIX_H */
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 046fd4979bd..66d3f228cb5 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.cc
@@ -1,77 +1,77 @@
-/*
- *
- * 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/lib/iomgr/tcp_server.h"
-
-grpc_tcp_server_vtable* grpc_tcp_server_impl;
-
-grpc_error* grpc_tcp_server_create(grpc_closure* shutdown_complete,
- const grpc_channel_args* args,
- grpc_tcp_server** server) {
- return grpc_tcp_server_impl->create(shutdown_complete, args, 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/tcp_server.h"
+
+grpc_tcp_server_vtable* grpc_tcp_server_impl;
+
+grpc_error* grpc_tcp_server_create(grpc_closure* shutdown_complete,
+ const grpc_channel_args* args,
+ grpc_tcp_server** server) {
+ return grpc_tcp_server_impl->create(shutdown_complete, args, server);
+}
+
void grpc_tcp_server_start(grpc_tcp_server* server,
const std::vector<grpc_pollset*>* pollsets,
- grpc_tcp_server_cb on_accept_cb, void* cb_arg) {
+ grpc_tcp_server_cb on_accept_cb, void* cb_arg) {
grpc_tcp_server_impl->start(server, pollsets, on_accept_cb, cb_arg);
-}
-
-grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s,
- const grpc_resolved_address* addr,
- int* out_port) {
- return grpc_tcp_server_impl->add_port(s, addr, out_port);
-}
-
+}
+
+grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s,
+ const grpc_resolved_address* addr,
+ int* out_port) {
+ 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);
}
-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);
-}
-
-int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
- unsigned fd_index) {
- return grpc_tcp_server_impl->port_fd(s, port_index, fd_index);
-}
-
-grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s) {
- return grpc_tcp_server_impl->ref(s);
-}
-
-void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s,
- grpc_closure* shutdown_starting) {
- grpc_tcp_server_impl->shutdown_starting_add(s, shutdown_starting);
-}
-
-void grpc_tcp_server_unref(grpc_tcp_server* s) {
- grpc_tcp_server_impl->unref(s);
-}
-
-void grpc_tcp_server_shutdown_listeners(grpc_tcp_server* s) {
- grpc_tcp_server_impl->shutdown_listeners(s);
-}
-
-void grpc_set_tcp_server_impl(grpc_tcp_server_vtable* impl) {
- grpc_tcp_server_impl = impl;
-}
+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);
+}
+
+int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
+ unsigned fd_index) {
+ return grpc_tcp_server_impl->port_fd(s, port_index, fd_index);
+}
+
+grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s) {
+ return grpc_tcp_server_impl->ref(s);
+}
+
+void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s,
+ grpc_closure* shutdown_starting) {
+ grpc_tcp_server_impl->shutdown_starting_add(s, shutdown_starting);
+}
+
+void grpc_tcp_server_unref(grpc_tcp_server* s) {
+ grpc_tcp_server_impl->unref(s);
+}
+
+void grpc_tcp_server_shutdown_listeners(grpc_tcp_server* s) {
+ grpc_tcp_server_impl->shutdown_listeners(s);
+}
+
+void grpc_set_tcp_server_impl(grpc_tcp_server_vtable* impl) {
+ grpc_tcp_server_impl = impl;
+}
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 6ba3513da5b..c053fea03a4 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TCP_SERVER_H
#define GRPC_CORE_LIB_IOMGR_TCP_SERVER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/grpc.h>
#include <grpc/impl/codegen/grpc_types.h>
@@ -36,7 +36,7 @@ typedef struct grpc_tcp_server grpc_tcp_server;
typedef struct grpc_tcp_server_acceptor {
/* grpc_tcp_server_cb functions share a ref on from_server that is valid
until the function returns. */
- grpc_tcp_server* from_server;
+ grpc_tcp_server* from_server;
/* Indices that may be passed to grpc_tcp_server_port_fd(). */
unsigned port_index;
unsigned fd_index;
@@ -48,9 +48,9 @@ typedef struct grpc_tcp_server_acceptor {
/* Called for newly connected TCP connections.
Takes ownership of acceptor. */
-typedef void (*grpc_tcp_server_cb)(void* arg, grpc_endpoint* ep,
- grpc_pollset* accepting_pollset,
- grpc_tcp_server_acceptor* 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.
@@ -62,36 +62,36 @@ class TcpServerFdHandler {
};
} // namespace grpc_core
-typedef struct grpc_tcp_server_vtable {
- grpc_error* (*create)(grpc_closure* shutdown_complete,
- const grpc_channel_args* args,
- grpc_tcp_server** server);
+typedef struct grpc_tcp_server_vtable {
+ grpc_error* (*create)(grpc_closure* shutdown_complete,
+ const grpc_channel_args* args,
+ grpc_tcp_server** server);
void (*start)(grpc_tcp_server* server,
const std::vector<grpc_pollset*>* pollsets,
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_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);
- 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);
- void (*shutdown_starting_add)(grpc_tcp_server* s,
- grpc_closure* shutdown_starting);
- void (*unref)(grpc_tcp_server* s);
- void (*shutdown_listeners)(grpc_tcp_server* s);
-} grpc_tcp_server_vtable;
-
+ 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);
+ void (*shutdown_starting_add)(grpc_tcp_server* s,
+ grpc_closure* shutdown_starting);
+ void (*unref)(grpc_tcp_server* s);
+ void (*shutdown_listeners)(grpc_tcp_server* s);
+} grpc_tcp_server_vtable;
+
/* Create a server, initially not bound to any ports. The caller owns one ref.
If shutdown_complete is not NULL, it will be used by
grpc_tcp_server_unref() when the ref count reaches zero. */
-grpc_error* grpc_tcp_server_create(grpc_closure* shutdown_complete,
- const grpc_channel_args* args,
- grpc_tcp_server** server);
+grpc_error* grpc_tcp_server_create(grpc_closure* shutdown_complete,
+ const grpc_channel_args* args,
+ grpc_tcp_server** server);
/* Start listening to bound ports */
void grpc_tcp_server_start(grpc_tcp_server* server,
const std::vector<grpc_pollset*>* pollsets,
- grpc_tcp_server_cb on_accept_cb, void* cb_arg);
+ grpc_tcp_server_cb on_accept_cb, void* cb_arg);
/* Add a port to the server, returning the newly allocated port on success, or
-1 on failure.
@@ -102,9 +102,9 @@ void grpc_tcp_server_start(grpc_tcp_server* server,
but not dualstack sockets. */
/* TODO(ctiller): deprecate this, and make grpc_tcp_server_add_ports to handle
all of the multiple socket port matching logic in one place */
-grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s,
- const grpc_resolved_address* addr,
- int* out_port);
+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. */
@@ -113,33 +113,33 @@ grpc_core::TcpServerFdHandler* grpc_tcp_server_create_fd_handler(
/* 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);
+unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server* s, unsigned port_index);
/* Returns the file descriptor of the Mth (fd_index) listening socket of the Nth
(port_index) call to add_port() on this server, or -1 if the indices are out
of bounds. The file descriptor remains owned by the server, and will be
cleaned up when the ref count reaches zero. */
-int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
+int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
unsigned fd_index);
/* Ref s and return s. */
-grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s);
+grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s);
/* shutdown_starting is called when ref count has reached zero and the server is
about to be destroyed. The server will be deleted after it returns. Calling
grpc_tcp_server_ref() from it has no effect. */
-void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s,
- grpc_closure* shutdown_starting);
+void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s,
+ grpc_closure* shutdown_starting);
/* If the refcount drops to zero, enqueue calls on exec_ctx to
shutdown_listeners and delete s. */
-void grpc_tcp_server_unref(grpc_tcp_server* s);
+void grpc_tcp_server_unref(grpc_tcp_server* s);
/* Shutdown the fds of listeners. */
-void grpc_tcp_server_shutdown_listeners(grpc_tcp_server* s);
-
-void grpc_tcp_server_global_init();
-
-void grpc_set_tcp_server_impl(grpc_tcp_server_vtable* impl);
+void grpc_tcp_server_shutdown_listeners(grpc_tcp_server* s);
+void grpc_tcp_server_global_init();
+
+void grpc_set_tcp_server_impl(grpc_tcp_server_vtable* impl);
+
#endif /* GRPC_CORE_LIB_IOMGR_TCP_SERVER_H */
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 0cffa1f5719..2c7ebb36429 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
@@ -1,288 +1,288 @@
-/*
- *
- * 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/lib/iomgr/port.h"
-
-#include <assert.h>
-#include <string.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 "src/core/lib/iomgr/port.h"
+
+#include <assert.h>
+#include <string.h>
+
#include <util/generic/string.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/tcp_custom.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-
-extern grpc_core::TraceFlag grpc_tcp_trace;
-
-extern grpc_socket_vtable* grpc_custom_socket_vtable;
-
-/* one listening port */
-struct grpc_tcp_listener {
- grpc_tcp_server* server;
- unsigned port_index;
- int port;
-
- grpc_custom_socket* socket;
-
- /* linked list */
- struct grpc_tcp_listener* next;
-
- bool closed;
-};
-
-struct grpc_tcp_server {
- gpr_refcount refs;
-
- /* Called whenever accept() succeeds on a server port. */
- grpc_tcp_server_cb on_accept_cb;
- void* on_accept_cb_arg;
-
- int open_ports;
-
- /* linked list of server ports */
- grpc_tcp_listener* head;
- grpc_tcp_listener* tail;
-
- /* List of closures passed to shutdown_starting_add(). */
- grpc_closure_list shutdown_starting;
-
- /* shutdown callback */
- grpc_closure* shutdown_complete;
-
- bool shutdown;
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/tcp_custom.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+
+extern grpc_core::TraceFlag grpc_tcp_trace;
+
+extern grpc_socket_vtable* grpc_custom_socket_vtable;
+
+/* one listening port */
+struct grpc_tcp_listener {
+ grpc_tcp_server* server;
+ unsigned port_index;
+ int port;
+
+ grpc_custom_socket* socket;
+
+ /* linked list */
+ struct grpc_tcp_listener* next;
+
+ bool closed;
+};
+
+struct grpc_tcp_server {
+ gpr_refcount refs;
+
+ /* Called whenever accept() succeeds on a server port. */
+ grpc_tcp_server_cb on_accept_cb;
+ void* on_accept_cb_arg;
+
+ int open_ports;
+
+ /* linked list of server ports */
+ grpc_tcp_listener* head;
+ grpc_tcp_listener* tail;
+
+ /* List of closures passed to shutdown_starting_add(). */
+ grpc_closure_list shutdown_starting;
+
+ /* shutdown callback */
+ grpc_closure* shutdown_complete;
+
+ bool shutdown;
bool so_reuseport;
-
- grpc_resource_quota* resource_quota;
-};
-
-static grpc_error* tcp_server_create(grpc_closure* shutdown_complete,
- const grpc_channel_args* args,
- grpc_tcp_server** server) {
- grpc_tcp_server* s = (grpc_tcp_server*)gpr_malloc(sizeof(grpc_tcp_server));
+
+ grpc_resource_quota* resource_quota;
+};
+
+static grpc_error* tcp_server_create(grpc_closure* shutdown_complete,
+ const grpc_channel_args* args,
+ grpc_tcp_server** server) {
+ grpc_tcp_server* s = (grpc_tcp_server*)gpr_malloc(sizeof(grpc_tcp_server));
// Let the implementation decide if so_reuseport can be enabled or not.
s->so_reuseport = true;
- s->resource_quota = grpc_resource_quota_create(nullptr);
- for (size_t i = 0; i < (args == nullptr ? 0 : args->num_args); i++) {
+ s->resource_quota = grpc_resource_quota_create(nullptr);
+ for (size_t i = 0; i < (args == nullptr ? 0 : args->num_args); i++) {
if (!grpc_channel_args_find_bool(args, GRPC_ARG_ALLOW_REUSEPORT, true)) {
s->so_reuseport = false;
}
- if (0 == strcmp(GRPC_ARG_RESOURCE_QUOTA, args->args[i].key)) {
- if (args->args[i].type == GRPC_ARG_POINTER) {
- grpc_resource_quota_unref_internal(s->resource_quota);
- s->resource_quota = grpc_resource_quota_ref_internal(
- (grpc_resource_quota*)args->args[i].value.pointer.p);
- } else {
- grpc_resource_quota_unref_internal(s->resource_quota);
- gpr_free(s);
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- GRPC_ARG_RESOURCE_QUOTA " must be a pointer to a buffer pool");
- }
- }
- }
- gpr_ref_init(&s->refs, 1);
- s->on_accept_cb = nullptr;
- s->on_accept_cb_arg = nullptr;
- s->open_ports = 0;
- s->head = nullptr;
- s->tail = nullptr;
- s->shutdown_starting.head = nullptr;
- s->shutdown_starting.tail = nullptr;
- s->shutdown_complete = shutdown_complete;
- s->shutdown = false;
- *server = s;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_tcp_server* tcp_server_ref(grpc_tcp_server* s) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- gpr_ref(&s->refs);
- return s;
-}
-
-static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
- grpc_closure* shutdown_starting) {
- grpc_closure_list_append(&s->shutdown_starting, shutdown_starting,
- GRPC_ERROR_NONE);
-}
-
-static void finish_shutdown(grpc_tcp_server* s) {
- GPR_ASSERT(s->shutdown);
- if (s->shutdown_complete != nullptr) {
+ if (0 == strcmp(GRPC_ARG_RESOURCE_QUOTA, args->args[i].key)) {
+ if (args->args[i].type == GRPC_ARG_POINTER) {
+ grpc_resource_quota_unref_internal(s->resource_quota);
+ s->resource_quota = grpc_resource_quota_ref_internal(
+ (grpc_resource_quota*)args->args[i].value.pointer.p);
+ } else {
+ grpc_resource_quota_unref_internal(s->resource_quota);
+ gpr_free(s);
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ GRPC_ARG_RESOURCE_QUOTA " must be a pointer to a buffer pool");
+ }
+ }
+ }
+ gpr_ref_init(&s->refs, 1);
+ s->on_accept_cb = nullptr;
+ s->on_accept_cb_arg = nullptr;
+ s->open_ports = 0;
+ s->head = nullptr;
+ s->tail = nullptr;
+ s->shutdown_starting.head = nullptr;
+ s->shutdown_starting.tail = nullptr;
+ s->shutdown_complete = shutdown_complete;
+ s->shutdown = false;
+ *server = s;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_tcp_server* tcp_server_ref(grpc_tcp_server* s) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ gpr_ref(&s->refs);
+ return s;
+}
+
+static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
+ grpc_closure* shutdown_starting) {
+ grpc_closure_list_append(&s->shutdown_starting, shutdown_starting,
+ GRPC_ERROR_NONE);
+}
+
+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);
- }
-
- while (s->head) {
- grpc_tcp_listener* sp = s->head;
- s->head = sp->next;
- sp->next = nullptr;
- gpr_free(sp);
- }
- grpc_resource_quota_unref_internal(s->resource_quota);
- gpr_free(s);
-}
-
-static void custom_close_callback(grpc_custom_socket* socket) {
- grpc_tcp_listener* sp = socket->listener;
- if (sp) {
- grpc_core::ExecCtx exec_ctx;
- sp->server->open_ports--;
- if (sp->server->open_ports == 0 && sp->server->shutdown) {
- finish_shutdown(sp->server);
- }
- }
- socket->refs--;
- if (socket->refs == 0) {
- grpc_custom_socket_vtable->destroy(socket);
- gpr_free(socket);
- }
-}
-
-void grpc_custom_close_server_callback(grpc_tcp_listener* sp) {
- if (sp) {
- grpc_core::ExecCtx exec_ctx;
- sp->server->open_ports--;
- if (sp->server->open_ports == 0 && sp->server->shutdown) {
- finish_shutdown(sp->server);
- }
- }
-}
-
-static void close_listener(grpc_tcp_listener* sp) {
- grpc_custom_socket* socket = sp->socket;
- if (!sp->closed) {
- sp->closed = true;
- grpc_custom_socket_vtable->close(socket, custom_close_callback);
- }
-}
-
-static void tcp_server_destroy(grpc_tcp_server* s) {
- int immediately_done = 0;
- grpc_tcp_listener* sp;
-
- GPR_ASSERT(!s->shutdown);
- s->shutdown = true;
-
- if (s->open_ports == 0) {
- immediately_done = 1;
- }
- for (sp = s->head; sp; sp = sp->next) {
- close_listener(sp);
- }
-
- if (immediately_done) {
- finish_shutdown(s);
- }
-}
-
-static void tcp_server_unref(grpc_tcp_server* s) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- if (gpr_unref(&s->refs)) {
- /* Complete shutdown_starting work before destroying. */
- grpc_core::ExecCtx exec_ctx;
+ }
+
+ while (s->head) {
+ grpc_tcp_listener* sp = s->head;
+ s->head = sp->next;
+ sp->next = nullptr;
+ gpr_free(sp);
+ }
+ grpc_resource_quota_unref_internal(s->resource_quota);
+ gpr_free(s);
+}
+
+static void custom_close_callback(grpc_custom_socket* socket) {
+ grpc_tcp_listener* sp = socket->listener;
+ if (sp) {
+ grpc_core::ExecCtx exec_ctx;
+ sp->server->open_ports--;
+ if (sp->server->open_ports == 0 && sp->server->shutdown) {
+ finish_shutdown(sp->server);
+ }
+ }
+ socket->refs--;
+ if (socket->refs == 0) {
+ grpc_custom_socket_vtable->destroy(socket);
+ gpr_free(socket);
+ }
+}
+
+void grpc_custom_close_server_callback(grpc_tcp_listener* sp) {
+ if (sp) {
+ grpc_core::ExecCtx exec_ctx;
+ sp->server->open_ports--;
+ if (sp->server->open_ports == 0 && sp->server->shutdown) {
+ finish_shutdown(sp->server);
+ }
+ }
+}
+
+static void close_listener(grpc_tcp_listener* sp) {
+ grpc_custom_socket* socket = sp->socket;
+ if (!sp->closed) {
+ sp->closed = true;
+ grpc_custom_socket_vtable->close(socket, custom_close_callback);
+ }
+}
+
+static void tcp_server_destroy(grpc_tcp_server* s) {
+ int immediately_done = 0;
+ grpc_tcp_listener* sp;
+
+ GPR_ASSERT(!s->shutdown);
+ s->shutdown = true;
+
+ if (s->open_ports == 0) {
+ immediately_done = 1;
+ }
+ for (sp = s->head; sp; sp = sp->next) {
+ close_listener(sp);
+ }
+
+ if (immediately_done) {
+ finish_shutdown(s);
+ }
+}
+
+static void tcp_server_unref(grpc_tcp_server* s) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ 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::Get()->Flush();
- tcp_server_destroy(s);
- }
-}
-
-static void finish_accept(grpc_tcp_listener* sp, grpc_custom_socket* socket) {
- grpc_tcp_server_acceptor* acceptor =
- (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor));
- grpc_endpoint* ep = nullptr;
- grpc_resolved_address peer_name;
+ grpc_core::ExecCtx::Get()->Flush();
+ tcp_server_destroy(s);
+ }
+}
+
+static void finish_accept(grpc_tcp_listener* sp, grpc_custom_socket* socket) {
+ grpc_tcp_server_acceptor* acceptor =
+ (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor));
+ grpc_endpoint* ep = nullptr;
+ grpc_resolved_address peer_name;
TString peer_name_string;
- grpc_error* err;
-
- memset(&peer_name, 0, sizeof(grpc_resolved_address));
- peer_name.len = GRPC_MAX_SOCKADDR_SIZE;
- err = grpc_custom_socket_vtable->getpeername(
- socket, (grpc_sockaddr*)&peer_name.addr, (int*)&peer_name.len);
- if (err == GRPC_ERROR_NONE) {
- peer_name_string = grpc_sockaddr_to_uri(&peer_name);
- } else {
- GRPC_LOG_IF_ERROR("getpeername error", err);
- GRPC_ERROR_UNREF(err);
- }
+ grpc_error* err;
+
+ memset(&peer_name, 0, sizeof(grpc_resolved_address));
+ peer_name.len = GRPC_MAX_SOCKADDR_SIZE;
+ err = grpc_custom_socket_vtable->getpeername(
+ socket, (grpc_sockaddr*)&peer_name.addr, (int*)&peer_name.len);
+ if (err == GRPC_ERROR_NONE) {
+ peer_name_string = grpc_sockaddr_to_uri(&peer_name);
+ } else {
+ GRPC_LOG_IF_ERROR("getpeername error", err);
+ GRPC_ERROR_UNREF(err);
+ }
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());
- }
- ep = custom_tcp_endpoint_create(socket, sp->server->resource_quota,
+ }
+ ep = custom_tcp_endpoint_create(socket, sp->server->resource_quota,
peer_name_string.c_str());
- acceptor->from_server = sp->server;
- acceptor->port_index = sp->port_index;
- acceptor->fd_index = 0;
+ acceptor->from_server = sp->server;
+ acceptor->port_index = sp->port_index;
+ acceptor->fd_index = 0;
acceptor->external_connection = false;
- sp->server->on_accept_cb(sp->server->on_accept_cb_arg, ep, nullptr, acceptor);
-}
-
-static void custom_accept_callback(grpc_custom_socket* socket,
- grpc_custom_socket* client,
- grpc_error* error);
-
-static void custom_accept_callback(grpc_custom_socket* socket,
- grpc_custom_socket* client,
- grpc_error* error) {
+ sp->server->on_accept_cb(sp->server->on_accept_cb_arg, ep, nullptr, acceptor);
+}
+
+static void custom_accept_callback(grpc_custom_socket* socket,
+ grpc_custom_socket* client,
+ grpc_error* error);
+
+static void custom_accept_callback(grpc_custom_socket* socket,
+ grpc_custom_socket* client,
+ grpc_error* error) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_tcp_listener* sp = socket->listener;
- if (error != GRPC_ERROR_NONE) {
- if (!sp->closed) {
- gpr_log(GPR_ERROR, "Accept failed: %s", grpc_error_string(error));
- }
- gpr_free(client);
- GRPC_ERROR_UNREF(error);
- return;
- }
- finish_accept(sp, client);
- if (!sp->closed) {
- grpc_custom_socket* new_socket =
- (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
- new_socket->endpoint = nullptr;
- new_socket->listener = nullptr;
- new_socket->connector = nullptr;
- new_socket->refs = 1;
- grpc_custom_socket_vtable->accept(sp->socket, new_socket,
- custom_accept_callback);
- }
-}
-
-static grpc_error* add_socket_to_server(grpc_tcp_server* s,
- grpc_custom_socket* socket,
- const grpc_resolved_address* addr,
- unsigned port_index,
- grpc_tcp_listener** listener) {
- grpc_tcp_listener* sp = nullptr;
- int port = -1;
- grpc_error* error;
- grpc_resolved_address sockname_temp;
-
+ grpc_core::ExecCtx exec_ctx;
+ grpc_tcp_listener* sp = socket->listener;
+ if (error != GRPC_ERROR_NONE) {
+ if (!sp->closed) {
+ gpr_log(GPR_ERROR, "Accept failed: %s", grpc_error_string(error));
+ }
+ gpr_free(client);
+ GRPC_ERROR_UNREF(error);
+ return;
+ }
+ finish_accept(sp, client);
+ if (!sp->closed) {
+ grpc_custom_socket* new_socket =
+ (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
+ new_socket->endpoint = nullptr;
+ new_socket->listener = nullptr;
+ new_socket->connector = nullptr;
+ new_socket->refs = 1;
+ grpc_custom_socket_vtable->accept(sp->socket, new_socket,
+ custom_accept_callback);
+ }
+}
+
+static grpc_error* add_socket_to_server(grpc_tcp_server* s,
+ grpc_custom_socket* socket,
+ const grpc_resolved_address* addr,
+ unsigned port_index,
+ grpc_tcp_listener** listener) {
+ grpc_tcp_listener* sp = nullptr;
+ int port = -1;
+ grpc_error* error;
+ grpc_resolved_address sockname_temp;
+
// NOTE(lidiz) The last argument is "flags" which is unused by other
// implementations. Python IO managers uses it to specify SO_REUSEPORT.
int flags = 0;
@@ -290,188 +290,188 @@ static grpc_error* add_socket_to_server(grpc_tcp_server* s,
flags |= GRPC_CUSTOM_SOCKET_OPT_SO_REUSEPORT;
}
- error = grpc_custom_socket_vtable->bind(socket, (grpc_sockaddr*)addr->addr,
+ error = grpc_custom_socket_vtable->bind(socket, (grpc_sockaddr*)addr->addr,
addr->len, flags);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
-
- error = grpc_custom_socket_vtable->listen(socket);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
-
- sockname_temp.len = GRPC_MAX_SOCKADDR_SIZE;
- error = grpc_custom_socket_vtable->getsockname(
- socket, (grpc_sockaddr*)&sockname_temp.addr, (int*)&sockname_temp.len);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
-
- port = grpc_sockaddr_get_port(&sockname_temp);
-
- GPR_ASSERT(port >= 0);
- GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
- sp = (grpc_tcp_listener*)gpr_zalloc(sizeof(grpc_tcp_listener));
- sp->next = nullptr;
- if (s->head == nullptr) {
- s->head = sp;
- } else {
- s->tail->next = sp;
- }
- s->tail = sp;
- sp->server = s;
- sp->socket = socket;
- sp->port = port;
- sp->port_index = port_index;
- sp->closed = false;
- s->open_ports++;
- *listener = sp;
-
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
- const grpc_resolved_address* addr,
- int* port) {
- // This function is mostly copied from tcp_server_windows.c
- grpc_tcp_listener* sp = nullptr;
- grpc_custom_socket* socket;
- grpc_resolved_address addr6_v4mapped;
- grpc_resolved_address wildcard;
- grpc_resolved_address* allocated_addr = nullptr;
- grpc_resolved_address sockname_temp;
- unsigned port_index = 0;
- grpc_error* error = GRPC_ERROR_NONE;
- int family;
-
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
-
- if (s->tail != nullptr) {
- port_index = s->tail->port_index + 1;
- }
-
- /* Check if this is a wildcard port, and if so, try to keep the port the same
- as some previously created listener. */
- if (grpc_sockaddr_get_port(addr) == 0) {
- for (sp = s->head; sp; sp = sp->next) {
- socket = sp->socket;
- sockname_temp.len = GRPC_MAX_SOCKADDR_SIZE;
- if (nullptr == grpc_custom_socket_vtable->getsockname(
- socket, (grpc_sockaddr*)&sockname_temp.addr,
- (int*)&sockname_temp.len)) {
- *port = grpc_sockaddr_get_port(&sockname_temp);
- if (*port > 0) {
- allocated_addr =
- (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address));
- memcpy(allocated_addr, addr, sizeof(grpc_resolved_address));
- grpc_sockaddr_set_port(allocated_addr, *port);
- addr = allocated_addr;
- break;
- }
- }
- }
- }
-
- if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
- addr = &addr6_v4mapped;
- }
-
- /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
- if (grpc_sockaddr_is_wildcard(addr, port)) {
- grpc_sockaddr_make_wildcard6(*port, &wildcard);
-
- addr = &wildcard;
- }
-
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+
+ error = grpc_custom_socket_vtable->listen(socket);
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+
+ sockname_temp.len = GRPC_MAX_SOCKADDR_SIZE;
+ error = grpc_custom_socket_vtable->getsockname(
+ socket, (grpc_sockaddr*)&sockname_temp.addr, (int*)&sockname_temp.len);
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+
+ port = grpc_sockaddr_get_port(&sockname_temp);
+
+ GPR_ASSERT(port >= 0);
+ GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
+ sp = (grpc_tcp_listener*)gpr_zalloc(sizeof(grpc_tcp_listener));
+ sp->next = nullptr;
+ if (s->head == nullptr) {
+ s->head = sp;
+ } else {
+ s->tail->next = sp;
+ }
+ s->tail = sp;
+ sp->server = s;
+ sp->socket = socket;
+ sp->port = port;
+ sp->port_index = port_index;
+ sp->closed = false;
+ s->open_ports++;
+ *listener = sp;
+
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
+ const grpc_resolved_address* addr,
+ int* port) {
+ // This function is mostly copied from tcp_server_windows.c
+ grpc_tcp_listener* sp = nullptr;
+ grpc_custom_socket* socket;
+ grpc_resolved_address addr6_v4mapped;
+ grpc_resolved_address wildcard;
+ grpc_resolved_address* allocated_addr = nullptr;
+ grpc_resolved_address sockname_temp;
+ unsigned port_index = 0;
+ grpc_error* error = GRPC_ERROR_NONE;
+ int family;
+
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+
+ if (s->tail != nullptr) {
+ port_index = s->tail->port_index + 1;
+ }
+
+ /* Check if this is a wildcard port, and if so, try to keep the port the same
+ as some previously created listener. */
+ if (grpc_sockaddr_get_port(addr) == 0) {
+ for (sp = s->head; sp; sp = sp->next) {
+ socket = sp->socket;
+ sockname_temp.len = GRPC_MAX_SOCKADDR_SIZE;
+ if (nullptr == grpc_custom_socket_vtable->getsockname(
+ socket, (grpc_sockaddr*)&sockname_temp.addr,
+ (int*)&sockname_temp.len)) {
+ *port = grpc_sockaddr_get_port(&sockname_temp);
+ if (*port > 0) {
+ allocated_addr =
+ (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address));
+ memcpy(allocated_addr, addr, sizeof(grpc_resolved_address));
+ grpc_sockaddr_set_port(allocated_addr, *port);
+ addr = allocated_addr;
+ break;
+ }
+ }
+ }
+ }
+
+ if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
+ addr = &addr6_v4mapped;
+ }
+
+ /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
+ if (grpc_sockaddr_is_wildcard(addr, port)) {
+ grpc_sockaddr_make_wildcard6(*port, &wildcard);
+
+ addr = &wildcard;
+ }
+
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));
- }
-
- family = grpc_sockaddr_get_family(addr);
- socket = (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
- socket->refs = 1;
- socket->endpoint = nullptr;
- socket->listener = nullptr;
- socket->connector = nullptr;
+ }
+
+ family = grpc_sockaddr_get_family(addr);
+ socket = (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
+ socket->refs = 1;
+ socket->endpoint = nullptr;
+ socket->listener = nullptr;
+ socket->connector = nullptr;
error = grpc_custom_socket_vtable->init(socket, family);
-
- if (error == GRPC_ERROR_NONE) {
- error = add_socket_to_server(s, socket, addr, port_index, &sp);
- }
- gpr_free(allocated_addr);
-
- if (error != GRPC_ERROR_NONE) {
- grpc_error* error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Failed to add port to server", &error, 1);
- GRPC_ERROR_UNREF(error);
- error = error_out;
- *port = -1;
- } else {
- GPR_ASSERT(sp != nullptr);
- *port = sp->port;
- }
- socket->listener = sp;
- return error;
-}
-
+
+ if (error == GRPC_ERROR_NONE) {
+ error = add_socket_to_server(s, socket, addr, port_index, &sp);
+ }
+ gpr_free(allocated_addr);
+
+ if (error != GRPC_ERROR_NONE) {
+ grpc_error* error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Failed to add port to server", &error, 1);
+ GRPC_ERROR_UNREF(error);
+ error = error_out;
+ *port = -1;
+ } else {
+ GPR_ASSERT(sp != nullptr);
+ *port = sp->port;
+ }
+ socket->listener = sp;
+ return error;
+}
+
static void tcp_server_start(grpc_tcp_server* server,
const std::vector<grpc_pollset*>* /*pollsets*/,
- grpc_tcp_server_cb on_accept_cb, void* cb_arg) {
- grpc_tcp_listener* sp;
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ 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)) {
- gpr_log(GPR_INFO, "SERVER_START %p", server);
- }
- GPR_ASSERT(on_accept_cb);
- GPR_ASSERT(!server->on_accept_cb);
- server->on_accept_cb = on_accept_cb;
- server->on_accept_cb_arg = cb_arg;
- for (sp = server->head; sp; sp = sp->next) {
- grpc_custom_socket* new_socket =
- (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
- new_socket->endpoint = nullptr;
- new_socket->listener = nullptr;
- new_socket->connector = nullptr;
- new_socket->refs = 1;
- grpc_custom_socket_vtable->accept(sp->socket, new_socket,
- custom_accept_callback);
- }
-}
-
+ gpr_log(GPR_INFO, "SERVER_START %p", server);
+ }
+ GPR_ASSERT(on_accept_cb);
+ GPR_ASSERT(!server->on_accept_cb);
+ server->on_accept_cb = on_accept_cb;
+ server->on_accept_cb_arg = cb_arg;
+ for (sp = server->head; sp; sp = sp->next) {
+ grpc_custom_socket* new_socket =
+ (grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
+ new_socket->endpoint = nullptr;
+ new_socket->listener = nullptr;
+ new_socket->connector = nullptr;
+ new_socket->refs = 1;
+ grpc_custom_socket_vtable->accept(sp->socket, new_socket,
+ custom_accept_callback);
+ }
+}
+
static unsigned tcp_server_port_fd_count(grpc_tcp_server* /*s*/,
unsigned /*port_index*/) {
- return 0;
-}
-
+ return 0;
+}
+
static int tcp_server_port_fd(grpc_tcp_server* /*s*/, unsigned /*port_index*/,
unsigned /*fd_index*/) {
- return -1;
-}
-
-static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {
- for (grpc_tcp_listener* sp = s->head; sp; sp = sp->next) {
- if (!sp->closed) {
- sp->closed = true;
- grpc_custom_socket_vtable->close(sp->socket, custom_close_callback);
- }
- }
-}
-
+ return -1;
+}
+
+static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {
+ for (grpc_tcp_listener* sp = s->head; sp; sp = sp->next) {
+ if (!sp->closed) {
+ sp->closed = true;
+ grpc_custom_socket_vtable->close(sp->socket, custom_close_callback);
+ }
+ }
+}
+
static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
grpc_tcp_server* /*s*/) {
return nullptr;
}
-grpc_tcp_server_vtable custom_tcp_server_vtable = {
+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};
-
-#ifdef GRPC_UV_TEST
-grpc_tcp_server_vtable* default_tcp_server_vtable = &custom_tcp_server_vtable;
-#endif
+
+#ifdef GRPC_UV_TEST
+grpc_tcp_server_vtable* default_tcp_server_vtable = &custom_tcp_server_vtable;
+#endif
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 b3f3febe635..672c6573f18 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
@@ -1,228 +1,228 @@
-/*
- *
- * 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.
- *
- */
-
-/* FIXME: "posix" files shouldn't be depending on _GNU_SOURCE */
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/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.
+ *
+ */
+
+/* FIXME: "posix" files shouldn't be depending on _GNU_SOURCE */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_TCP_SERVER
-
-#include <errno.h>
-#include <fcntl.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
+
+#include <errno.h>
+#include <fcntl.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.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/channel/channel_args.h"
-#include "src/core/lib/gpr/string.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/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/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/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_utils_posix.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
-
-static grpc_error* tcp_server_create(grpc_closure* shutdown_complete,
- const grpc_channel_args* args,
- grpc_tcp_server** server) {
- grpc_tcp_server* s =
- static_cast<grpc_tcp_server*>(gpr_zalloc(sizeof(grpc_tcp_server)));
- s->so_reuseport = grpc_is_socket_reuse_port_supported();
- s->expand_wildcard_addrs = false;
- for (size_t i = 0; i < (args == nullptr ? 0 : args->num_args); i++) {
- if (0 == strcmp(GRPC_ARG_ALLOW_REUSEPORT, args->args[i].key)) {
- if (args->args[i].type == GRPC_ARG_INTEGER) {
- s->so_reuseport = grpc_is_socket_reuse_port_supported() &&
- (args->args[i].value.integer != 0);
- } else {
- gpr_free(s);
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(GRPC_ARG_ALLOW_REUSEPORT
- " must be an integer");
- }
- } else if (0 == strcmp(GRPC_ARG_EXPAND_WILDCARD_ADDRS, args->args[i].key)) {
- if (args->args[i].type == GRPC_ARG_INTEGER) {
- s->expand_wildcard_addrs = (args->args[i].value.integer != 0);
- } else {
- gpr_free(s);
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- GRPC_ARG_EXPAND_WILDCARD_ADDRS " must be an integer");
- }
- }
- }
- gpr_ref_init(&s->refs, 1);
- gpr_mu_init(&s->mu);
- s->active_ports = 0;
- s->destroyed_ports = 0;
- s->shutdown = false;
- s->shutdown_starting.head = nullptr;
- s->shutdown_starting.tail = nullptr;
- s->shutdown_complete = shutdown_complete;
- s->on_accept_cb = nullptr;
- s->on_accept_cb_arg = nullptr;
- s->head = nullptr;
- s->tail = nullptr;
- s->nports = 0;
- s->channel_args = grpc_channel_args_copy(args);
+#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
+
+static grpc_error* tcp_server_create(grpc_closure* shutdown_complete,
+ const grpc_channel_args* args,
+ grpc_tcp_server** server) {
+ grpc_tcp_server* s =
+ static_cast<grpc_tcp_server*>(gpr_zalloc(sizeof(grpc_tcp_server)));
+ s->so_reuseport = grpc_is_socket_reuse_port_supported();
+ s->expand_wildcard_addrs = false;
+ for (size_t i = 0; i < (args == nullptr ? 0 : args->num_args); i++) {
+ if (0 == strcmp(GRPC_ARG_ALLOW_REUSEPORT, args->args[i].key)) {
+ if (args->args[i].type == GRPC_ARG_INTEGER) {
+ s->so_reuseport = grpc_is_socket_reuse_port_supported() &&
+ (args->args[i].value.integer != 0);
+ } else {
+ gpr_free(s);
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(GRPC_ARG_ALLOW_REUSEPORT
+ " must be an integer");
+ }
+ } else if (0 == strcmp(GRPC_ARG_EXPAND_WILDCARD_ADDRS, args->args[i].key)) {
+ if (args->args[i].type == GRPC_ARG_INTEGER) {
+ s->expand_wildcard_addrs = (args->args[i].value.integer != 0);
+ } else {
+ gpr_free(s);
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ GRPC_ARG_EXPAND_WILDCARD_ADDRS " must be an integer");
+ }
+ }
+ }
+ gpr_ref_init(&s->refs, 1);
+ gpr_mu_init(&s->mu);
+ s->active_ports = 0;
+ s->destroyed_ports = 0;
+ s->shutdown = false;
+ s->shutdown_starting.head = nullptr;
+ s->shutdown_starting.tail = nullptr;
+ s->shutdown_complete = shutdown_complete;
+ s->on_accept_cb = nullptr;
+ s->on_accept_cb_arg = nullptr;
+ s->head = nullptr;
+ s->tail = nullptr;
+ s->nports = 0;
+ s->channel_args = grpc_channel_args_copy(args);
s->fd_handler = nullptr;
- gpr_atm_no_barrier_store(&s->next_pollset_to_assign, 0);
- *server = s;
- return GRPC_ERROR_NONE;
-}
-
-static void finish_shutdown(grpc_tcp_server* s) {
- gpr_mu_lock(&s->mu);
- GPR_ASSERT(s->shutdown);
- gpr_mu_unlock(&s->mu);
- if (s->shutdown_complete != nullptr) {
+ gpr_atm_no_barrier_store(&s->next_pollset_to_assign, 0);
+ *server = s;
+ return GRPC_ERROR_NONE;
+}
+
+static void finish_shutdown(grpc_tcp_server* s) {
+ gpr_mu_lock(&s->mu);
+ 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);
- }
-
- gpr_mu_destroy(&s->mu);
-
- while (s->head) {
- grpc_tcp_listener* sp = s->head;
- s->head = sp->next;
- gpr_free(sp);
- }
- grpc_channel_args_destroy(s->channel_args);
+ }
+
+ gpr_mu_destroy(&s->mu);
+
+ while (s->head) {
+ grpc_tcp_listener* sp = s->head;
+ s->head = sp->next;
+ gpr_free(sp);
+ }
+ grpc_channel_args_destroy(s->channel_args);
delete s->fd_handler;
-
- gpr_free(s);
-}
-
+
+ gpr_free(s);
+}
+
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++;
- if (s->destroyed_ports == s->nports) {
- gpr_mu_unlock(&s->mu);
- finish_shutdown(s);
- } else {
- GPR_ASSERT(s->destroyed_ports < s->nports);
- gpr_mu_unlock(&s->mu);
- }
-}
-
-/* called when all listening endpoints have been shutdown, so no further
- events will be received on them - at this point it's safe to destroy
- things */
-static void deactivated_all_ports(grpc_tcp_server* s) {
- /* delete ALL the things */
- gpr_mu_lock(&s->mu);
-
- GPR_ASSERT(s->shutdown);
-
- if (s->head) {
- grpc_tcp_listener* sp;
- for (sp = s->head; sp; sp = sp->next) {
- grpc_unlink_if_unix_domain_socket(&sp->addr);
- GRPC_CLOSURE_INIT(&sp->destroyed_closure, destroyed_port, s,
- grpc_schedule_on_exec_ctx);
- grpc_fd_orphan(sp->emfd, &sp->destroyed_closure, nullptr,
+ grpc_tcp_server* s = static_cast<grpc_tcp_server*>(server);
+ gpr_mu_lock(&s->mu);
+ s->destroyed_ports++;
+ if (s->destroyed_ports == s->nports) {
+ gpr_mu_unlock(&s->mu);
+ finish_shutdown(s);
+ } else {
+ GPR_ASSERT(s->destroyed_ports < s->nports);
+ gpr_mu_unlock(&s->mu);
+ }
+}
+
+/* called when all listening endpoints have been shutdown, so no further
+ events will be received on them - at this point it's safe to destroy
+ things */
+static void deactivated_all_ports(grpc_tcp_server* s) {
+ /* delete ALL the things */
+ gpr_mu_lock(&s->mu);
+
+ GPR_ASSERT(s->shutdown);
+
+ if (s->head) {
+ grpc_tcp_listener* sp;
+ for (sp = s->head; sp; sp = sp->next) {
+ grpc_unlink_if_unix_domain_socket(&sp->addr);
+ GRPC_CLOSURE_INIT(&sp->destroyed_closure, destroyed_port, s,
+ grpc_schedule_on_exec_ctx);
+ grpc_fd_orphan(sp->emfd, &sp->destroyed_closure, nullptr,
"tcp_listener_shutdown");
- }
- gpr_mu_unlock(&s->mu);
- } else {
- gpr_mu_unlock(&s->mu);
- finish_shutdown(s);
- }
-}
-
-static void tcp_server_destroy(grpc_tcp_server* s) {
- gpr_mu_lock(&s->mu);
-
- GPR_ASSERT(!s->shutdown);
- s->shutdown = true;
-
- /* shutdown all fd's */
- if (s->active_ports) {
- grpc_tcp_listener* sp;
- for (sp = s->head; sp; sp = sp->next) {
- grpc_fd_shutdown(
- sp->emfd, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server destroyed"));
- }
- gpr_mu_unlock(&s->mu);
- } else {
- gpr_mu_unlock(&s->mu);
- deactivated_all_ports(s);
- }
-}
-
-/* event manager callback when reads are ready */
-static void on_read(void* arg, grpc_error* err) {
- grpc_tcp_listener* sp = static_cast<grpc_tcp_listener*>(arg);
- grpc_pollset* read_notifier_pollset;
- if (err != GRPC_ERROR_NONE) {
- goto error;
- }
-
- /* loop until accept4 returns EAGAIN, and then re-arm notification */
- for (;;) {
- grpc_resolved_address addr;
- memset(&addr, 0, sizeof(addr));
- addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
- /* Note: If we ever decide to return this address to the user, remember to
- strip off the ::ffff:0.0.0.0/96 prefix first. */
- int fd = grpc_accept4(sp->fd, &addr, 1, 1);
- if (fd < 0) {
- switch (errno) {
- case EINTR:
- continue;
- case EAGAIN:
- grpc_fd_notify_on_read(sp->emfd, &sp->read_closure);
- return;
- default:
- gpr_mu_lock(&sp->server->mu);
- if (!sp->server->shutdown_listeners) {
- gpr_log(GPR_ERROR, "Failed accept4: %s", strerror(errno));
- } else {
- /* if we have shutdown listeners, accept4 could fail, and we
- needn't notify users */
- }
- gpr_mu_unlock(&sp->server->mu);
- goto error;
- }
- }
-
+ }
+ gpr_mu_unlock(&s->mu);
+ } else {
+ gpr_mu_unlock(&s->mu);
+ finish_shutdown(s);
+ }
+}
+
+static void tcp_server_destroy(grpc_tcp_server* s) {
+ gpr_mu_lock(&s->mu);
+
+ GPR_ASSERT(!s->shutdown);
+ s->shutdown = true;
+
+ /* shutdown all fd's */
+ if (s->active_ports) {
+ grpc_tcp_listener* sp;
+ for (sp = s->head; sp; sp = sp->next) {
+ grpc_fd_shutdown(
+ sp->emfd, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server destroyed"));
+ }
+ gpr_mu_unlock(&s->mu);
+ } else {
+ gpr_mu_unlock(&s->mu);
+ deactivated_all_ports(s);
+ }
+}
+
+/* event manager callback when reads are ready */
+static void on_read(void* arg, grpc_error* err) {
+ grpc_tcp_listener* sp = static_cast<grpc_tcp_listener*>(arg);
+ grpc_pollset* read_notifier_pollset;
+ if (err != GRPC_ERROR_NONE) {
+ goto error;
+ }
+
+ /* loop until accept4 returns EAGAIN, and then re-arm notification */
+ for (;;) {
+ grpc_resolved_address addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
+ /* Note: If we ever decide to return this address to the user, remember to
+ strip off the ::ffff:0.0.0.0/96 prefix first. */
+ int fd = grpc_accept4(sp->fd, &addr, 1, 1);
+ if (fd < 0) {
+ switch (errno) {
+ case EINTR:
+ continue;
+ case EAGAIN:
+ grpc_fd_notify_on_read(sp->emfd, &sp->read_closure);
+ return;
+ default:
+ gpr_mu_lock(&sp->server->mu);
+ if (!sp->server->shutdown_listeners) {
+ gpr_log(GPR_ERROR, "Failed accept4: %s", strerror(errno));
+ } else {
+ /* if we have shutdown listeners, accept4 could fail, and we
+ needn't notify users */
+ }
+ gpr_mu_unlock(&sp->server->mu);
+ 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)) {
@@ -236,335 +236,335 @@ static void on_read(void* arg, grpc_error* err) {
}
}
- grpc_set_socket_no_sigpipe_if_possible(fd);
-
+ grpc_set_socket_no_sigpipe_if_possible(fd);
+
TString addr_str = grpc_sockaddr_to_uri(&addr);
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "SERVER_CONNECT: incoming 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 = (*(sp->server->pollsets))
[static_cast<size_t>(gpr_atm_no_barrier_fetch_add(
&sp->server->next_pollset_to_assign, 1)) %
sp->server->pollsets->size()];
- grpc_pollset_add_fd(read_notifier_pollset, fdobj);
-
- // Create acceptor.
- grpc_tcp_server_acceptor* acceptor =
- static_cast<grpc_tcp_server_acceptor*>(gpr_malloc(sizeof(*acceptor)));
- acceptor->from_server = sp->server;
- acceptor->port_index = sp->port_index;
- acceptor->fd_index = sp->fd_index;
+ grpc_pollset_add_fd(read_notifier_pollset, fdobj);
+
+ // Create acceptor.
+ grpc_tcp_server_acceptor* acceptor =
+ static_cast<grpc_tcp_server_acceptor*>(gpr_malloc(sizeof(*acceptor)));
+ acceptor->from_server = sp->server;
+ acceptor->port_index = sp->port_index;
+ acceptor->fd_index = sp->fd_index;
acceptor->external_connection = false;
-
- sp->server->on_accept_cb(
- sp->server->on_accept_cb_arg,
+
+ sp->server->on_accept_cb(
+ sp->server->on_accept_cb_arg,
grpc_tcp_create(fdobj, sp->server->channel_args, addr_str.c_str()),
- read_notifier_pollset, acceptor);
- }
-
- GPR_UNREACHABLE_CODE(return );
-
-error:
- gpr_mu_lock(&sp->server->mu);
- if (0 == --sp->server->active_ports && sp->server->shutdown) {
- gpr_mu_unlock(&sp->server->mu);
- deactivated_all_ports(sp->server);
- } else {
- gpr_mu_unlock(&sp->server->mu);
- }
-}
-
-/* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
-static grpc_error* add_wildcard_addrs_to_server(grpc_tcp_server* s,
- unsigned port_index,
- int requested_port,
- int* out_port) {
- grpc_resolved_address wild4;
- grpc_resolved_address wild6;
- unsigned fd_index = 0;
- grpc_dualstack_mode dsmode;
- grpc_tcp_listener* sp = nullptr;
- grpc_tcp_listener* sp2 = nullptr;
- grpc_error* v6_err = GRPC_ERROR_NONE;
- grpc_error* v4_err = GRPC_ERROR_NONE;
- *out_port = -1;
-
- if (grpc_tcp_server_have_ifaddrs() && s->expand_wildcard_addrs) {
- return grpc_tcp_server_add_all_local_addrs(s, port_index, requested_port,
- out_port);
- }
-
- grpc_sockaddr_make_wildcards(requested_port, &wild4, &wild6);
- /* Try listening on IPv6 first. */
- if ((v6_err = grpc_tcp_server_add_addr(s, &wild6, port_index, fd_index,
- &dsmode, &sp)) == GRPC_ERROR_NONE) {
- ++fd_index;
- requested_port = *out_port = sp->port;
- if (dsmode == GRPC_DSMODE_DUALSTACK || dsmode == GRPC_DSMODE_IPV4) {
- return GRPC_ERROR_NONE;
- }
- }
- /* If we got a v6-only socket or nothing, try adding 0.0.0.0. */
- grpc_sockaddr_set_port(&wild4, requested_port);
- if ((v4_err = grpc_tcp_server_add_addr(s, &wild4, port_index, fd_index,
- &dsmode, &sp2)) == GRPC_ERROR_NONE) {
- *out_port = sp2->port;
- if (sp != nullptr) {
- sp2->is_sibling = 1;
- sp->sibling = sp2;
- }
- }
- if (*out_port > 0) {
- if (v6_err != GRPC_ERROR_NONE) {
- gpr_log(GPR_INFO,
- "Failed to add :: listener, "
- "the environment may not support IPv6: %s",
- grpc_error_string(v6_err));
- GRPC_ERROR_UNREF(v6_err);
- }
- if (v4_err != GRPC_ERROR_NONE) {
- gpr_log(GPR_INFO,
- "Failed to add 0.0.0.0 listener, "
- "the environment may not support IPv4: %s",
- grpc_error_string(v4_err));
- GRPC_ERROR_UNREF(v4_err);
- }
- return GRPC_ERROR_NONE;
- } else {
- grpc_error* root_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Failed to add any wildcard listeners");
- GPR_ASSERT(v6_err != GRPC_ERROR_NONE && v4_err != GRPC_ERROR_NONE);
- root_err = grpc_error_add_child(root_err, v6_err);
- root_err = grpc_error_add_child(root_err, v4_err);
- return root_err;
- }
-}
-
-static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) {
- grpc_tcp_listener* sp = nullptr;
+ read_notifier_pollset, acceptor);
+ }
+
+ GPR_UNREACHABLE_CODE(return );
+
+error:
+ gpr_mu_lock(&sp->server->mu);
+ if (0 == --sp->server->active_ports && sp->server->shutdown) {
+ gpr_mu_unlock(&sp->server->mu);
+ deactivated_all_ports(sp->server);
+ } else {
+ gpr_mu_unlock(&sp->server->mu);
+ }
+}
+
+/* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
+static grpc_error* add_wildcard_addrs_to_server(grpc_tcp_server* s,
+ unsigned port_index,
+ int requested_port,
+ int* out_port) {
+ grpc_resolved_address wild4;
+ grpc_resolved_address wild6;
+ unsigned fd_index = 0;
+ grpc_dualstack_mode dsmode;
+ grpc_tcp_listener* sp = nullptr;
+ grpc_tcp_listener* sp2 = nullptr;
+ grpc_error* v6_err = GRPC_ERROR_NONE;
+ grpc_error* v4_err = GRPC_ERROR_NONE;
+ *out_port = -1;
+
+ if (grpc_tcp_server_have_ifaddrs() && s->expand_wildcard_addrs) {
+ return grpc_tcp_server_add_all_local_addrs(s, port_index, requested_port,
+ out_port);
+ }
+
+ grpc_sockaddr_make_wildcards(requested_port, &wild4, &wild6);
+ /* Try listening on IPv6 first. */
+ if ((v6_err = grpc_tcp_server_add_addr(s, &wild6, port_index, fd_index,
+ &dsmode, &sp)) == GRPC_ERROR_NONE) {
+ ++fd_index;
+ requested_port = *out_port = sp->port;
+ if (dsmode == GRPC_DSMODE_DUALSTACK || dsmode == GRPC_DSMODE_IPV4) {
+ return GRPC_ERROR_NONE;
+ }
+ }
+ /* If we got a v6-only socket or nothing, try adding 0.0.0.0. */
+ grpc_sockaddr_set_port(&wild4, requested_port);
+ if ((v4_err = grpc_tcp_server_add_addr(s, &wild4, port_index, fd_index,
+ &dsmode, &sp2)) == GRPC_ERROR_NONE) {
+ *out_port = sp2->port;
+ if (sp != nullptr) {
+ sp2->is_sibling = 1;
+ sp->sibling = sp2;
+ }
+ }
+ if (*out_port > 0) {
+ if (v6_err != GRPC_ERROR_NONE) {
+ gpr_log(GPR_INFO,
+ "Failed to add :: listener, "
+ "the environment may not support IPv6: %s",
+ grpc_error_string(v6_err));
+ GRPC_ERROR_UNREF(v6_err);
+ }
+ if (v4_err != GRPC_ERROR_NONE) {
+ gpr_log(GPR_INFO,
+ "Failed to add 0.0.0.0 listener, "
+ "the environment may not support IPv4: %s",
+ grpc_error_string(v4_err));
+ GRPC_ERROR_UNREF(v4_err);
+ }
+ return GRPC_ERROR_NONE;
+ } else {
+ grpc_error* root_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Failed to add any wildcard listeners");
+ GPR_ASSERT(v6_err != GRPC_ERROR_NONE && v4_err != GRPC_ERROR_NONE);
+ root_err = grpc_error_add_child(root_err, v6_err);
+ root_err = grpc_error_add_child(root_err, v4_err);
+ return root_err;
+ }
+}
+
+static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) {
+ grpc_tcp_listener* sp = nullptr;
TString addr_str;
- grpc_error* err;
-
- for (grpc_tcp_listener* l = listener->next; l && l->is_sibling; l = l->next) {
- l->fd_index += count;
- }
-
- for (unsigned i = 0; i < count; i++) {
- int fd = -1;
- int port = -1;
- grpc_dualstack_mode dsmode;
- err = grpc_create_dualstack_socket(&listener->addr, SOCK_STREAM, 0, &dsmode,
- &fd);
- if (err != GRPC_ERROR_NONE) return err;
+ grpc_error* err;
+
+ for (grpc_tcp_listener* l = listener->next; l && l->is_sibling; l = l->next) {
+ l->fd_index += count;
+ }
+
+ for (unsigned i = 0; i < count; i++) {
+ int fd = -1;
+ int port = -1;
+ grpc_dualstack_mode dsmode;
+ err = grpc_create_dualstack_socket(&listener->addr, SOCK_STREAM, 0, &dsmode,
+ &fd);
+ if (err != GRPC_ERROR_NONE) return err;
err = grpc_tcp_server_prepare_socket(listener->server, fd, &listener->addr,
true, &port);
- if (err != GRPC_ERROR_NONE) return err;
- listener->server->nports++;
+ if (err != GRPC_ERROR_NONE) return err;
+ listener->server->nports++;
addr_str = grpc_sockaddr_to_string(&listener->addr, true);
- sp = static_cast<grpc_tcp_listener*>(gpr_malloc(sizeof(grpc_tcp_listener)));
- sp->next = listener->next;
- listener->next = sp;
- /* sp (the new listener) is a sibling of 'listener' (the original
- listener). */
- sp->is_sibling = 1;
- sp->sibling = listener->sibling;
- listener->sibling = sp;
- sp->server = listener->server;
- sp->fd = fd;
+ sp = static_cast<grpc_tcp_listener*>(gpr_malloc(sizeof(grpc_tcp_listener)));
+ sp->next = listener->next;
+ listener->next = sp;
+ /* sp (the new listener) is a sibling of 'listener' (the original
+ listener). */
+ sp->is_sibling = 1;
+ sp->sibling = listener->sibling;
+ listener->sibling = sp;
+ sp->server = listener->server;
+ sp->fd = fd;
sp->emfd = grpc_fd_create(
fd,
y_absl::StrFormat("tcp-server-listener:%s/clone-%d", addr_str.c_str(), i)
.c_str(),
true);
- memcpy(&sp->addr, &listener->addr, sizeof(grpc_resolved_address));
- sp->port = port;
- sp->port_index = listener->port_index;
- sp->fd_index = listener->fd_index + count - i;
- GPR_ASSERT(sp->emfd);
- while (listener->server->tail->next != nullptr) {
- listener->server->tail = listener->server->tail->next;
- }
- }
-
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
- const grpc_resolved_address* addr,
- int* out_port) {
- grpc_tcp_listener* sp;
- grpc_resolved_address sockname_temp;
- grpc_resolved_address addr6_v4mapped;
- int requested_port = grpc_sockaddr_get_port(addr);
- unsigned port_index = 0;
- grpc_dualstack_mode dsmode;
- grpc_error* err;
- *out_port = -1;
- if (s->tail != nullptr) {
- port_index = s->tail->port_index + 1;
- }
- grpc_unlink_if_unix_domain_socket(addr);
-
- /* Check if this is a wildcard port, and if so, try to keep the port the same
- as some previously created listener. */
- if (requested_port == 0) {
- for (sp = s->head; sp; sp = sp->next) {
- sockname_temp.len =
- static_cast<socklen_t>(sizeof(struct sockaddr_storage));
- if (0 ==
- getsockname(sp->fd,
- reinterpret_cast<grpc_sockaddr*>(&sockname_temp.addr),
- &sockname_temp.len)) {
- int used_port = grpc_sockaddr_get_port(&sockname_temp);
- if (used_port > 0) {
- memcpy(&sockname_temp, addr, sizeof(grpc_resolved_address));
- grpc_sockaddr_set_port(&sockname_temp, used_port);
- requested_port = used_port;
- addr = &sockname_temp;
- break;
- }
- }
- }
- }
- if (grpc_sockaddr_is_wildcard(addr, &requested_port)) {
- return add_wildcard_addrs_to_server(s, port_index, requested_port,
- out_port);
- }
- if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
- addr = &addr6_v4mapped;
- }
- if ((err = grpc_tcp_server_add_addr(s, addr, port_index, 0, &dsmode, &sp)) ==
- GRPC_ERROR_NONE) {
- *out_port = sp->port;
- }
- return err;
-}
-
-/* Return listener at port_index or NULL. Should only be called with s->mu
- locked. */
-static grpc_tcp_listener* get_port_index(grpc_tcp_server* s,
- unsigned port_index) {
- unsigned num_ports = 0;
- grpc_tcp_listener* sp;
- for (sp = s->head; sp; sp = sp->next) {
- if (!sp->is_sibling) {
- if (++num_ports > port_index) {
- return sp;
- }
- }
- }
- return nullptr;
-}
-
-unsigned tcp_server_port_fd_count(grpc_tcp_server* s, unsigned port_index) {
- unsigned num_fds = 0;
- gpr_mu_lock(&s->mu);
- grpc_tcp_listener* sp = get_port_index(s, port_index);
- for (; sp; sp = sp->sibling) {
- ++num_fds;
- }
- gpr_mu_unlock(&s->mu);
- return num_fds;
-}
-
-static int tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
- unsigned fd_index) {
- gpr_mu_lock(&s->mu);
- grpc_tcp_listener* sp = get_port_index(s, port_index);
- for (; sp; sp = sp->sibling, --fd_index) {
- if (fd_index == 0) {
- gpr_mu_unlock(&s->mu);
- return sp->fd;
- }
- }
- gpr_mu_unlock(&s->mu);
- return -1;
-}
-
+ memcpy(&sp->addr, &listener->addr, sizeof(grpc_resolved_address));
+ sp->port = port;
+ sp->port_index = listener->port_index;
+ sp->fd_index = listener->fd_index + count - i;
+ GPR_ASSERT(sp->emfd);
+ while (listener->server->tail->next != nullptr) {
+ listener->server->tail = listener->server->tail->next;
+ }
+ }
+
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
+ const grpc_resolved_address* addr,
+ int* out_port) {
+ grpc_tcp_listener* sp;
+ grpc_resolved_address sockname_temp;
+ grpc_resolved_address addr6_v4mapped;
+ int requested_port = grpc_sockaddr_get_port(addr);
+ unsigned port_index = 0;
+ grpc_dualstack_mode dsmode;
+ grpc_error* err;
+ *out_port = -1;
+ if (s->tail != nullptr) {
+ port_index = s->tail->port_index + 1;
+ }
+ grpc_unlink_if_unix_domain_socket(addr);
+
+ /* Check if this is a wildcard port, and if so, try to keep the port the same
+ as some previously created listener. */
+ if (requested_port == 0) {
+ for (sp = s->head; sp; sp = sp->next) {
+ sockname_temp.len =
+ static_cast<socklen_t>(sizeof(struct sockaddr_storage));
+ if (0 ==
+ getsockname(sp->fd,
+ reinterpret_cast<grpc_sockaddr*>(&sockname_temp.addr),
+ &sockname_temp.len)) {
+ int used_port = grpc_sockaddr_get_port(&sockname_temp);
+ if (used_port > 0) {
+ memcpy(&sockname_temp, addr, sizeof(grpc_resolved_address));
+ grpc_sockaddr_set_port(&sockname_temp, used_port);
+ requested_port = used_port;
+ addr = &sockname_temp;
+ break;
+ }
+ }
+ }
+ }
+ if (grpc_sockaddr_is_wildcard(addr, &requested_port)) {
+ return add_wildcard_addrs_to_server(s, port_index, requested_port,
+ out_port);
+ }
+ if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
+ addr = &addr6_v4mapped;
+ }
+ if ((err = grpc_tcp_server_add_addr(s, addr, port_index, 0, &dsmode, &sp)) ==
+ GRPC_ERROR_NONE) {
+ *out_port = sp->port;
+ }
+ return err;
+}
+
+/* Return listener at port_index or NULL. Should only be called with s->mu
+ locked. */
+static grpc_tcp_listener* get_port_index(grpc_tcp_server* s,
+ unsigned port_index) {
+ unsigned num_ports = 0;
+ grpc_tcp_listener* sp;
+ for (sp = s->head; sp; sp = sp->next) {
+ if (!sp->is_sibling) {
+ if (++num_ports > port_index) {
+ return sp;
+ }
+ }
+ }
+ return nullptr;
+}
+
+unsigned tcp_server_port_fd_count(grpc_tcp_server* s, unsigned port_index) {
+ unsigned num_fds = 0;
+ gpr_mu_lock(&s->mu);
+ grpc_tcp_listener* sp = get_port_index(s, port_index);
+ for (; sp; sp = sp->sibling) {
+ ++num_fds;
+ }
+ gpr_mu_unlock(&s->mu);
+ return num_fds;
+}
+
+static int tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index,
+ unsigned fd_index) {
+ gpr_mu_lock(&s->mu);
+ grpc_tcp_listener* sp = get_port_index(s, port_index);
+ for (; sp; sp = sp->sibling, --fd_index) {
+ if (fd_index == 0) {
+ gpr_mu_unlock(&s->mu);
+ return sp->fd;
+ }
+ }
+ gpr_mu_unlock(&s->mu);
+ return -1;
+}
+
static void tcp_server_start(grpc_tcp_server* s,
const std::vector<grpc_pollset*>* pollsets,
- grpc_tcp_server_cb on_accept_cb,
- void* on_accept_cb_arg) {
- size_t i;
- grpc_tcp_listener* sp;
- GPR_ASSERT(on_accept_cb);
- gpr_mu_lock(&s->mu);
- GPR_ASSERT(!s->on_accept_cb);
- GPR_ASSERT(s->active_ports == 0);
- s->on_accept_cb = on_accept_cb;
- s->on_accept_cb_arg = on_accept_cb_arg;
- s->pollsets = pollsets;
- sp = s->head;
- while (sp != nullptr) {
- if (s->so_reuseport && !grpc_is_unix_socket(&sp->addr) &&
+ grpc_tcp_server_cb on_accept_cb,
+ void* on_accept_cb_arg) {
+ size_t i;
+ grpc_tcp_listener* sp;
+ GPR_ASSERT(on_accept_cb);
+ gpr_mu_lock(&s->mu);
+ GPR_ASSERT(!s->on_accept_cb);
+ GPR_ASSERT(s->active_ports == 0);
+ s->on_accept_cb = on_accept_cb;
+ s->on_accept_cb_arg = on_accept_cb_arg;
+ s->pollsets = pollsets;
+ sp = s->head;
+ while (sp != nullptr) {
+ if (s->so_reuseport && !grpc_is_unix_socket(&sp->addr) &&
pollsets->size() > 1) {
- GPR_ASSERT(GRPC_LOG_IF_ERROR(
+ GPR_ASSERT(GRPC_LOG_IF_ERROR(
"clone_port", clone_port(sp, (unsigned)(pollsets->size() - 1))));
for (i = 0; i < pollsets->size(); i++) {
grpc_pollset_add_fd((*pollsets)[i], sp->emfd);
- GRPC_CLOSURE_INIT(&sp->read_closure, on_read, sp,
- grpc_schedule_on_exec_ctx);
- grpc_fd_notify_on_read(sp->emfd, &sp->read_closure);
- s->active_ports++;
- sp = sp->next;
- }
- } else {
+ GRPC_CLOSURE_INIT(&sp->read_closure, on_read, sp,
+ grpc_schedule_on_exec_ctx);
+ grpc_fd_notify_on_read(sp->emfd, &sp->read_closure);
+ s->active_ports++;
+ sp = sp->next;
+ }
+ } else {
for (i = 0; i < pollsets->size(); i++) {
grpc_pollset_add_fd((*pollsets)[i], sp->emfd);
- }
- GRPC_CLOSURE_INIT(&sp->read_closure, on_read, sp,
- grpc_schedule_on_exec_ctx);
- grpc_fd_notify_on_read(sp->emfd, &sp->read_closure);
- s->active_ports++;
- sp = sp->next;
- }
- }
- gpr_mu_unlock(&s->mu);
-}
-
-grpc_tcp_server* tcp_server_ref(grpc_tcp_server* s) {
- gpr_ref_non_zero(&s->refs);
- return s;
-}
-
-static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
- grpc_closure* shutdown_starting) {
- gpr_mu_lock(&s->mu);
- grpc_closure_list_append(&s->shutdown_starting, shutdown_starting,
- GRPC_ERROR_NONE);
- gpr_mu_unlock(&s->mu);
-}
-
-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_CLOSURE_INIT(&sp->read_closure, on_read, sp,
+ grpc_schedule_on_exec_ctx);
+ grpc_fd_notify_on_read(sp->emfd, &sp->read_closure);
+ s->active_ports++;
+ sp = sp->next;
+ }
+ }
+ gpr_mu_unlock(&s->mu);
+}
+
+grpc_tcp_server* tcp_server_ref(grpc_tcp_server* s) {
+ gpr_ref_non_zero(&s->refs);
+ return s;
+}
+
+static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
+ grpc_closure* shutdown_starting) {
+ gpr_mu_lock(&s->mu);
+ grpc_closure_list_append(&s->shutdown_starting, shutdown_starting,
+ GRPC_ERROR_NONE);
+ gpr_mu_unlock(&s->mu);
+}
+
+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);
- gpr_mu_unlock(&s->mu);
- tcp_server_destroy(s);
- }
-}
-
-static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {
- gpr_mu_lock(&s->mu);
- s->shutdown_listeners = true;
- /* shutdown all fd's */
- if (s->active_ports) {
- grpc_tcp_listener* sp;
- for (sp = s->head; sp; sp = sp->next) {
- grpc_fd_shutdown(sp->emfd,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server shutdown"));
- }
- }
- gpr_mu_unlock(&s->mu);
-}
-
+ gpr_mu_unlock(&s->mu);
+ tcp_server_destroy(s);
+ }
+}
+
+static void tcp_server_shutdown_listeners(grpc_tcp_server* s) {
+ gpr_mu_lock(&s->mu);
+ s->shutdown_listeners = true;
+ /* shutdown all fd's */
+ if (s->active_ports) {
+ grpc_tcp_listener* sp;
+ for (sp = s->head; sp; sp = sp->next) {
+ grpc_fd_shutdown(sp->emfd,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server shutdown"));
+ }
+ }
+ gpr_mu_unlock(&s->mu);
+}
+
namespace {
class ExternalConnectionHandler : public grpc_core::TcpServerFdHandler {
public:
@@ -621,7 +621,7 @@ static grpc_core::TcpServerFdHandler* tcp_server_create_fd_handler(
return s->fd_handler;
}
-grpc_tcp_server_vtable grpc_posix_tcp_server_vtable = {
+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,
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 6b8a5f9f207..d5ace42c329 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
@@ -1,124 +1,124 @@
-/*
- *
- * 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_IOMGR_TCP_SERVER_UTILS_POSIX_H
-#define GRPC_CORE_LIB_IOMGR_TCP_SERVER_UTILS_POSIX_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-
-/* one listening port */
-typedef struct grpc_tcp_listener {
- int fd;
- grpc_fd* emfd;
- grpc_tcp_server* server;
- grpc_resolved_address addr;
- int port;
- unsigned port_index;
- unsigned fd_index;
- grpc_closure read_closure;
- grpc_closure destroyed_closure;
- struct grpc_tcp_listener* next;
- /* sibling is a linked list of all listeners for a given port. add_port and
- clone_port place all new listeners in the same sibling list. A member of
- the 'sibling' list is also a member of the 'next' list. The head of each
- sibling list has is_sibling==0, and subsequent members of sibling lists
- have is_sibling==1. is_sibling allows separate sibling lists to be
- identified while iterating through 'next'. */
- struct grpc_tcp_listener* sibling;
- int is_sibling;
-} grpc_tcp_listener;
-
-/* the overall server */
-struct grpc_tcp_server {
- gpr_refcount refs;
- /* Called whenever accept() succeeds on a server port. */
- grpc_tcp_server_cb on_accept_cb;
- void* on_accept_cb_arg;
-
- gpr_mu mu;
-
- /* active port count: how many ports are actually still listening */
- size_t active_ports;
- /* destroyed port count: how many ports are completely destroyed */
- size_t destroyed_ports;
-
- /* is this server shutting down? */
- bool shutdown;
- /* have listeners been shutdown? */
- bool shutdown_listeners;
- /* use SO_REUSEPORT */
- bool so_reuseport;
- /* expand wildcard addresses to a list of all local addresses */
- bool expand_wildcard_addrs;
-
- /* linked list of server ports */
- grpc_tcp_listener* head;
- grpc_tcp_listener* tail;
- unsigned nports;
-
- /* List of closures passed to shutdown_starting_add(). */
- grpc_closure_list shutdown_starting;
-
- /* shutdown callback */
- grpc_closure* shutdown_complete;
-
+/*
+ *
+ * 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_IOMGR_TCP_SERVER_UTILS_POSIX_H
+#define GRPC_CORE_LIB_IOMGR_TCP_SERVER_UTILS_POSIX_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+
+/* one listening port */
+typedef struct grpc_tcp_listener {
+ int fd;
+ grpc_fd* emfd;
+ grpc_tcp_server* server;
+ grpc_resolved_address addr;
+ int port;
+ unsigned port_index;
+ unsigned fd_index;
+ grpc_closure read_closure;
+ grpc_closure destroyed_closure;
+ struct grpc_tcp_listener* next;
+ /* sibling is a linked list of all listeners for a given port. add_port and
+ clone_port place all new listeners in the same sibling list. A member of
+ the 'sibling' list is also a member of the 'next' list. The head of each
+ sibling list has is_sibling==0, and subsequent members of sibling lists
+ have is_sibling==1. is_sibling allows separate sibling lists to be
+ identified while iterating through 'next'. */
+ struct grpc_tcp_listener* sibling;
+ int is_sibling;
+} grpc_tcp_listener;
+
+/* the overall server */
+struct grpc_tcp_server {
+ gpr_refcount refs;
+ /* Called whenever accept() succeeds on a server port. */
+ grpc_tcp_server_cb on_accept_cb;
+ void* on_accept_cb_arg;
+
+ gpr_mu mu;
+
+ /* active port count: how many ports are actually still listening */
+ size_t active_ports;
+ /* destroyed port count: how many ports are completely destroyed */
+ size_t destroyed_ports;
+
+ /* is this server shutting down? */
+ bool shutdown;
+ /* have listeners been shutdown? */
+ bool shutdown_listeners;
+ /* use SO_REUSEPORT */
+ bool so_reuseport;
+ /* expand wildcard addresses to a list of all local addresses */
+ bool expand_wildcard_addrs;
+
+ /* linked list of server ports */
+ grpc_tcp_listener* head;
+ grpc_tcp_listener* tail;
+ unsigned nports;
+
+ /* List of closures passed to shutdown_starting_add(). */
+ grpc_closure_list shutdown_starting;
+
+ /* shutdown callback */
+ grpc_closure* shutdown_complete;
+
/* all pollsets interested in new connections. The object pointed at is not
* owned by this struct */
const std::vector<grpc_pollset*>* pollsets;
-
- /* next pollset to assign a channel to */
- gpr_atm next_pollset_to_assign;
-
- /* channel args for this server */
- grpc_channel_args* channel_args;
+
+ /* next pollset to assign a channel to */
+ gpr_atm next_pollset_to_assign;
+
+ /* channel args for this server */
+ grpc_channel_args* channel_args;
/* 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
- socket, and return the \a listener. */
-grpc_error* grpc_tcp_server_add_addr(grpc_tcp_server* s,
- const grpc_resolved_address* addr,
- unsigned port_index, unsigned fd_index,
- grpc_dualstack_mode* dsmode,
- grpc_tcp_listener** listener);
-
-/* Get all addresses assigned to network interfaces on the machine and create a
- listener for each. requested_port is the port to use for every listener, or 0
- to select one random port that will be used for every listener. Set *out_port
- to the port selected. Return GRPC_ERROR_NONE only if all listeners were
- added. */
-grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s,
- unsigned port_index,
- int requested_port,
- int* out_port);
-
-/* Prepare a recently-created socket for listening. */
+};
+
+/* If successful, add a listener to \a s for \a addr, set \a dsmode for the
+ socket, and return the \a listener. */
+grpc_error* grpc_tcp_server_add_addr(grpc_tcp_server* s,
+ const grpc_resolved_address* addr,
+ unsigned port_index, unsigned fd_index,
+ grpc_dualstack_mode* dsmode,
+ grpc_tcp_listener** listener);
+
+/* Get all addresses assigned to network interfaces on the machine and create a
+ listener for each. requested_port is the port to use for every listener, or 0
+ to select one random port that will be used for every listener. Set *out_port
+ to the port selected. Return GRPC_ERROR_NONE only if all listeners were
+ added. */
+grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s,
+ unsigned port_index,
+ int requested_port,
+ int* out_port);
+
+/* Prepare a recently-created socket for listening. */
grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server*, int fd,
- const grpc_resolved_address* addr,
- bool so_reuseport, int* port);
-/* Ruturn true if the platform supports ifaddrs */
-bool grpc_tcp_server_have_ifaddrs(void);
-
-#endif /* GRPC_CORE_LIB_IOMGR_TCP_SERVER_UTILS_POSIX_H */
+ const grpc_resolved_address* addr,
+ bool so_reuseport, int* port);
+/* Ruturn true if the platform supports ifaddrs */
+bool grpc_tcp_server_have_ifaddrs(void);
+
+#endif /* GRPC_CORE_LIB_IOMGR_TCP_SERVER_UTILS_POSIX_H */
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 46bc18e5a09..8c43809879c 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
@@ -1,161 +1,161 @@
-/*
- *
- * 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/iomgr/port.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON
-
-#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
-
-#include <errno.h>
-#include <limits.h>
-#include <stdio.h>
-#include <string.h>
-
+
+#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
+
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
-
-#define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
-
-static gpr_once s_init_max_accept_queue_size = GPR_ONCE_INIT;
-static int s_max_accept_queue_size;
-
-/* get max listen queue size on linux */
-static void init_max_accept_queue_size(void) {
- int n = SOMAXCONN;
- char buf[64];
- FILE* fp = fopen("/proc/sys/net/core/somaxconn", "r");
- if (fp == nullptr) {
- /* 2.4 kernel. */
- s_max_accept_queue_size = SOMAXCONN;
- return;
- }
- if (fgets(buf, sizeof buf, fp)) {
- char* end;
- long i = strtol(buf, &end, 10);
- if (i > 0 && i <= INT_MAX && end && *end == '\n') {
- n = static_cast<int>(i);
- }
- }
- fclose(fp);
- s_max_accept_queue_size = n;
-
- if (s_max_accept_queue_size < MIN_SAFE_ACCEPT_QUEUE_SIZE) {
- gpr_log(GPR_INFO,
- "Suspiciously small accept queue (%d) will probably lead to "
- "connection drops",
- s_max_accept_queue_size);
- }
-}
-
-static int get_max_accept_queue_size(void) {
- gpr_once_init(&s_init_max_accept_queue_size, init_max_accept_queue_size);
- return s_max_accept_queue_size;
-}
-
-static grpc_error* add_socket_to_server(grpc_tcp_server* s, int fd,
- const grpc_resolved_address* addr,
- unsigned port_index, unsigned fd_index,
- grpc_tcp_listener** listener) {
- grpc_tcp_listener* sp = nullptr;
- int port = -1;
-
- grpc_error* err =
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
+
+#define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
+
+static gpr_once s_init_max_accept_queue_size = GPR_ONCE_INIT;
+static int s_max_accept_queue_size;
+
+/* get max listen queue size on linux */
+static void init_max_accept_queue_size(void) {
+ int n = SOMAXCONN;
+ char buf[64];
+ FILE* fp = fopen("/proc/sys/net/core/somaxconn", "r");
+ if (fp == nullptr) {
+ /* 2.4 kernel. */
+ s_max_accept_queue_size = SOMAXCONN;
+ return;
+ }
+ if (fgets(buf, sizeof buf, fp)) {
+ char* end;
+ long i = strtol(buf, &end, 10);
+ if (i > 0 && i <= INT_MAX && end && *end == '\n') {
+ n = static_cast<int>(i);
+ }
+ }
+ fclose(fp);
+ s_max_accept_queue_size = n;
+
+ if (s_max_accept_queue_size < MIN_SAFE_ACCEPT_QUEUE_SIZE) {
+ gpr_log(GPR_INFO,
+ "Suspiciously small accept queue (%d) will probably lead to "
+ "connection drops",
+ s_max_accept_queue_size);
+ }
+}
+
+static int get_max_accept_queue_size(void) {
+ gpr_once_init(&s_init_max_accept_queue_size, init_max_accept_queue_size);
+ return s_max_accept_queue_size;
+}
+
+static grpc_error* add_socket_to_server(grpc_tcp_server* s, int fd,
+ const grpc_resolved_address* addr,
+ unsigned port_index, unsigned fd_index,
+ grpc_tcp_listener** listener) {
+ grpc_tcp_listener* sp = nullptr;
+ int port = -1;
+
+ grpc_error* err =
grpc_tcp_server_prepare_socket(s, fd, addr, s->so_reuseport, &port);
- if (err == GRPC_ERROR_NONE) {
- GPR_ASSERT(port > 0);
+ if (err == GRPC_ERROR_NONE) {
+ GPR_ASSERT(port > 0);
TString addr_str = grpc_sockaddr_to_string(addr, true);
TString name = y_absl::StrCat("tcp-server-listener:", addr_str);
- gpr_mu_lock(&s->mu);
- s->nports++;
- GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
- sp = static_cast<grpc_tcp_listener*>(gpr_malloc(sizeof(grpc_tcp_listener)));
- sp->next = nullptr;
- if (s->head == nullptr) {
- s->head = sp;
- } else {
- s->tail->next = sp;
- }
- s->tail = sp;
- sp->server = s;
- sp->fd = fd;
+ gpr_mu_lock(&s->mu);
+ s->nports++;
+ GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
+ sp = static_cast<grpc_tcp_listener*>(gpr_malloc(sizeof(grpc_tcp_listener)));
+ sp->next = nullptr;
+ if (s->head == nullptr) {
+ s->head = sp;
+ } else {
+ s->tail->next = sp;
+ }
+ s->tail = sp;
+ sp->server = s;
+ sp->fd = fd;
sp->emfd = grpc_fd_create(fd, name.c_str(), true);
- memcpy(&sp->addr, addr, sizeof(grpc_resolved_address));
- sp->port = port;
- sp->port_index = port_index;
- sp->fd_index = fd_index;
- sp->is_sibling = 0;
- sp->sibling = nullptr;
- GPR_ASSERT(sp->emfd);
- gpr_mu_unlock(&s->mu);
- }
-
- *listener = sp;
- return err;
-}
-
-/* If successful, add a listener to s for addr, set *dsmode for the socket, and
- return the *listener. */
-grpc_error* grpc_tcp_server_add_addr(grpc_tcp_server* s,
- const grpc_resolved_address* addr,
- unsigned port_index, unsigned fd_index,
- grpc_dualstack_mode* dsmode,
- grpc_tcp_listener** listener) {
- grpc_resolved_address addr4_copy;
- int fd;
- grpc_error* err =
- grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, dsmode, &fd);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- if (*dsmode == GRPC_DSMODE_IPV4 &&
- grpc_sockaddr_is_v4mapped(addr, &addr4_copy)) {
- addr = &addr4_copy;
- }
- return add_socket_to_server(s, fd, addr, port_index, fd_index, listener);
-}
-
-/* Prepare a recently-created socket for listening. */
+ memcpy(&sp->addr, addr, sizeof(grpc_resolved_address));
+ sp->port = port;
+ sp->port_index = port_index;
+ sp->fd_index = fd_index;
+ sp->is_sibling = 0;
+ sp->sibling = nullptr;
+ GPR_ASSERT(sp->emfd);
+ gpr_mu_unlock(&s->mu);
+ }
+
+ *listener = sp;
+ return err;
+}
+
+/* If successful, add a listener to s for addr, set *dsmode for the socket, and
+ return the *listener. */
+grpc_error* grpc_tcp_server_add_addr(grpc_tcp_server* s,
+ const grpc_resolved_address* addr,
+ unsigned port_index, unsigned fd_index,
+ grpc_dualstack_mode* dsmode,
+ grpc_tcp_listener** listener) {
+ grpc_resolved_address addr4_copy;
+ int fd;
+ grpc_error* err =
+ grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, dsmode, &fd);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ if (*dsmode == GRPC_DSMODE_IPV4 &&
+ grpc_sockaddr_is_v4mapped(addr, &addr4_copy)) {
+ addr = &addr4_copy;
+ }
+ return add_socket_to_server(s, fd, addr, port_index, fd_index, listener);
+}
+
+/* Prepare a recently-created socket for listening. */
grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server* s, int fd,
- const grpc_resolved_address* addr,
- bool so_reuseport, int* port) {
- grpc_resolved_address sockname_temp;
- grpc_error* err = GRPC_ERROR_NONE;
-
- GPR_ASSERT(fd >= 0);
-
- if (so_reuseport && !grpc_is_unix_socket(addr)) {
- err = grpc_set_socket_reuse_port(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
- }
-
+ const grpc_resolved_address* addr,
+ bool so_reuseport, int* port) {
+ grpc_resolved_address sockname_temp;
+ grpc_error* err = GRPC_ERROR_NONE;
+
+ GPR_ASSERT(fd >= 0);
+
+ if (so_reuseport && !grpc_is_unix_socket(addr)) {
+ err = grpc_set_socket_reuse_port(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
+ }
+
#ifdef GRPC_LINUX_ERRQUEUE
err = grpc_set_socket_zerocopy(fd);
if (err != GRPC_ERROR_NONE) {
@@ -164,58 +164,58 @@ grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server* s, int fd,
GRPC_ERROR_UNREF(err);
}
#endif
- err = grpc_set_socket_nonblocking(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
- err = grpc_set_socket_cloexec(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
- if (!grpc_is_unix_socket(addr)) {
- err = grpc_set_socket_low_latency(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
- err = grpc_set_socket_reuse_addr(fd, 1);
- if (err != GRPC_ERROR_NONE) goto error;
+ err = grpc_set_socket_nonblocking(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
+ err = grpc_set_socket_cloexec(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
+ if (!grpc_is_unix_socket(addr)) {
+ err = grpc_set_socket_low_latency(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
+ err = grpc_set_socket_reuse_addr(fd, 1);
+ if (err != GRPC_ERROR_NONE) goto error;
err = grpc_set_socket_tcp_user_timeout(fd, s->channel_args,
false /* is_client */);
if (err != GRPC_ERROR_NONE) goto error;
- }
- err = grpc_set_socket_no_sigpipe_if_possible(fd);
- if (err != GRPC_ERROR_NONE) goto error;
-
+ }
+ 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;
- if (bind(fd, reinterpret_cast<grpc_sockaddr*>(const_cast<char*>(addr->addr)),
- addr->len) < 0) {
- err = GRPC_OS_ERROR(errno, "bind");
- goto error;
- }
-
- if (listen(fd, get_max_accept_queue_size()) < 0) {
- err = GRPC_OS_ERROR(errno, "listen");
- goto error;
- }
-
- sockname_temp.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
-
- if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(sockname_temp.addr),
- &sockname_temp.len) < 0) {
- err = GRPC_OS_ERROR(errno, "getsockname");
- goto error;
- }
-
- *port = grpc_sockaddr_get_port(&sockname_temp);
- return GRPC_ERROR_NONE;
-
-error:
- GPR_ASSERT(err != GRPC_ERROR_NONE);
- if (fd >= 0) {
- close(fd);
- }
- grpc_error* ret =
- grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Unable to configure socket", &err, 1),
- GRPC_ERROR_INT_FD, fd);
- GRPC_ERROR_UNREF(err);
- return ret;
-}
-
+ if (bind(fd, reinterpret_cast<grpc_sockaddr*>(const_cast<char*>(addr->addr)),
+ addr->len) < 0) {
+ err = GRPC_OS_ERROR(errno, "bind");
+ goto error;
+ }
+
+ if (listen(fd, get_max_accept_queue_size()) < 0) {
+ err = GRPC_OS_ERROR(errno, "listen");
+ goto error;
+ }
+
+ sockname_temp.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
+
+ if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(sockname_temp.addr),
+ &sockname_temp.len) < 0) {
+ err = GRPC_OS_ERROR(errno, "getsockname");
+ goto error;
+ }
+
+ *port = grpc_sockaddr_get_port(&sockname_temp);
+ return GRPC_ERROR_NONE;
+
+error:
+ GPR_ASSERT(err != GRPC_ERROR_NONE);
+ if (fd >= 0) {
+ close(fd);
+ }
+ grpc_error* ret =
+ grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Unable to configure socket", &err, 1),
+ GRPC_ERROR_INT_FD, fd);
+ GRPC_ERROR_UNREF(err);
+ return ret;
+}
+
#endif /* GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc
index 1c7cd5cc10b..0e1af2b3a35 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc
@@ -1,176 +1,176 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_HAVE_IFADDRS
-
-#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
-
-#include <errno.h>
-#include <ifaddrs.h>
-#include <stddef.h>
-#include <string.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_HAVE_IFADDRS
+
+#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
+
+#include <errno.h>
+#include <ifaddrs.h>
+#include <stddef.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-
-/* Return the listener in s with address addr or NULL. */
-static grpc_tcp_listener* find_listener_with_addr(grpc_tcp_server* s,
- grpc_resolved_address* addr) {
- grpc_tcp_listener* l;
- gpr_mu_lock(&s->mu);
- for (l = s->head; l != nullptr; l = l->next) {
- if (l->addr.len != addr->len) {
- continue;
- }
- if (memcmp(l->addr.addr, addr->addr, addr->len) == 0) {
- break;
- }
- }
- gpr_mu_unlock(&s->mu);
- return l;
-}
-
-/* Bind to "::" to get a port number not used by any address. */
-static grpc_error* get_unused_port(int* port) {
- grpc_resolved_address wild;
- grpc_sockaddr_make_wildcard6(0, &wild);
- grpc_dualstack_mode dsmode;
- int fd;
- grpc_error* err =
- grpc_create_dualstack_socket(&wild, SOCK_STREAM, 0, &dsmode, &fd);
- if (err != GRPC_ERROR_NONE) {
- return err;
- }
- if (dsmode == GRPC_DSMODE_IPV4) {
- grpc_sockaddr_make_wildcard4(0, &wild);
- }
- if (bind(fd, reinterpret_cast<const grpc_sockaddr*>(wild.addr), wild.len) !=
- 0) {
- err = GRPC_OS_ERROR(errno, "bind");
- close(fd);
- return err;
- }
- if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(wild.addr), &wild.len) !=
- 0) {
- err = GRPC_OS_ERROR(errno, "getsockname");
- close(fd);
- return err;
- }
- close(fd);
- *port = grpc_sockaddr_get_port(&wild);
- return *port <= 0 ? GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad port")
- : GRPC_ERROR_NONE;
-}
-
-grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s,
- unsigned port_index,
- int requested_port,
- int* out_port) {
- struct ifaddrs* ifa = nullptr;
- struct ifaddrs* ifa_it;
- unsigned fd_index = 0;
- grpc_tcp_listener* sp = nullptr;
- grpc_error* err = GRPC_ERROR_NONE;
- if (requested_port == 0) {
- /* Note: There could be a race where some local addrs can listen on the
- selected port and some can't. The sane way to handle this would be to
- retry by recreating the whole grpc_tcp_server. Backing out individual
- listeners and orphaning the FDs looks like too much trouble. */
- if ((err = get_unused_port(&requested_port)) != GRPC_ERROR_NONE) {
- return err;
- } else if (requested_port <= 0) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad get_unused_port()");
- }
- gpr_log(GPR_DEBUG, "Picked unused port %d", requested_port);
- }
- if (getifaddrs(&ifa) != 0 || ifa == nullptr) {
- return GRPC_OS_ERROR(errno, "getifaddrs");
- }
- for (ifa_it = ifa; ifa_it != nullptr; ifa_it = ifa_it->ifa_next) {
- grpc_resolved_address addr;
- grpc_dualstack_mode dsmode;
- grpc_tcp_listener* new_sp = nullptr;
- const char* ifa_name = (ifa_it->ifa_name ? ifa_it->ifa_name : "<unknown>");
- if (ifa_it->ifa_addr == nullptr) {
- continue;
- } else if (ifa_it->ifa_addr->sa_family == AF_INET) {
- addr.len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
- } else if (ifa_it->ifa_addr->sa_family == AF_INET6) {
- addr.len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
- } else {
- continue;
- }
- memcpy(addr.addr, ifa_it->ifa_addr, addr.len);
- if (!grpc_sockaddr_set_port(&addr, requested_port)) {
- /* Should never happen, because we check sa_family above. */
- err = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set port");
- break;
- }
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+
+/* Return the listener in s with address addr or NULL. */
+static grpc_tcp_listener* find_listener_with_addr(grpc_tcp_server* s,
+ grpc_resolved_address* addr) {
+ grpc_tcp_listener* l;
+ gpr_mu_lock(&s->mu);
+ for (l = s->head; l != nullptr; l = l->next) {
+ if (l->addr.len != addr->len) {
+ continue;
+ }
+ if (memcmp(l->addr.addr, addr->addr, addr->len) == 0) {
+ break;
+ }
+ }
+ gpr_mu_unlock(&s->mu);
+ return l;
+}
+
+/* Bind to "::" to get a port number not used by any address. */
+static grpc_error* get_unused_port(int* port) {
+ grpc_resolved_address wild;
+ grpc_sockaddr_make_wildcard6(0, &wild);
+ grpc_dualstack_mode dsmode;
+ int fd;
+ grpc_error* err =
+ grpc_create_dualstack_socket(&wild, SOCK_STREAM, 0, &dsmode, &fd);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ }
+ if (dsmode == GRPC_DSMODE_IPV4) {
+ grpc_sockaddr_make_wildcard4(0, &wild);
+ }
+ if (bind(fd, reinterpret_cast<const grpc_sockaddr*>(wild.addr), wild.len) !=
+ 0) {
+ err = GRPC_OS_ERROR(errno, "bind");
+ close(fd);
+ return err;
+ }
+ if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(wild.addr), &wild.len) !=
+ 0) {
+ err = GRPC_OS_ERROR(errno, "getsockname");
+ close(fd);
+ return err;
+ }
+ close(fd);
+ *port = grpc_sockaddr_get_port(&wild);
+ return *port <= 0 ? GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad port")
+ : GRPC_ERROR_NONE;
+}
+
+grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s,
+ unsigned port_index,
+ int requested_port,
+ int* out_port) {
+ struct ifaddrs* ifa = nullptr;
+ struct ifaddrs* ifa_it;
+ unsigned fd_index = 0;
+ grpc_tcp_listener* sp = nullptr;
+ grpc_error* err = GRPC_ERROR_NONE;
+ if (requested_port == 0) {
+ /* Note: There could be a race where some local addrs can listen on the
+ selected port and some can't. The sane way to handle this would be to
+ retry by recreating the whole grpc_tcp_server. Backing out individual
+ listeners and orphaning the FDs looks like too much trouble. */
+ if ((err = get_unused_port(&requested_port)) != GRPC_ERROR_NONE) {
+ return err;
+ } else if (requested_port <= 0) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad get_unused_port()");
+ }
+ gpr_log(GPR_DEBUG, "Picked unused port %d", requested_port);
+ }
+ if (getifaddrs(&ifa) != 0 || ifa == nullptr) {
+ return GRPC_OS_ERROR(errno, "getifaddrs");
+ }
+ for (ifa_it = ifa; ifa_it != nullptr; ifa_it = ifa_it->ifa_next) {
+ grpc_resolved_address addr;
+ grpc_dualstack_mode dsmode;
+ grpc_tcp_listener* new_sp = nullptr;
+ const char* ifa_name = (ifa_it->ifa_name ? ifa_it->ifa_name : "<unknown>");
+ if (ifa_it->ifa_addr == nullptr) {
+ continue;
+ } else if (ifa_it->ifa_addr->sa_family == AF_INET) {
+ addr.len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in));
+ } else if (ifa_it->ifa_addr->sa_family == AF_INET6) {
+ addr.len = static_cast<socklen_t>(sizeof(grpc_sockaddr_in6));
+ } else {
+ continue;
+ }
+ memcpy(addr.addr, ifa_it->ifa_addr, addr.len);
+ if (!grpc_sockaddr_set_port(&addr, requested_port)) {
+ /* Should never happen, because we check sa_family above. */
+ err = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to set port");
+ break;
+ }
TString addr_str = grpc_sockaddr_to_string(&addr, false);
- gpr_log(GPR_DEBUG,
- "Adding local addr from interface %s flags 0x%x to server: %s",
+ gpr_log(GPR_DEBUG,
+ "Adding local addr from interface %s flags 0x%x to server: %s",
ifa_name, ifa_it->ifa_flags, addr_str.c_str());
- /* We could have multiple interfaces with the same address (e.g., bonding),
- so look for duplicates. */
- if (find_listener_with_addr(s, &addr) != nullptr) {
+ /* We could have multiple interfaces with the same address (e.g., bonding),
+ so look for duplicates. */
+ if (find_listener_with_addr(s, &addr) != nullptr) {
gpr_log(GPR_DEBUG, "Skipping duplicate addr %s on interface %s",
addr_str.c_str(), ifa_name);
- continue;
- }
- if ((err = grpc_tcp_server_add_addr(s, &addr, port_index, fd_index, &dsmode,
- &new_sp)) != GRPC_ERROR_NONE) {
+ continue;
+ }
+ if ((err = grpc_tcp_server_add_addr(s, &addr, port_index, fd_index, &dsmode,
+ &new_sp)) != GRPC_ERROR_NONE) {
grpc_error* root_err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Failed to add listener: ", addr_str).c_str());
- err = grpc_error_add_child(root_err, err);
- break;
- } else {
- GPR_ASSERT(requested_port == new_sp->port);
- ++fd_index;
- if (sp != nullptr) {
- new_sp->is_sibling = 1;
- sp->sibling = new_sp;
- }
- sp = new_sp;
- }
- }
- freeifaddrs(ifa);
- if (err != GRPC_ERROR_NONE) {
- return err;
- } else if (sp == nullptr) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("No local addresses");
- } else {
- *out_port = sp->port;
- return GRPC_ERROR_NONE;
- }
-}
-
-bool grpc_tcp_server_have_ifaddrs(void) { return true; }
-
-#endif /* GRPC_HAVE_IFADDRS */
+ err = grpc_error_add_child(root_err, err);
+ break;
+ } else {
+ GPR_ASSERT(requested_port == new_sp->port);
+ ++fd_index;
+ if (sp != nullptr) {
+ new_sp->is_sibling = 1;
+ sp->sibling = new_sp;
+ }
+ sp = new_sp;
+ }
+ }
+ freeifaddrs(ifa);
+ if (err != GRPC_ERROR_NONE) {
+ return err;
+ } else if (sp == nullptr) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("No local addresses");
+ } else {
+ *out_port = sp->port;
+ return GRPC_ERROR_NONE;
+ }
+}
+
+bool grpc_tcp_server_have_ifaddrs(void) { return true; }
+
+#endif /* GRPC_HAVE_IFADDRS */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc
index 86ee14f2856..61a98d9d22c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc
@@ -1,36 +1,36 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#if defined(GRPC_POSIX_SOCKET) && !defined(GRPC_HAVE_IFADDRS)
-
-#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
-
-grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s,
- unsigned port_index,
- int requested_port,
- int* out_port) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("no ifaddrs available");
-}
-
-bool grpc_tcp_server_have_ifaddrs(void) { return false; }
-
-#endif /* defined(GRPC_POSIX_SOCKET) && !defined(GRPC_HAVE_IFADDRS) */
+/*
+ *
+ * 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/iomgr/port.h"
+
+#if defined(GRPC_POSIX_SOCKET) && !defined(GRPC_HAVE_IFADDRS)
+
+#include "src/core/lib/iomgr/tcp_server_utils_posix.h"
+
+grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s,
+ unsigned port_index,
+ int requested_port,
+ int* out_port) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("no ifaddrs available");
+}
+
+bool grpc_tcp_server_have_ifaddrs(void) { return false; }
+
+#endif /* defined(GRPC_POSIX_SOCKET) && !defined(GRPC_HAVE_IFADDRS) */
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 13c17260dc2..677d2481cb0 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
@@ -1,564 +1,564 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include <inttypes.h>
-#include <io.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/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include <inttypes.h>
+#include <io.h>
+
#include <vector>
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/log_windows.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/pollset_windows.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/socket_windows.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "src/core/lib/iomgr/tcp_windows.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_windows.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/pollset_windows.h"
+#include "src/core/lib/iomgr/resolve_address.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/socket_windows.h"
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "src/core/lib/iomgr/tcp_windows.h"
#include "src/core/lib/slice/slice_internal.h"
-
-#define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
-
-/* one listening port */
-typedef struct grpc_tcp_listener grpc_tcp_listener;
-struct grpc_tcp_listener {
- /* This seemingly magic number comes from AcceptEx's documentation. each
- address buffer needs to have at least 16 more bytes at their end. */
- uint8_t addresses[(sizeof(grpc_sockaddr_in6) + 16) * 2];
- /* This will hold the socket for the next accept. */
- SOCKET new_socket;
- /* The listener winsocket. */
- grpc_winsocket* socket;
- /* The actual TCP port number. */
- int port;
- unsigned port_index;
- grpc_tcp_server* server;
- /* The cached AcceptEx for that port. */
- LPFN_ACCEPTEX AcceptEx;
- int shutting_down;
- int outstanding_calls;
- /* closure for socket notification of accept being ready */
- grpc_closure on_accept;
- /* linked list */
- struct grpc_tcp_listener* next;
-};
-
-/* the overall server */
-struct grpc_tcp_server {
- gpr_refcount refs;
- /* Called whenever accept() succeeds on a server port. */
- grpc_tcp_server_cb on_accept_cb;
- void* on_accept_cb_arg;
-
- gpr_mu mu;
-
- /* active port count: how many ports are actually still listening */
- int active_ports;
-
- /* linked list of server ports */
- grpc_tcp_listener* head;
- grpc_tcp_listener* tail;
-
- /* List of closures passed to shutdown_starting_add(). */
- grpc_closure_list shutdown_starting;
-
- /* shutdown callback */
- grpc_closure* shutdown_complete;
-
- grpc_channel_args* channel_args;
-};
-
-/* Public function. Allocates the proper data structures to hold a
- grpc_tcp_server. */
-static grpc_error* tcp_server_create(grpc_closure* shutdown_complete,
- const grpc_channel_args* args,
- grpc_tcp_server** server) {
- grpc_tcp_server* s = (grpc_tcp_server*)gpr_malloc(sizeof(grpc_tcp_server));
- s->channel_args = grpc_channel_args_copy(args);
- gpr_ref_init(&s->refs, 1);
- gpr_mu_init(&s->mu);
- s->active_ports = 0;
- s->on_accept_cb = NULL;
- s->on_accept_cb_arg = NULL;
- s->head = NULL;
- s->tail = NULL;
- s->shutdown_starting.head = NULL;
- s->shutdown_starting.tail = NULL;
- s->shutdown_complete = shutdown_complete;
- *server = s;
- return GRPC_ERROR_NONE;
-}
-
-static void destroy_server(void* arg, grpc_error* error) {
- grpc_tcp_server* s = (grpc_tcp_server*)arg;
-
- /* Now that the accepts have been aborted, we can destroy the sockets.
- The IOCP won't get notified on these, so we can flag them as already
- closed by the system. */
- while (s->head) {
- grpc_tcp_listener* sp = s->head;
- s->head = sp->next;
- sp->next = NULL;
- grpc_winsocket_destroy(sp->socket);
- gpr_free(sp);
- }
- grpc_channel_args_destroy(s->channel_args);
- gpr_mu_destroy(&s->mu);
- gpr_free(s);
-}
-
-static void finish_shutdown_locked(grpc_tcp_server* s) {
- if (s->shutdown_complete != NULL) {
+
+#define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
+
+/* one listening port */
+typedef struct grpc_tcp_listener grpc_tcp_listener;
+struct grpc_tcp_listener {
+ /* This seemingly magic number comes from AcceptEx's documentation. each
+ address buffer needs to have at least 16 more bytes at their end. */
+ uint8_t addresses[(sizeof(grpc_sockaddr_in6) + 16) * 2];
+ /* This will hold the socket for the next accept. */
+ SOCKET new_socket;
+ /* The listener winsocket. */
+ grpc_winsocket* socket;
+ /* The actual TCP port number. */
+ int port;
+ unsigned port_index;
+ grpc_tcp_server* server;
+ /* The cached AcceptEx for that port. */
+ LPFN_ACCEPTEX AcceptEx;
+ int shutting_down;
+ int outstanding_calls;
+ /* closure for socket notification of accept being ready */
+ grpc_closure on_accept;
+ /* linked list */
+ struct grpc_tcp_listener* next;
+};
+
+/* the overall server */
+struct grpc_tcp_server {
+ gpr_refcount refs;
+ /* Called whenever accept() succeeds on a server port. */
+ grpc_tcp_server_cb on_accept_cb;
+ void* on_accept_cb_arg;
+
+ gpr_mu mu;
+
+ /* active port count: how many ports are actually still listening */
+ int active_ports;
+
+ /* linked list of server ports */
+ grpc_tcp_listener* head;
+ grpc_tcp_listener* tail;
+
+ /* List of closures passed to shutdown_starting_add(). */
+ grpc_closure_list shutdown_starting;
+
+ /* shutdown callback */
+ grpc_closure* shutdown_complete;
+
+ grpc_channel_args* channel_args;
+};
+
+/* Public function. Allocates the proper data structures to hold a
+ grpc_tcp_server. */
+static grpc_error* tcp_server_create(grpc_closure* shutdown_complete,
+ const grpc_channel_args* args,
+ grpc_tcp_server** server) {
+ grpc_tcp_server* s = (grpc_tcp_server*)gpr_malloc(sizeof(grpc_tcp_server));
+ s->channel_args = grpc_channel_args_copy(args);
+ gpr_ref_init(&s->refs, 1);
+ gpr_mu_init(&s->mu);
+ s->active_ports = 0;
+ s->on_accept_cb = NULL;
+ s->on_accept_cb_arg = NULL;
+ s->head = NULL;
+ s->tail = NULL;
+ s->shutdown_starting.head = NULL;
+ s->shutdown_starting.tail = NULL;
+ s->shutdown_complete = shutdown_complete;
+ *server = s;
+ return GRPC_ERROR_NONE;
+}
+
+static void destroy_server(void* arg, grpc_error* error) {
+ grpc_tcp_server* s = (grpc_tcp_server*)arg;
+
+ /* Now that the accepts have been aborted, we can destroy the sockets.
+ The IOCP won't get notified on these, so we can flag them as already
+ closed by the system. */
+ while (s->head) {
+ grpc_tcp_listener* sp = s->head;
+ s->head = sp->next;
+ sp->next = NULL;
+ grpc_winsocket_destroy(sp->socket);
+ gpr_free(sp);
+ }
+ grpc_channel_args_destroy(s->channel_args);
+ gpr_mu_destroy(&s->mu);
+ gpr_free(s);
+}
+
+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,
- GRPC_CLOSURE_CREATE(destroy_server, s, grpc_schedule_on_exec_ctx),
- GRPC_ERROR_NONE);
-}
-
-static grpc_tcp_server* tcp_server_ref(grpc_tcp_server* s) {
- gpr_ref_non_zero(&s->refs);
- return s;
-}
-
-static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
- grpc_closure* shutdown_starting) {
- gpr_mu_lock(&s->mu);
- grpc_closure_list_append(&s->shutdown_starting, shutdown_starting,
- GRPC_ERROR_NONE);
- gpr_mu_unlock(&s->mu);
-}
-
-static void tcp_server_destroy(grpc_tcp_server* s) {
- grpc_tcp_listener* sp;
- gpr_mu_lock(&s->mu);
-
- /* First, shutdown all fd's. This will queue abortion calls for all
- of the pending accepts due to the normal operation mechanism. */
- if (s->active_ports == 0) {
- finish_shutdown_locked(s);
- } else {
- for (sp = s->head; sp; sp = sp->next) {
- sp->shutting_down = 1;
- grpc_winsocket_shutdown(sp->socket);
- }
- }
- gpr_mu_unlock(&s->mu);
-}
-
-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_CLOSURE_CREATE(destroy_server, s, grpc_schedule_on_exec_ctx),
+ GRPC_ERROR_NONE);
+}
+
+static grpc_tcp_server* tcp_server_ref(grpc_tcp_server* s) {
+ gpr_ref_non_zero(&s->refs);
+ return s;
+}
+
+static void tcp_server_shutdown_starting_add(grpc_tcp_server* s,
+ grpc_closure* shutdown_starting) {
+ gpr_mu_lock(&s->mu);
+ grpc_closure_list_append(&s->shutdown_starting, shutdown_starting,
+ GRPC_ERROR_NONE);
+ gpr_mu_unlock(&s->mu);
+}
+
+static void tcp_server_destroy(grpc_tcp_server* s) {
+ grpc_tcp_listener* sp;
+ gpr_mu_lock(&s->mu);
+
+ /* First, shutdown all fd's. This will queue abortion calls for all
+ of the pending accepts due to the normal operation mechanism. */
+ if (s->active_ports == 0) {
+ finish_shutdown_locked(s);
+ } else {
+ for (sp = s->head; sp; sp = sp->next) {
+ sp->shutting_down = 1;
+ grpc_winsocket_shutdown(sp->socket);
+ }
+ }
+ gpr_mu_unlock(&s->mu);
+}
+
+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);
- gpr_mu_unlock(&s->mu);
- tcp_server_destroy(s);
- }
-}
-
-/* Prepare (bind) a recently-created socket for listening. */
-static grpc_error* prepare_socket(SOCKET sock,
- const grpc_resolved_address* addr,
- int* port) {
- grpc_resolved_address sockname_temp;
- grpc_error* error = GRPC_ERROR_NONE;
- int sockname_temp_len;
-
- error = grpc_tcp_prepare_socket(sock);
- if (error != GRPC_ERROR_NONE) {
- goto failure;
- }
-
- if (bind(sock, (const grpc_sockaddr*)addr->addr, (int)addr->len) ==
- SOCKET_ERROR) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "bind");
- goto failure;
- }
-
- if (listen(sock, SOMAXCONN) == SOCKET_ERROR) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "listen");
- goto failure;
- }
-
- sockname_temp_len = sizeof(struct sockaddr_storage);
- if (getsockname(sock, (grpc_sockaddr*)sockname_temp.addr,
- &sockname_temp_len) == SOCKET_ERROR) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "getsockname");
- goto failure;
- }
- sockname_temp.len = (size_t)sockname_temp_len;
-
- *port = grpc_sockaddr_get_port(&sockname_temp);
- return GRPC_ERROR_NONE;
-
-failure:
- GPR_ASSERT(error != GRPC_ERROR_NONE);
- grpc_error_set_int(
+ gpr_mu_unlock(&s->mu);
+ tcp_server_destroy(s);
+ }
+}
+
+/* Prepare (bind) a recently-created socket for listening. */
+static grpc_error* prepare_socket(SOCKET sock,
+ const grpc_resolved_address* addr,
+ int* port) {
+ grpc_resolved_address sockname_temp;
+ grpc_error* error = GRPC_ERROR_NONE;
+ int sockname_temp_len;
+
+ error = grpc_tcp_prepare_socket(sock);
+ if (error != GRPC_ERROR_NONE) {
+ goto failure;
+ }
+
+ if (bind(sock, (const grpc_sockaddr*)addr->addr, (int)addr->len) ==
+ SOCKET_ERROR) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "bind");
+ goto failure;
+ }
+
+ if (listen(sock, SOMAXCONN) == SOCKET_ERROR) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "listen");
+ goto failure;
+ }
+
+ sockname_temp_len = sizeof(struct sockaddr_storage);
+ if (getsockname(sock, (grpc_sockaddr*)sockname_temp.addr,
+ &sockname_temp_len) == SOCKET_ERROR) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "getsockname");
+ goto failure;
+ }
+ sockname_temp.len = (size_t)sockname_temp_len;
+
+ *port = grpc_sockaddr_get_port(&sockname_temp);
+ return GRPC_ERROR_NONE;
+
+failure:
+ GPR_ASSERT(error != GRPC_ERROR_NONE);
+ grpc_error_set_int(
grpc_error_set_str(
GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Failed to prepare server socket", &error, 1),
GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_cpp_string(grpc_sockaddr_to_uri(addr))),
- GRPC_ERROR_INT_FD, (intptr_t)sock);
- GRPC_ERROR_UNREF(error);
- if (sock != INVALID_SOCKET) closesocket(sock);
- return error;
-}
-
-static void decrement_active_ports_and_notify_locked(grpc_tcp_listener* sp) {
- sp->shutting_down = 0;
- GPR_ASSERT(sp->server->active_ports > 0);
- if (0 == --sp->server->active_ports) {
- finish_shutdown_locked(sp->server);
- }
-}
-
-/* In order to do an async accept, we need to create a socket first which
- will be the one assigned to the new incoming connection. */
-static grpc_error* start_accept_locked(grpc_tcp_listener* port) {
- SOCKET sock = INVALID_SOCKET;
- BOOL success;
- DWORD addrlen = sizeof(grpc_sockaddr_in6) + 16;
- DWORD bytes_received = 0;
- grpc_error* error = GRPC_ERROR_NONE;
-
- if (port->shutting_down) {
- return GRPC_ERROR_NONE;
- }
-
- sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
+ GRPC_ERROR_INT_FD, (intptr_t)sock);
+ GRPC_ERROR_UNREF(error);
+ if (sock != INVALID_SOCKET) closesocket(sock);
+ return error;
+}
+
+static void decrement_active_ports_and_notify_locked(grpc_tcp_listener* sp) {
+ sp->shutting_down = 0;
+ GPR_ASSERT(sp->server->active_ports > 0);
+ if (0 == --sp->server->active_ports) {
+ finish_shutdown_locked(sp->server);
+ }
+}
+
+/* In order to do an async accept, we need to create a socket first which
+ will be the one assigned to the new incoming connection. */
+static grpc_error* start_accept_locked(grpc_tcp_listener* port) {
+ SOCKET sock = INVALID_SOCKET;
+ BOOL success;
+ DWORD addrlen = sizeof(grpc_sockaddr_in6) + 16;
+ DWORD bytes_received = 0;
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ if (port->shutting_down) {
+ return GRPC_ERROR_NONE;
+ }
+
+ sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
grpc_get_default_wsa_socket_flags());
- if (sock == INVALID_SOCKET) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
- goto failure;
- }
-
- error = grpc_tcp_prepare_socket(sock);
- if (error != GRPC_ERROR_NONE) goto failure;
-
- /* Start the "accept" asynchronously. */
- success = port->AcceptEx(port->socket->socket, sock, port->addresses, 0,
- addrlen, addrlen, &bytes_received,
- &port->socket->read_info.overlapped);
-
- /* It is possible to get an accept immediately without delay. However, we
- will still get an IOCP notification for it. So let's just ignore it. */
- if (!success) {
- int last_error = WSAGetLastError();
- if (last_error != ERROR_IO_PENDING) {
- error = GRPC_WSA_ERROR(last_error, "AcceptEx");
- goto failure;
- }
- }
-
- /* We're ready to do the accept. Calling grpc_socket_notify_on_read may
- immediately process an accept that happened in the meantime. */
- port->new_socket = sock;
- grpc_socket_notify_on_read(port->socket, &port->on_accept);
- port->outstanding_calls++;
- return error;
-
-failure:
- GPR_ASSERT(error != GRPC_ERROR_NONE);
- if (sock != INVALID_SOCKET) closesocket(sock);
- return error;
-}
-
-/* Event manager callback when reads are ready. */
-static void on_accept(void* arg, grpc_error* error) {
- grpc_tcp_listener* sp = (grpc_tcp_listener*)arg;
- SOCKET sock = sp->new_socket;
- grpc_winsocket_callback_info* info = &sp->socket->read_info;
- grpc_endpoint* ep = NULL;
- grpc_resolved_address peer_name;
- DWORD transfered_bytes;
- DWORD flags;
- BOOL wsa_success;
- int err;
-
- gpr_mu_lock(&sp->server->mu);
-
- peer_name.len = sizeof(struct sockaddr_storage);
-
- /* The general mechanism for shutting down is to queue abortion calls. While
- this is necessary in the read/write case, it's useless for the accept
- case. We only need to adjust the pending callback count */
- if (error != GRPC_ERROR_NONE) {
- const char* msg = grpc_error_string(error);
- gpr_log(GPR_INFO, "Skipping on_accept due to error: %s", msg);
-
- gpr_mu_unlock(&sp->server->mu);
- return;
- }
-
- /* The IOCP notified us of a completed operation. Let's grab the results,
- and act accordingly. */
- transfered_bytes = 0;
- wsa_success = WSAGetOverlappedResult(sock, &info->overlapped,
- &transfered_bytes, FALSE, &flags);
- if (!wsa_success) {
- if (!sp->shutting_down) {
- char* utf8_message = gpr_format_message(WSAGetLastError());
- gpr_log(GPR_ERROR, "on_accept error: %s", utf8_message);
- gpr_free(utf8_message);
- }
- closesocket(sock);
- } else {
- if (!sp->shutting_down) {
- err = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
- (char*)&sp->socket->socket, sizeof(sp->socket->socket));
- if (err) {
- char* utf8_message = gpr_format_message(WSAGetLastError());
- gpr_log(GPR_ERROR, "setsockopt error: %s", utf8_message);
- gpr_free(utf8_message);
- }
- int peer_name_len = (int)peer_name.len;
- err = getpeername(sock, (grpc_sockaddr*)peer_name.addr, &peer_name_len);
- peer_name.len = (size_t)peer_name_len;
+ if (sock == INVALID_SOCKET) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
+ goto failure;
+ }
+
+ error = grpc_tcp_prepare_socket(sock);
+ if (error != GRPC_ERROR_NONE) goto failure;
+
+ /* Start the "accept" asynchronously. */
+ success = port->AcceptEx(port->socket->socket, sock, port->addresses, 0,
+ addrlen, addrlen, &bytes_received,
+ &port->socket->read_info.overlapped);
+
+ /* It is possible to get an accept immediately without delay. However, we
+ will still get an IOCP notification for it. So let's just ignore it. */
+ if (!success) {
+ int last_error = WSAGetLastError();
+ if (last_error != ERROR_IO_PENDING) {
+ error = GRPC_WSA_ERROR(last_error, "AcceptEx");
+ goto failure;
+ }
+ }
+
+ /* We're ready to do the accept. Calling grpc_socket_notify_on_read may
+ immediately process an accept that happened in the meantime. */
+ port->new_socket = sock;
+ grpc_socket_notify_on_read(port->socket, &port->on_accept);
+ port->outstanding_calls++;
+ return error;
+
+failure:
+ GPR_ASSERT(error != GRPC_ERROR_NONE);
+ if (sock != INVALID_SOCKET) closesocket(sock);
+ return error;
+}
+
+/* Event manager callback when reads are ready. */
+static void on_accept(void* arg, grpc_error* error) {
+ grpc_tcp_listener* sp = (grpc_tcp_listener*)arg;
+ SOCKET sock = sp->new_socket;
+ grpc_winsocket_callback_info* info = &sp->socket->read_info;
+ grpc_endpoint* ep = NULL;
+ grpc_resolved_address peer_name;
+ DWORD transfered_bytes;
+ DWORD flags;
+ BOOL wsa_success;
+ int err;
+
+ gpr_mu_lock(&sp->server->mu);
+
+ peer_name.len = sizeof(struct sockaddr_storage);
+
+ /* The general mechanism for shutting down is to queue abortion calls. While
+ this is necessary in the read/write case, it's useless for the accept
+ case. We only need to adjust the pending callback count */
+ if (error != GRPC_ERROR_NONE) {
+ const char* msg = grpc_error_string(error);
+ gpr_log(GPR_INFO, "Skipping on_accept due to error: %s", msg);
+
+ gpr_mu_unlock(&sp->server->mu);
+ return;
+ }
+
+ /* The IOCP notified us of a completed operation. Let's grab the results,
+ and act accordingly. */
+ transfered_bytes = 0;
+ wsa_success = WSAGetOverlappedResult(sock, &info->overlapped,
+ &transfered_bytes, FALSE, &flags);
+ if (!wsa_success) {
+ if (!sp->shutting_down) {
+ char* utf8_message = gpr_format_message(WSAGetLastError());
+ gpr_log(GPR_ERROR, "on_accept error: %s", utf8_message);
+ gpr_free(utf8_message);
+ }
+ closesocket(sock);
+ } else {
+ if (!sp->shutting_down) {
+ err = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
+ (char*)&sp->socket->socket, sizeof(sp->socket->socket));
+ if (err) {
+ char* utf8_message = gpr_format_message(WSAGetLastError());
+ gpr_log(GPR_ERROR, "setsockopt error: %s", utf8_message);
+ gpr_free(utf8_message);
+ }
+ int peer_name_len = (int)peer_name.len;
+ err = getpeername(sock, (grpc_sockaddr*)peer_name.addr, &peer_name_len);
+ peer_name.len = (size_t)peer_name_len;
TString peer_name_string;
- if (!err) {
- peer_name_string = grpc_sockaddr_to_uri(&peer_name);
- } else {
- char* utf8_message = gpr_format_message(WSAGetLastError());
- gpr_log(GPR_ERROR, "getpeername error: %s", utf8_message);
- gpr_free(utf8_message);
- }
+ if (!err) {
+ peer_name_string = grpc_sockaddr_to_uri(&peer_name);
+ } else {
+ char* utf8_message = gpr_format_message(WSAGetLastError());
+ gpr_log(GPR_ERROR, "getpeername error: %s", utf8_message);
+ gpr_free(utf8_message);
+ }
TString fd_name = y_absl::StrCat("tcp_server:", peer_name_string);
ep = grpc_tcp_create(grpc_winsocket_create(sock, fd_name.c_str()),
sp->server->channel_args, peer_name_string.c_str());
- } else {
- closesocket(sock);
- }
- }
-
- /* The only time we should call our callback, is where we successfully
- managed to accept a connection, and created an endpoint. */
- if (ep) {
- // Create acceptor.
- grpc_tcp_server_acceptor* acceptor =
- (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor));
- acceptor->from_server = sp->server;
- acceptor->port_index = sp->port_index;
- acceptor->fd_index = 0;
+ } else {
+ closesocket(sock);
+ }
+ }
+
+ /* The only time we should call our callback, is where we successfully
+ managed to accept a connection, and created an endpoint. */
+ if (ep) {
+ // Create acceptor.
+ grpc_tcp_server_acceptor* acceptor =
+ (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor));
+ acceptor->from_server = sp->server;
+ acceptor->port_index = sp->port_index;
+ acceptor->fd_index = 0;
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,
- the former socked we created has now either been destroy or assigned
- to the new connection. We need to create a new one for the next
- connection. */
- GPR_ASSERT(GRPC_LOG_IF_ERROR("start_accept", start_accept_locked(sp)));
- if (0 == --sp->outstanding_calls) {
- decrement_active_ports_and_notify_locked(sp);
- }
- gpr_mu_unlock(&sp->server->mu);
-}
-
-static grpc_error* add_socket_to_server(grpc_tcp_server* s, SOCKET sock,
- const grpc_resolved_address* addr,
- unsigned port_index,
- grpc_tcp_listener** listener) {
- grpc_tcp_listener* sp = NULL;
- int port = -1;
- int status;
- GUID guid = WSAID_ACCEPTEX;
- DWORD ioctl_num_bytes;
- LPFN_ACCEPTEX AcceptEx;
- grpc_error* error = GRPC_ERROR_NONE;
-
- /* We need to grab the AcceptEx pointer for that port, as it may be
- interface-dependent. We'll cache it to avoid doing that again. */
- status =
- WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
- &AcceptEx, sizeof(AcceptEx), &ioctl_num_bytes, NULL, NULL);
-
- if (status != 0) {
- char* utf8_message = gpr_format_message(WSAGetLastError());
- gpr_log(GPR_ERROR, "on_connect error: %s", utf8_message);
- gpr_free(utf8_message);
- closesocket(sock);
+ 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,
+ the former socked we created has now either been destroy or assigned
+ to the new connection. We need to create a new one for the next
+ connection. */
+ GPR_ASSERT(GRPC_LOG_IF_ERROR("start_accept", start_accept_locked(sp)));
+ if (0 == --sp->outstanding_calls) {
+ decrement_active_ports_and_notify_locked(sp);
+ }
+ gpr_mu_unlock(&sp->server->mu);
+}
+
+static grpc_error* add_socket_to_server(grpc_tcp_server* s, SOCKET sock,
+ const grpc_resolved_address* addr,
+ unsigned port_index,
+ grpc_tcp_listener** listener) {
+ grpc_tcp_listener* sp = NULL;
+ int port = -1;
+ int status;
+ GUID guid = WSAID_ACCEPTEX;
+ DWORD ioctl_num_bytes;
+ LPFN_ACCEPTEX AcceptEx;
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ /* We need to grab the AcceptEx pointer for that port, as it may be
+ interface-dependent. We'll cache it to avoid doing that again. */
+ status =
+ WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
+ &AcceptEx, sizeof(AcceptEx), &ioctl_num_bytes, NULL, NULL);
+
+ if (status != 0) {
+ char* utf8_message = gpr_format_message(WSAGetLastError());
+ gpr_log(GPR_ERROR, "on_connect error: %s", utf8_message);
+ gpr_free(utf8_message);
+ closesocket(sock);
return GRPC_ERROR_NONE;
- }
-
- error = prepare_socket(sock, addr, &port);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
-
- GPR_ASSERT(port >= 0);
- gpr_mu_lock(&s->mu);
- GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
- sp = (grpc_tcp_listener*)gpr_malloc(sizeof(grpc_tcp_listener));
- sp->next = NULL;
- if (s->head == NULL) {
- s->head = sp;
- } else {
- s->tail->next = sp;
- }
- s->tail = sp;
- sp->server = s;
- sp->socket = grpc_winsocket_create(sock, "listener");
- sp->shutting_down = 0;
- sp->outstanding_calls = 0;
- sp->AcceptEx = AcceptEx;
- sp->new_socket = INVALID_SOCKET;
- sp->port = port;
- sp->port_index = port_index;
- GRPC_CLOSURE_INIT(&sp->on_accept, on_accept, sp, grpc_schedule_on_exec_ctx);
- GPR_ASSERT(sp->socket);
- gpr_mu_unlock(&s->mu);
- *listener = sp;
-
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
- const grpc_resolved_address* addr,
- int* port) {
- grpc_tcp_listener* sp = NULL;
- SOCKET sock;
- grpc_resolved_address addr6_v4mapped;
- grpc_resolved_address wildcard;
- grpc_resolved_address* allocated_addr = NULL;
- grpc_resolved_address sockname_temp;
- unsigned port_index = 0;
- grpc_error* error = GRPC_ERROR_NONE;
-
- if (s->tail != NULL) {
- port_index = s->tail->port_index + 1;
- }
-
- /* Check if this is a wildcard port, and if so, try to keep the port the same
- as some previously created listener. */
- if (grpc_sockaddr_get_port(addr) == 0) {
- for (sp = s->head; sp; sp = sp->next) {
- int sockname_temp_len = sizeof(struct sockaddr_storage);
- if (0 == getsockname(sp->socket->socket,
- (grpc_sockaddr*)sockname_temp.addr,
- &sockname_temp_len)) {
- sockname_temp.len = (size_t)sockname_temp_len;
- *port = grpc_sockaddr_get_port(&sockname_temp);
- if (*port > 0) {
- allocated_addr =
- (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address));
- memcpy(allocated_addr, addr, sizeof(grpc_resolved_address));
- grpc_sockaddr_set_port(allocated_addr, *port);
- addr = allocated_addr;
- break;
- }
- }
- }
- }
-
- if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
- addr = &addr6_v4mapped;
- }
-
- /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
- if (grpc_sockaddr_is_wildcard(addr, port)) {
- grpc_sockaddr_make_wildcard6(*port, &wildcard);
-
- addr = &wildcard;
- }
-
- sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
+ }
+
+ error = prepare_socket(sock, addr, &port);
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+
+ GPR_ASSERT(port >= 0);
+ gpr_mu_lock(&s->mu);
+ GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
+ sp = (grpc_tcp_listener*)gpr_malloc(sizeof(grpc_tcp_listener));
+ sp->next = NULL;
+ if (s->head == NULL) {
+ s->head = sp;
+ } else {
+ s->tail->next = sp;
+ }
+ s->tail = sp;
+ sp->server = s;
+ sp->socket = grpc_winsocket_create(sock, "listener");
+ sp->shutting_down = 0;
+ sp->outstanding_calls = 0;
+ sp->AcceptEx = AcceptEx;
+ sp->new_socket = INVALID_SOCKET;
+ sp->port = port;
+ sp->port_index = port_index;
+ GRPC_CLOSURE_INIT(&sp->on_accept, on_accept, sp, grpc_schedule_on_exec_ctx);
+ GPR_ASSERT(sp->socket);
+ gpr_mu_unlock(&s->mu);
+ *listener = sp;
+
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* tcp_server_add_port(grpc_tcp_server* s,
+ const grpc_resolved_address* addr,
+ int* port) {
+ grpc_tcp_listener* sp = NULL;
+ SOCKET sock;
+ grpc_resolved_address addr6_v4mapped;
+ grpc_resolved_address wildcard;
+ grpc_resolved_address* allocated_addr = NULL;
+ grpc_resolved_address sockname_temp;
+ unsigned port_index = 0;
+ grpc_error* error = GRPC_ERROR_NONE;
+
+ if (s->tail != NULL) {
+ port_index = s->tail->port_index + 1;
+ }
+
+ /* Check if this is a wildcard port, and if so, try to keep the port the same
+ as some previously created listener. */
+ if (grpc_sockaddr_get_port(addr) == 0) {
+ for (sp = s->head; sp; sp = sp->next) {
+ int sockname_temp_len = sizeof(struct sockaddr_storage);
+ if (0 == getsockname(sp->socket->socket,
+ (grpc_sockaddr*)sockname_temp.addr,
+ &sockname_temp_len)) {
+ sockname_temp.len = (size_t)sockname_temp_len;
+ *port = grpc_sockaddr_get_port(&sockname_temp);
+ if (*port > 0) {
+ allocated_addr =
+ (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address));
+ memcpy(allocated_addr, addr, sizeof(grpc_resolved_address));
+ grpc_sockaddr_set_port(allocated_addr, *port);
+ addr = allocated_addr;
+ break;
+ }
+ }
+ }
+ }
+
+ if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
+ addr = &addr6_v4mapped;
+ }
+
+ /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
+ if (grpc_sockaddr_is_wildcard(addr, port)) {
+ grpc_sockaddr_make_wildcard6(*port, &wildcard);
+
+ addr = &wildcard;
+ }
+
+ sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
grpc_get_default_wsa_socket_flags());
- if (sock == INVALID_SOCKET) {
- error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
- goto done;
- }
-
- error = add_socket_to_server(s, sock, addr, port_index, &sp);
-
-done:
- gpr_free(allocated_addr);
-
- if (error != GRPC_ERROR_NONE) {
- grpc_error* error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Failed to add port to server", &error, 1);
- GRPC_ERROR_UNREF(error);
- error = error_out;
- *port = -1;
- } else {
- GPR_ASSERT(sp != NULL);
- *port = sp->port;
- }
- return error;
-}
-
+ if (sock == INVALID_SOCKET) {
+ error = GRPC_WSA_ERROR(WSAGetLastError(), "WSASocket");
+ goto done;
+ }
+
+ error = add_socket_to_server(s, sock, addr, port_index, &sp);
+
+done:
+ gpr_free(allocated_addr);
+
+ if (error != GRPC_ERROR_NONE) {
+ grpc_error* error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Failed to add port to server", &error, 1);
+ GRPC_ERROR_UNREF(error);
+ error = error_out;
+ *port = -1;
+ } else {
+ GPR_ASSERT(sp != NULL);
+ *port = sp->port;
+ }
+ return error;
+}
+
static void tcp_server_start(grpc_tcp_server* s,
const std::vector<grpc_pollset*>* /*pollsets*/,
- grpc_tcp_server_cb on_accept_cb,
- void* on_accept_cb_arg) {
- grpc_tcp_listener* sp;
- GPR_ASSERT(on_accept_cb);
- gpr_mu_lock(&s->mu);
- GPR_ASSERT(!s->on_accept_cb);
- GPR_ASSERT(s->active_ports == 0);
- s->on_accept_cb = on_accept_cb;
- s->on_accept_cb_arg = on_accept_cb_arg;
- for (sp = s->head; sp; sp = sp->next) {
- GPR_ASSERT(GRPC_LOG_IF_ERROR("start_accept", start_accept_locked(sp)));
- s->active_ports++;
- }
- gpr_mu_unlock(&s->mu);
-}
-
-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) {
- return -1;
-}
-
+ grpc_tcp_server_cb on_accept_cb,
+ void* on_accept_cb_arg) {
+ grpc_tcp_listener* sp;
+ GPR_ASSERT(on_accept_cb);
+ gpr_mu_lock(&s->mu);
+ GPR_ASSERT(!s->on_accept_cb);
+ GPR_ASSERT(s->active_ports == 0);
+ s->on_accept_cb = on_accept_cb;
+ s->on_accept_cb_arg = on_accept_cb_arg;
+ for (sp = s->head; sp; sp = sp->next) {
+ GPR_ASSERT(GRPC_LOG_IF_ERROR("start_accept", start_accept_locked(sp)));
+ s->active_ports++;
+ }
+ gpr_mu_unlock(&s->mu);
+}
+
+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) {
+ return -1;
+}
+
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 = {
+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};
-#endif /* GRPC_WINSOCK_SOCKET */
+#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 371b38c9914..b40976c0ca5 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_uv.cc
@@ -1,419 +1,419 @@
-/*
- *
- * 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"
-
-#ifdef GRPC_UV
-#include <limits.h>
-#include <string.h>
-
-#include <grpc/slice_buffer.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/iomgr/error.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/resolve_address_custom.h"
-#include "src/core/lib/iomgr/resource_quota.h"
-#include "src/core/lib/iomgr/tcp_custom.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.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"
+
+#ifdef GRPC_UV
+#include <limits.h>
+#include <string.h>
+
+#include <grpc/slice_buffer.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/iomgr/error.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/resolve_address_custom.h"
+#include "src/core/lib/iomgr/resource_quota.h"
+#include "src/core/lib/iomgr/tcp_custom.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+
#error #include <uv.h>
-
-#define IGNORE_CONST(addr) ((grpc_sockaddr*)(uintptr_t)(addr))
-
-typedef struct uv_socket_t {
- uv_connect_t connect_req;
- uv_write_t write_req;
- uv_shutdown_t shutdown_req;
- uv_tcp_t* handle;
- uv_buf_t* write_buffers;
-
- char* read_buf;
- size_t read_len;
-
+
+#define IGNORE_CONST(addr) ((grpc_sockaddr*)(uintptr_t)(addr))
+
+typedef struct uv_socket_t {
+ uv_connect_t connect_req;
+ uv_write_t write_req;
+ uv_shutdown_t shutdown_req;
+ uv_tcp_t* handle;
+ uv_buf_t* write_buffers;
+
+ char* read_buf;
+ size_t read_len;
+
int pending_connections;
- grpc_custom_socket* accept_socket;
- grpc_error* accept_error;
-
- grpc_custom_connect_callback connect_cb;
- grpc_custom_write_callback write_cb;
- grpc_custom_read_callback read_cb;
- grpc_custom_accept_callback accept_cb;
- grpc_custom_close_callback close_cb;
-
-} uv_socket_t;
-
-static grpc_error* tcp_error_create(const char* desc, int status) {
- if (status == 0) {
- return GRPC_ERROR_NONE;
- }
- grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(desc);
- /* All tcp errors are marked with UNAVAILABLE so that application may
- * choose to retry. */
- error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_UNAVAILABLE);
- return grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,
- grpc_slice_from_static_string(uv_strerror(status)));
-}
-
-static void uv_socket_destroy(grpc_custom_socket* socket) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- gpr_free(uv_socket->handle);
- gpr_free(uv_socket);
-}
-
-static void alloc_uv_buf(uv_handle_t* handle, size_t suggested_size,
- uv_buf_t* buf) {
- uv_socket_t* uv_socket =
- (uv_socket_t*)((grpc_custom_socket*)handle->data)->impl;
- (void)suggested_size;
- buf->base = uv_socket->read_buf;
- buf->len = uv_socket->read_len;
-}
-
-static void uv_read_callback(uv_stream_t* stream, ssize_t nread,
- const uv_buf_t* buf) {
- grpc_error* error = GRPC_ERROR_NONE;
- if (nread == 0) {
- // Nothing happened. Wait for the next callback
- return;
- }
- // TODO(murgatroid99): figure out what the return value here means
- uv_read_stop(stream);
- if (nread == UV_EOF) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF");
- } else if (nread < 0) {
- error = tcp_error_create("TCP Read failed", nread);
- }
- grpc_custom_socket* socket = (grpc_custom_socket*)stream->data;
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- uv_socket->read_cb(socket, (size_t)nread, error);
-}
-
-static void uv_close_callback(uv_handle_t* handle) {
- grpc_custom_socket* socket = (grpc_custom_socket*)handle->data;
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- if (uv_socket->accept_socket) {
- uv_socket->accept_cb(socket, uv_socket->accept_socket,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("socket closed"));
- }
- uv_socket->close_cb(socket);
-}
-
-static void uv_socket_read(grpc_custom_socket* socket, char* buffer,
- size_t length, grpc_custom_read_callback read_cb) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- int status;
- grpc_error* error;
- uv_socket->read_cb = read_cb;
- uv_socket->read_buf = buffer;
- uv_socket->read_len = length;
- // TODO(murgatroid99): figure out what the return value here means
- status =
- uv_read_start((uv_stream_t*)uv_socket->handle, (uv_alloc_cb)alloc_uv_buf,
- (uv_read_cb)uv_read_callback);
- if (status != 0) {
- error = tcp_error_create("TCP Read failed at start", status);
- uv_socket->read_cb(socket, 0, error);
- }
-}
-
-static void uv_write_callback(uv_write_t* req, int status) {
- grpc_custom_socket* socket = (grpc_custom_socket*)req->data;
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- gpr_free(uv_socket->write_buffers);
- uv_socket->write_cb(socket, tcp_error_create("TCP Write failed", status));
-}
-
-void uv_socket_write(grpc_custom_socket* socket,
- grpc_slice_buffer* write_slices,
- grpc_custom_write_callback write_cb) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- uv_socket->write_cb = write_cb;
- uv_buf_t* uv_buffers;
- uv_write_t* write_req;
-
- uv_buffers = (uv_buf_t*)gpr_malloc(sizeof(uv_buf_t) * write_slices->count);
- for (size_t i = 0; i < write_slices->count; i++) {
- uv_buffers[i].base = (char*)GRPC_SLICE_START_PTR(write_slices->slices[i]);
- uv_buffers[i].len = GRPC_SLICE_LENGTH(write_slices->slices[i]);
- }
-
- uv_socket->write_buffers = uv_buffers;
- write_req = &uv_socket->write_req;
- write_req->data = socket;
- // TODO(murgatroid99): figure out what the return value here means
- uv_write(write_req, (uv_stream_t*)uv_socket->handle, uv_buffers,
- write_slices->count, uv_write_callback);
-}
-
-static void shutdown_callback(uv_shutdown_t* req, int status) {}
-
-static void uv_socket_shutdown(grpc_custom_socket* socket) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- uv_shutdown_t* req = &uv_socket->shutdown_req;
- uv_shutdown(req, (uv_stream_t*)uv_socket->handle, shutdown_callback);
-}
-
-static void uv_socket_close(grpc_custom_socket* socket,
- grpc_custom_close_callback close_cb) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- uv_socket->close_cb = close_cb;
- uv_close((uv_handle_t*)uv_socket->handle, uv_close_callback);
-}
-
-static grpc_error* uv_socket_init_helper(uv_socket_t* uv_socket, int domain) {
- uv_tcp_t* tcp = (uv_tcp_t*)gpr_malloc(sizeof(uv_tcp_t));
- uv_socket->handle = tcp;
- int status = uv_tcp_init_ex(uv_default_loop(), tcp, (unsigned int)domain);
- if (status != 0) {
- return tcp_error_create("Failed to initialize UV tcp handle", status);
- }
-#if defined(GPR_LINUX) && defined(SO_REUSEPORT)
- if (domain == AF_INET || domain == AF_INET6) {
- int enable = 1;
- int fd;
- uv_fileno((uv_handle_t*)tcp, &fd);
- // TODO Handle error here.
- setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable));
- }
-#endif
- uv_socket->write_buffers = nullptr;
- uv_socket->read_len = 0;
- uv_tcp_nodelay(uv_socket->handle, 1);
- // 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);
+ grpc_custom_socket* accept_socket;
+ grpc_error* accept_error;
+
+ grpc_custom_connect_callback connect_cb;
+ grpc_custom_write_callback write_cb;
+ grpc_custom_read_callback read_cb;
+ grpc_custom_accept_callback accept_cb;
+ grpc_custom_close_callback close_cb;
+
+} uv_socket_t;
+
+static grpc_error* tcp_error_create(const char* desc, int status) {
+ if (status == 0) {
+ return GRPC_ERROR_NONE;
+ }
+ grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(desc);
+ /* All tcp errors are marked with UNAVAILABLE so that application may
+ * choose to retry. */
+ error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_UNAVAILABLE);
+ return grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,
+ grpc_slice_from_static_string(uv_strerror(status)));
+}
+
+static void uv_socket_destroy(grpc_custom_socket* socket) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ gpr_free(uv_socket->handle);
+ gpr_free(uv_socket);
+}
+
+static void alloc_uv_buf(uv_handle_t* handle, size_t suggested_size,
+ uv_buf_t* buf) {
+ uv_socket_t* uv_socket =
+ (uv_socket_t*)((grpc_custom_socket*)handle->data)->impl;
+ (void)suggested_size;
+ buf->base = uv_socket->read_buf;
+ buf->len = uv_socket->read_len;
+}
+
+static void uv_read_callback(uv_stream_t* stream, ssize_t nread,
+ const uv_buf_t* buf) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (nread == 0) {
+ // Nothing happened. Wait for the next callback
+ return;
+ }
+ // TODO(murgatroid99): figure out what the return value here means
+ uv_read_stop(stream);
+ if (nread == UV_EOF) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF");
+ } else if (nread < 0) {
+ error = tcp_error_create("TCP Read failed", nread);
+ }
+ grpc_custom_socket* socket = (grpc_custom_socket*)stream->data;
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ uv_socket->read_cb(socket, (size_t)nread, error);
+}
+
+static void uv_close_callback(uv_handle_t* handle) {
+ grpc_custom_socket* socket = (grpc_custom_socket*)handle->data;
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ if (uv_socket->accept_socket) {
+ uv_socket->accept_cb(socket, uv_socket->accept_socket,
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("socket closed"));
+ }
+ uv_socket->close_cb(socket);
+}
+
+static void uv_socket_read(grpc_custom_socket* socket, char* buffer,
+ size_t length, grpc_custom_read_callback read_cb) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ int status;
+ grpc_error* error;
+ uv_socket->read_cb = read_cb;
+ uv_socket->read_buf = buffer;
+ uv_socket->read_len = length;
+ // TODO(murgatroid99): figure out what the return value here means
+ status =
+ uv_read_start((uv_stream_t*)uv_socket->handle, (uv_alloc_cb)alloc_uv_buf,
+ (uv_read_cb)uv_read_callback);
+ if (status != 0) {
+ error = tcp_error_create("TCP Read failed at start", status);
+ uv_socket->read_cb(socket, 0, error);
+ }
+}
+
+static void uv_write_callback(uv_write_t* req, int status) {
+ grpc_custom_socket* socket = (grpc_custom_socket*)req->data;
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ gpr_free(uv_socket->write_buffers);
+ uv_socket->write_cb(socket, tcp_error_create("TCP Write failed", status));
+}
+
+void uv_socket_write(grpc_custom_socket* socket,
+ grpc_slice_buffer* write_slices,
+ grpc_custom_write_callback write_cb) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ uv_socket->write_cb = write_cb;
+ uv_buf_t* uv_buffers;
+ uv_write_t* write_req;
+
+ uv_buffers = (uv_buf_t*)gpr_malloc(sizeof(uv_buf_t) * write_slices->count);
+ for (size_t i = 0; i < write_slices->count; i++) {
+ uv_buffers[i].base = (char*)GRPC_SLICE_START_PTR(write_slices->slices[i]);
+ uv_buffers[i].len = GRPC_SLICE_LENGTH(write_slices->slices[i]);
+ }
+
+ uv_socket->write_buffers = uv_buffers;
+ write_req = &uv_socket->write_req;
+ write_req->data = socket;
+ // TODO(murgatroid99): figure out what the return value here means
+ uv_write(write_req, (uv_stream_t*)uv_socket->handle, uv_buffers,
+ write_slices->count, uv_write_callback);
+}
+
+static void shutdown_callback(uv_shutdown_t* req, int status) {}
+
+static void uv_socket_shutdown(grpc_custom_socket* socket) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ uv_shutdown_t* req = &uv_socket->shutdown_req;
+ uv_shutdown(req, (uv_stream_t*)uv_socket->handle, shutdown_callback);
+}
+
+static void uv_socket_close(grpc_custom_socket* socket,
+ grpc_custom_close_callback close_cb) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ uv_socket->close_cb = close_cb;
+ uv_close((uv_handle_t*)uv_socket->handle, uv_close_callback);
+}
+
+static grpc_error* uv_socket_init_helper(uv_socket_t* uv_socket, int domain) {
+ uv_tcp_t* tcp = (uv_tcp_t*)gpr_malloc(sizeof(uv_tcp_t));
+ uv_socket->handle = tcp;
+ int status = uv_tcp_init_ex(uv_default_loop(), tcp, (unsigned int)domain);
+ if (status != 0) {
+ return tcp_error_create("Failed to initialize UV tcp handle", status);
+ }
+#if defined(GPR_LINUX) && defined(SO_REUSEPORT)
+ if (domain == AF_INET || domain == AF_INET6) {
+ int enable = 1;
+ int fd;
+ uv_fileno((uv_handle_t*)tcp, &fd);
+ // TODO Handle error here.
+ setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable));
+ }
+#endif
+ uv_socket->write_buffers = nullptr;
+ uv_socket->read_len = 0;
+ uv_tcp_nodelay(uv_socket->handle, 1);
+ // 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->accept_socket = nullptr;
- uv_socket->accept_error = GRPC_ERROR_NONE;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* uv_socket_init(grpc_custom_socket* socket, int domain) {
- uv_socket_t* uv_socket = (uv_socket_t*)gpr_malloc(sizeof(uv_socket_t));
- grpc_error* error = uv_socket_init_helper(uv_socket, domain);
- if (error != GRPC_ERROR_NONE) {
- return error;
- }
- uv_socket->handle->data = socket;
- socket->impl = uv_socket;
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* uv_socket_getpeername(grpc_custom_socket* socket,
- const grpc_sockaddr* addr,
- int* addr_len) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- int err = uv_tcp_getpeername(uv_socket->handle,
- (struct sockaddr*)IGNORE_CONST(addr), addr_len);
- return tcp_error_create("getpeername failed", err);
-}
-
-static grpc_error* uv_socket_getsockname(grpc_custom_socket* socket,
- const grpc_sockaddr* addr,
- int* addr_len) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- int err = uv_tcp_getsockname(uv_socket->handle,
- (struct sockaddr*)IGNORE_CONST(addr), addr_len);
- return tcp_error_create("getsockname failed", err);
-}
-
-static void accept_new_connection(grpc_custom_socket* socket) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ uv_socket->accept_socket = nullptr;
+ uv_socket->accept_error = GRPC_ERROR_NONE;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* uv_socket_init(grpc_custom_socket* socket, int domain) {
+ uv_socket_t* uv_socket = (uv_socket_t*)gpr_malloc(sizeof(uv_socket_t));
+ grpc_error* error = uv_socket_init_helper(uv_socket, domain);
+ if (error != GRPC_ERROR_NONE) {
+ return error;
+ }
+ uv_socket->handle->data = socket;
+ socket->impl = uv_socket;
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* uv_socket_getpeername(grpc_custom_socket* socket,
+ const grpc_sockaddr* addr,
+ int* addr_len) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ int err = uv_tcp_getpeername(uv_socket->handle,
+ (struct sockaddr*)IGNORE_CONST(addr), addr_len);
+ return tcp_error_create("getpeername failed", err);
+}
+
+static grpc_error* uv_socket_getsockname(grpc_custom_socket* socket,
+ const grpc_sockaddr* addr,
+ int* addr_len) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ int err = uv_tcp_getsockname(uv_socket->handle,
+ (struct sockaddr*)IGNORE_CONST(addr), addr_len);
+ return tcp_error_create("getsockname failed", err);
+}
+
+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) {
- 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;
+ 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;
- if (uv_socket->accept_error != GRPC_ERROR_NONE) {
- uv_stream_t dummy_handle;
- uv_accept((uv_stream_t*)uv_socket->handle, &dummy_handle);
- uv_socket->accept_cb(socket, new_socket, error);
- } else {
- uv_socket_t* uv_new_socket = (uv_socket_t*)gpr_malloc(sizeof(uv_socket_t));
- uv_socket_init_helper(uv_new_socket, AF_UNSPEC);
- // UV documentation says this is guaranteed to succeed
- GPR_ASSERT(uv_accept((uv_stream_t*)uv_socket->handle,
- (uv_stream_t*)uv_new_socket->handle) == 0);
- new_socket->impl = uv_new_socket;
- uv_new_socket->handle->data = new_socket;
- uv_socket->accept_cb(socket, new_socket, error);
- }
-}
-
-static void uv_on_connect(uv_stream_t* server, int status) {
- grpc_custom_socket* socket = (grpc_custom_socket*)server->data;
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- if (status < 0) {
- switch (status) {
- case UV_EINTR:
- case UV_EAGAIN:
- return;
- default:
- uv_socket->accept_error = tcp_error_create("accept failed", status);
- }
- }
+ if (uv_socket->accept_error != GRPC_ERROR_NONE) {
+ uv_stream_t dummy_handle;
+ uv_accept((uv_stream_t*)uv_socket->handle, &dummy_handle);
+ uv_socket->accept_cb(socket, new_socket, error);
+ } else {
+ uv_socket_t* uv_new_socket = (uv_socket_t*)gpr_malloc(sizeof(uv_socket_t));
+ uv_socket_init_helper(uv_new_socket, AF_UNSPEC);
+ // UV documentation says this is guaranteed to succeed
+ GPR_ASSERT(uv_accept((uv_stream_t*)uv_socket->handle,
+ (uv_stream_t*)uv_new_socket->handle) == 0);
+ new_socket->impl = uv_new_socket;
+ uv_new_socket->handle->data = new_socket;
+ uv_socket->accept_cb(socket, new_socket, error);
+ }
+}
+
+static void uv_on_connect(uv_stream_t* server, int status) {
+ grpc_custom_socket* socket = (grpc_custom_socket*)server->data;
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ if (status < 0) {
+ switch (status) {
+ case UV_EINTR:
+ case UV_EAGAIN:
+ return;
+ default:
+ uv_socket->accept_error = tcp_error_create("accept failed", status);
+ }
+ }
uv_socket->pending_connections += 1;
- accept_new_connection(socket);
-}
-
-void uv_socket_accept(grpc_custom_socket* socket,
- grpc_custom_socket* new_socket,
- grpc_custom_accept_callback accept_cb) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- uv_socket->accept_cb = accept_cb;
- GPR_ASSERT(uv_socket->accept_socket == nullptr);
- uv_socket->accept_socket = new_socket;
- accept_new_connection(socket);
-}
-
-static grpc_error* uv_socket_bind(grpc_custom_socket* socket,
- const grpc_sockaddr* addr, size_t len,
- int flags) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- int status =
- uv_tcp_bind((uv_tcp_t*)uv_socket->handle, (struct sockaddr*)addr, 0);
- return tcp_error_create("Failed to bind to port", status);
-}
-
-static grpc_error* uv_socket_listen(grpc_custom_socket* socket) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- int status =
- uv_listen((uv_stream_t*)uv_socket->handle, SOMAXCONN, uv_on_connect);
- return tcp_error_create("Failed to listen to port", status);
-}
-
-static void uv_tc_on_connect(uv_connect_t* req, int status) {
- grpc_custom_socket* socket = (grpc_custom_socket*)req->data;
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- grpc_error* error;
- if (status == UV_ECANCELED) {
- // This should only happen if the handle is already closed
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Timeout occurred");
- } else {
- error = tcp_error_create("Failed to connect to remote host", status);
- }
- uv_socket->connect_cb(socket, error);
-}
-
-static void uv_socket_connect(grpc_custom_socket* socket,
- const grpc_sockaddr* addr, size_t len,
- grpc_custom_connect_callback connect_cb) {
- uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
- uv_socket->connect_cb = connect_cb;
- uv_socket->connect_req.data = socket;
- int status = uv_tcp_connect(&uv_socket->connect_req, uv_socket->handle,
- (struct sockaddr*)addr, uv_tc_on_connect);
- if (status != 0) {
- // The callback will not be called
- uv_socket->connect_cb(socket, tcp_error_create("connect failed", status));
- }
-}
-
-static grpc_resolved_addresses* handle_addrinfo_result(
- struct addrinfo* result) {
- struct addrinfo* resp;
- size_t i;
- grpc_resolved_addresses* addresses =
- (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses));
- addresses->naddrs = 0;
- for (resp = result; resp != nullptr; resp = resp->ai_next) {
- addresses->naddrs++;
- }
- addresses->addrs = (grpc_resolved_address*)gpr_malloc(
- sizeof(grpc_resolved_address) * addresses->naddrs);
- for (resp = result, i = 0; resp != nullptr; resp = resp->ai_next, i++) {
- memcpy(&addresses->addrs[i].addr, resp->ai_addr, resp->ai_addrlen);
- addresses->addrs[i].len = resp->ai_addrlen;
- }
- // addrinfo objects are allocated by libuv (e.g. in uv_getaddrinfo)
- // and not by gpr_malloc
- uv_freeaddrinfo(result);
- return addresses;
-}
-
-static void uv_resolve_callback(uv_getaddrinfo_t* req, int status,
- struct addrinfo* res) {
- grpc_custom_resolver* r = (grpc_custom_resolver*)req->data;
- gpr_free(req);
- grpc_resolved_addresses* result = nullptr;
- if (status == 0) {
- result = handle_addrinfo_result(res);
- }
- grpc_custom_resolve_callback(r, result,
- tcp_error_create("getaddrinfo failed", status));
-}
-
+ accept_new_connection(socket);
+}
+
+void uv_socket_accept(grpc_custom_socket* socket,
+ grpc_custom_socket* new_socket,
+ grpc_custom_accept_callback accept_cb) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ uv_socket->accept_cb = accept_cb;
+ GPR_ASSERT(uv_socket->accept_socket == nullptr);
+ uv_socket->accept_socket = new_socket;
+ accept_new_connection(socket);
+}
+
+static grpc_error* uv_socket_bind(grpc_custom_socket* socket,
+ const grpc_sockaddr* addr, size_t len,
+ int flags) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ int status =
+ uv_tcp_bind((uv_tcp_t*)uv_socket->handle, (struct sockaddr*)addr, 0);
+ return tcp_error_create("Failed to bind to port", status);
+}
+
+static grpc_error* uv_socket_listen(grpc_custom_socket* socket) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ int status =
+ uv_listen((uv_stream_t*)uv_socket->handle, SOMAXCONN, uv_on_connect);
+ return tcp_error_create("Failed to listen to port", status);
+}
+
+static void uv_tc_on_connect(uv_connect_t* req, int status) {
+ grpc_custom_socket* socket = (grpc_custom_socket*)req->data;
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ grpc_error* error;
+ if (status == UV_ECANCELED) {
+ // This should only happen if the handle is already closed
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Timeout occurred");
+ } else {
+ error = tcp_error_create("Failed to connect to remote host", status);
+ }
+ uv_socket->connect_cb(socket, error);
+}
+
+static void uv_socket_connect(grpc_custom_socket* socket,
+ const grpc_sockaddr* addr, size_t len,
+ grpc_custom_connect_callback connect_cb) {
+ uv_socket_t* uv_socket = (uv_socket_t*)socket->impl;
+ uv_socket->connect_cb = connect_cb;
+ uv_socket->connect_req.data = socket;
+ int status = uv_tcp_connect(&uv_socket->connect_req, uv_socket->handle,
+ (struct sockaddr*)addr, uv_tc_on_connect);
+ if (status != 0) {
+ // The callback will not be called
+ uv_socket->connect_cb(socket, tcp_error_create("connect failed", status));
+ }
+}
+
+static grpc_resolved_addresses* handle_addrinfo_result(
+ struct addrinfo* result) {
+ struct addrinfo* resp;
+ size_t i;
+ grpc_resolved_addresses* addresses =
+ (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses));
+ addresses->naddrs = 0;
+ for (resp = result; resp != nullptr; resp = resp->ai_next) {
+ addresses->naddrs++;
+ }
+ addresses->addrs = (grpc_resolved_address*)gpr_malloc(
+ sizeof(grpc_resolved_address) * addresses->naddrs);
+ for (resp = result, i = 0; resp != nullptr; resp = resp->ai_next, i++) {
+ memcpy(&addresses->addrs[i].addr, resp->ai_addr, resp->ai_addrlen);
+ addresses->addrs[i].len = resp->ai_addrlen;
+ }
+ // addrinfo objects are allocated by libuv (e.g. in uv_getaddrinfo)
+ // and not by gpr_malloc
+ uv_freeaddrinfo(result);
+ return addresses;
+}
+
+static void uv_resolve_callback(uv_getaddrinfo_t* req, int status,
+ struct addrinfo* res) {
+ grpc_custom_resolver* r = (grpc_custom_resolver*)req->data;
+ gpr_free(req);
+ grpc_resolved_addresses* result = nullptr;
+ if (status == 0) {
+ result = handle_addrinfo_result(res);
+ }
+ grpc_custom_resolve_callback(r, result,
+ tcp_error_create("getaddrinfo failed", status));
+}
+
static grpc_error* uv_resolve(const char* host, const char* port,
- grpc_resolved_addresses** result) {
- int status;
- uv_getaddrinfo_t req;
- struct addrinfo hints;
- memset(&hints, 0, sizeof(struct addrinfo));
- hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
- hints.ai_socktype = SOCK_STREAM; /* stream socket */
- hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
- status = uv_getaddrinfo(uv_default_loop(), &req, NULL, host, port, &hints);
- if (status != 0) {
- *result = nullptr;
- } else {
- *result = handle_addrinfo_result(req.addrinfo);
- }
- return tcp_error_create("getaddrinfo failed", status);
-}
-
+ grpc_resolved_addresses** result) {
+ int status;
+ uv_getaddrinfo_t req;
+ struct addrinfo hints;
+ memset(&hints, 0, sizeof(struct addrinfo));
+ hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
+ hints.ai_socktype = SOCK_STREAM; /* stream socket */
+ hints.ai_flags = AI_PASSIVE; /* for wildcard IP address */
+ status = uv_getaddrinfo(uv_default_loop(), &req, NULL, host, port, &hints);
+ if (status != 0) {
+ *result = nullptr;
+ } else {
+ *result = handle_addrinfo_result(req.addrinfo);
+ }
+ return tcp_error_create("getaddrinfo failed", status);
+}
+
static void uv_resolve_async(grpc_custom_resolver* r, const char* host,
const char* port) {
- int status;
- uv_getaddrinfo_t* req =
- (uv_getaddrinfo_t*)gpr_malloc(sizeof(uv_getaddrinfo_t));
- req->data = r;
- struct addrinfo hints;
- memset(&hints, 0, sizeof(struct addrinfo));
- hints.ai_family = GRPC_AF_UNSPEC; /* ipv4 or ipv6 */
- hints.ai_socktype = GRPC_SOCK_STREAM; /* stream socket */
- hints.ai_flags = GRPC_AI_PASSIVE; /* for wildcard IP address */
- status = uv_getaddrinfo(uv_default_loop(), req, uv_resolve_callback, host,
- port, &hints);
- if (status != 0) {
- gpr_free(req);
- grpc_error* error = tcp_error_create("getaddrinfo failed", status);
- grpc_custom_resolve_callback(r, NULL, error);
- }
-}
-
-grpc_custom_resolver_vtable uv_resolver_vtable = {uv_resolve, uv_resolve_async};
-
-grpc_socket_vtable grpc_uv_socket_vtable = {
- uv_socket_init, uv_socket_connect, uv_socket_destroy,
- uv_socket_shutdown, uv_socket_close, uv_socket_write,
- uv_socket_read, uv_socket_getpeername, uv_socket_getsockname,
- uv_socket_bind, uv_socket_listen, uv_socket_accept};
-
-#endif
+ int status;
+ uv_getaddrinfo_t* req =
+ (uv_getaddrinfo_t*)gpr_malloc(sizeof(uv_getaddrinfo_t));
+ req->data = r;
+ struct addrinfo hints;
+ memset(&hints, 0, sizeof(struct addrinfo));
+ hints.ai_family = GRPC_AF_UNSPEC; /* ipv4 or ipv6 */
+ hints.ai_socktype = GRPC_SOCK_STREAM; /* stream socket */
+ hints.ai_flags = GRPC_AI_PASSIVE; /* for wildcard IP address */
+ status = uv_getaddrinfo(uv_default_loop(), req, uv_resolve_callback, host,
+ port, &hints);
+ if (status != 0) {
+ gpr_free(req);
+ grpc_error* error = tcp_error_create("getaddrinfo failed", status);
+ grpc_custom_resolve_callback(r, NULL, error);
+ }
+}
+
+grpc_custom_resolver_vtable uv_resolver_vtable = {uv_resolve, uv_resolve_async};
+
+grpc_socket_vtable grpc_uv_socket_vtable = {
+ uv_socket_init, uv_socket_connect, uv_socket_destroy,
+ uv_socket_shutdown, uv_socket_close, uv_socket_write,
+ uv_socket_read, uv_socket_getpeername, uv_socket_getsockname,
+ uv_socket_bind, uv_socket_listen, uv_socket_accept};
+
+#endif
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 3d410a2d3fc..69f150936aa 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc
@@ -1,201 +1,201 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
-
-#include <limits.h>
-
-#include "src/core/lib/iomgr/sockaddr_windows.h"
-
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/log_windows.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/iocp_windows.h"
-#include "src/core/lib/iomgr/sockaddr.h"
-#include "src/core/lib/iomgr/sockaddr_utils.h"
-#include "src/core/lib/iomgr/socket_windows.h"
-#include "src/core/lib/iomgr/tcp_client.h"
-#include "src/core/lib/iomgr/tcp_windows.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/slice/slice_internal.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/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
+
+#include <limits.h>
+
+#include "src/core/lib/iomgr/sockaddr_windows.h"
+
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_windows.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/iocp_windows.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+#include "src/core/lib/iomgr/sockaddr_utils.h"
+#include "src/core/lib/iomgr/socket_windows.h"
+#include "src/core/lib/iomgr/tcp_client.h"
+#include "src/core/lib/iomgr/tcp_windows.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
-
-#if defined(__MSYS__) && defined(GPR_ARCH_64)
-/* Nasty workaround for nasty bug when using the 64 bits msys compiler
- in conjunction with Microsoft Windows headers. */
-#define GRPC_FIONBIO _IOW('f', 126, uint32_t)
-#else
-#define GRPC_FIONBIO FIONBIO
-#endif
-
-extern grpc_core::TraceFlag grpc_tcp_trace;
-
+
+#if defined(__MSYS__) && defined(GPR_ARCH_64)
+/* Nasty workaround for nasty bug when using the 64 bits msys compiler
+ in conjunction with Microsoft Windows headers. */
+#define GRPC_FIONBIO _IOW('f', 126, uint32_t)
+#else
+#define GRPC_FIONBIO FIONBIO
+#endif
+
+extern grpc_core::TraceFlag grpc_tcp_trace;
+
grpc_error* grpc_tcp_set_non_block(SOCKET sock) {
- int status;
- uint32_t param = 1;
- DWORD ret;
- status = WSAIoctl(sock, GRPC_FIONBIO, &param, sizeof(param), NULL, 0, &ret,
- NULL, NULL);
- return status == 0
- ? GRPC_ERROR_NONE
- : GRPC_WSA_ERROR(WSAGetLastError(), "WSAIoctl(GRPC_FIONBIO)");
-}
-
-static grpc_error* set_dualstack(SOCKET sock) {
- int status;
- unsigned long param = 0;
- status = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&param,
- sizeof(param));
- return status == 0
- ? GRPC_ERROR_NONE
- : GRPC_WSA_ERROR(WSAGetLastError(), "setsockopt(IPV6_V6ONLY)");
-}
-
+ int status;
+ uint32_t param = 1;
+ DWORD ret;
+ status = WSAIoctl(sock, GRPC_FIONBIO, &param, sizeof(param), NULL, 0, &ret,
+ NULL, NULL);
+ return status == 0
+ ? GRPC_ERROR_NONE
+ : GRPC_WSA_ERROR(WSAGetLastError(), "WSAIoctl(GRPC_FIONBIO)");
+}
+
+static grpc_error* set_dualstack(SOCKET sock) {
+ int status;
+ unsigned long param = 0;
+ status = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&param,
+ sizeof(param));
+ return status == 0
+ ? GRPC_ERROR_NONE
+ : GRPC_WSA_ERROR(WSAGetLastError(), "setsockopt(IPV6_V6ONLY)");
+}
+
static grpc_error* enable_socket_low_latency(SOCKET sock) {
- int status;
+ int status;
BOOL param = TRUE;
status = ::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<char*>(&param), sizeof(param));
- if (status == SOCKET_ERROR) {
- status = WSAGetLastError();
- }
+ if (status == SOCKET_ERROR) {
+ status = WSAGetLastError();
+ }
return status == 0 ? GRPC_ERROR_NONE
: GRPC_WSA_ERROR(status, "setsockopt(TCP_NODELAY)");
-}
-
-grpc_error* grpc_tcp_prepare_socket(SOCKET sock) {
- grpc_error* err;
+}
+
+grpc_error* grpc_tcp_prepare_socket(SOCKET sock) {
+ grpc_error* err;
err = grpc_tcp_set_non_block(sock);
- if (err != GRPC_ERROR_NONE) return err;
- err = set_dualstack(sock);
- if (err != GRPC_ERROR_NONE) return err;
+ if (err != GRPC_ERROR_NONE) return err;
+ err = set_dualstack(sock);
+ if (err != GRPC_ERROR_NONE) return err;
err = enable_socket_low_latency(sock);
- if (err != GRPC_ERROR_NONE) return err;
- return GRPC_ERROR_NONE;
-}
-
-typedef struct grpc_tcp {
- /* This is our C++ class derivation emulation. */
- grpc_endpoint base;
- /* The one socket this endpoint is using. */
- grpc_winsocket* socket;
- /* Refcounting how many operations are in progress. */
- gpr_refcount refcount;
-
- grpc_closure on_read;
- grpc_closure on_write;
-
- grpc_closure* read_cb;
- grpc_closure* write_cb;
+ if (err != GRPC_ERROR_NONE) return err;
+ return GRPC_ERROR_NONE;
+}
+
+typedef struct grpc_tcp {
+ /* This is our C++ class derivation emulation. */
+ grpc_endpoint base;
+ /* The one socket this endpoint is using. */
+ grpc_winsocket* socket;
+ /* Refcounting how many operations are in progress. */
+ gpr_refcount refcount;
+
+ grpc_closure on_read;
+ grpc_closure on_write;
+
+ grpc_closure* read_cb;
+ grpc_closure* write_cb;
/* garbage after the last read */
grpc_slice_buffer last_read_buffer;
- grpc_slice_buffer* write_slices;
- grpc_slice_buffer* read_slices;
-
- grpc_resource_user* resource_user;
-
- /* The IO Completion Port runs from another thread. We need some mechanism
- to protect ourselves when requesting a shutdown. */
- gpr_mu mu;
- int shutting_down;
- grpc_error* shutdown_error;
-
+ grpc_slice_buffer* write_slices;
+ grpc_slice_buffer* read_slices;
+
+ grpc_resource_user* resource_user;
+
+ /* The IO Completion Port runs from another thread. We need some mechanism
+ to protect ourselves when requesting a shutdown. */
+ gpr_mu mu;
+ int shutting_down;
+ grpc_error* shutdown_error;
+
TString peer_string;
TString local_address;
-} grpc_tcp;
-
-static void tcp_free(grpc_tcp* tcp) {
- grpc_winsocket_destroy(tcp->socket);
- gpr_mu_destroy(&tcp->mu);
+} grpc_tcp;
+
+static void tcp_free(grpc_tcp* tcp) {
+ grpc_winsocket_destroy(tcp->socket);
+ gpr_mu_destroy(&tcp->mu);
grpc_slice_buffer_destroy_internal(&tcp->last_read_buffer);
- grpc_resource_user_unref(tcp->resource_user);
- if (tcp->shutting_down) GRPC_ERROR_UNREF(tcp->shutdown_error);
+ grpc_resource_user_unref(tcp->resource_user);
+ if (tcp->shutting_down) GRPC_ERROR_UNREF(tcp->shutdown_error);
delete tcp;
-}
-
-#ifndef NDEBUG
-#define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), __FILE__, __LINE__)
-#define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__)
-static void tcp_unref(grpc_tcp* tcp, const char* reason, const char* file,
- int line) {
- if (grpc_tcp_trace.enabled()) {
- gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
- gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
- "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
- val - 1);
- }
- if (gpr_unref(&tcp->refcount)) {
- tcp_free(tcp);
- }
-}
-
-static void tcp_ref(grpc_tcp* tcp, const char* reason, const char* file,
- int line) {
- if (grpc_tcp_trace.enabled()) {
- gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
- gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
- "TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
- val + 1);
- }
- gpr_ref(&tcp->refcount);
-}
-#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_unref(&tcp->refcount)) {
- tcp_free(tcp);
- }
-}
-
-static void tcp_ref(grpc_tcp* tcp) { gpr_ref(&tcp->refcount); }
-#endif
-
-/* Asynchronous callback from the IOCP, or the background thread. */
-static void on_read(void* tcpp, grpc_error* error) {
- grpc_tcp* tcp = (grpc_tcp*)tcpp;
- grpc_closure* cb = tcp->read_cb;
- grpc_winsocket* socket = tcp->socket;
- grpc_winsocket_callback_info* info = &socket->read_info;
-
+}
+
+#ifndef NDEBUG
+#define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), __FILE__, __LINE__)
+#define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__)
+static void tcp_unref(grpc_tcp* tcp, const char* reason, const char* file,
+ int line) {
+ if (grpc_tcp_trace.enabled()) {
+ gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
+ gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
+ "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
+ val - 1);
+ }
+ if (gpr_unref(&tcp->refcount)) {
+ tcp_free(tcp);
+ }
+}
+
+static void tcp_ref(grpc_tcp* tcp, const char* reason, const char* file,
+ int line) {
+ if (grpc_tcp_trace.enabled()) {
+ gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
+ gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,
+ "TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val,
+ val + 1);
+ }
+ gpr_ref(&tcp->refcount);
+}
+#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_unref(&tcp->refcount)) {
+ tcp_free(tcp);
+ }
+}
+
+static void tcp_ref(grpc_tcp* tcp) { gpr_ref(&tcp->refcount); }
+#endif
+
+/* Asynchronous callback from the IOCP, or the background thread. */
+static void on_read(void* tcpp, grpc_error* error) {
+ grpc_tcp* tcp = (grpc_tcp*)tcpp;
+ grpc_closure* cb = tcp->read_cb;
+ grpc_winsocket* socket = tcp->socket;
+ grpc_winsocket_callback_info* info = &socket->read_info;
+
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_INFO, "TCP:%p on_read", tcp);
}
- GRPC_ERROR_REF(error);
-
- if (error == GRPC_ERROR_NONE) {
- if (info->wsa_error != 0 && !tcp->shutting_down) {
- char* utf8_message = gpr_format_message(info->wsa_error);
- error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(utf8_message);
- gpr_free(utf8_message);
+ GRPC_ERROR_REF(error);
+
+ if (error == GRPC_ERROR_NONE) {
+ if (info->wsa_error != 0 && !tcp->shutting_down) {
+ char* utf8_message = gpr_format_message(info->wsa_error);
+ error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(utf8_message);
+ gpr_free(utf8_message);
grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
- } else {
+ } 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) !=
@@ -218,144 +218,144 @@ static void on_read(void* tcpp, grpc_error* error) {
gpr_free(dump);
}
}
- } else {
+ } else {
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_INFO, "TCP:%p unref read_slice", tcp);
}
grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
- error = tcp->shutting_down
- ? GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "TCP stream shutting down", &tcp->shutdown_error, 1)
- : GRPC_ERROR_CREATE_FROM_STATIC_STRING("End of TCP stream");
- }
- }
- }
-
- tcp->read_cb = NULL;
- TCP_UNREF(tcp, "read");
+ error = tcp->shutting_down
+ ? GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "TCP stream shutting down", &tcp->shutdown_error, 1)
+ : GRPC_ERROR_CREATE_FROM_STATIC_STRING("End of TCP stream");
+ }
+ }
+ }
+
+ tcp->read_cb = NULL;
+ TCP_UNREF(tcp, "read");
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,
+static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
grpc_closure* cb, bool urgent) {
- grpc_tcp* tcp = (grpc_tcp*)ep;
- grpc_winsocket* handle = tcp->socket;
- grpc_winsocket_callback_info* info = &handle->read_info;
- int status;
- DWORD bytes_read = 0;
- DWORD flags = 0;
+ grpc_tcp* tcp = (grpc_tcp*)ep;
+ grpc_winsocket* handle = tcp->socket;
+ grpc_winsocket_callback_info* info = &handle->read_info;
+ int status;
+ DWORD bytes_read = 0;
+ DWORD flags = 0;
WSABUF buffers[MAX_WSABUF_COUNT];
size_t i;
-
+
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_INFO, "TCP:%p win_read", tcp);
}
- if (tcp->shutting_down) {
+ 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));
- return;
- }
-
- tcp->read_cb = cb;
- tcp->read_slices = read_slices;
- grpc_slice_buffer_reset_and_unref_internal(read_slices);
+ return;
+ }
+
+ tcp->read_cb = cb;
+ tcp->read_slices = read_slices;
+ grpc_slice_buffer_reset_and_unref_internal(read_slices);
grpc_slice_buffer_swap(read_slices, &tcp->last_read_buffer);
-
+
if (tcp->read_slices->length < DEFAULT_TARGET_READ_SIZE / 2 &&
tcp->read_slices->count < MAX_WSABUF_COUNT) {
// TODO(jtattermusch): slice should be allocated using resource quota
grpc_slice_buffer_add(tcp->read_slices,
GRPC_SLICE_MALLOC(DEFAULT_TARGET_READ_SIZE));
}
-
+
GPR_ASSERT(tcp->read_slices->count <= MAX_WSABUF_COUNT);
for (i = 0; i < tcp->read_slices->count; i++) {
buffers[i].len = (ULONG)GRPC_SLICE_LENGTH(
tcp->read_slices->slices[i]); // we know slice size fits in 32bit.
buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[i]);
}
-
- TCP_REF(tcp, "read");
-
- /* First let's try a synchronous, non-blocking read. */
+
+ TCP_REF(tcp, "read");
+
+ /* First let's try a synchronous, non-blocking read. */
status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count,
&bytes_read, &flags, NULL, NULL);
- info->wsa_error = status == 0 ? 0 : WSAGetLastError();
-
- /* Did we get data immediately ? Yay. */
- if (info->wsa_error != WSAEWOULDBLOCK) {
+ info->wsa_error = status == 0 ? 0 : WSAGetLastError();
+
+ /* 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);
- return;
- }
-
- /* Otherwise, let's retry, by queuing a read. */
- memset(&tcp->socket->read_info.overlapped, 0, sizeof(OVERLAPPED));
+ return;
+ }
+
+ /* Otherwise, let's retry, by queuing a read. */
+ memset(&tcp->socket->read_info.overlapped, 0, sizeof(OVERLAPPED));
status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count,
&bytes_read, &flags, &info->overlapped, NULL);
-
- if (status != 0) {
- int wsa_error = WSAGetLastError();
- if (wsa_error != WSA_IO_PENDING) {
- info->wsa_error = wsa_error;
+
+ if (status != 0) {
+ 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"));
- return;
- }
- }
-
- grpc_socket_notify_on_read(tcp->socket, &tcp->on_read);
-}
-
-/* Asynchronous callback from the IOCP, or the background thread. */
-static void on_write(void* tcpp, grpc_error* error) {
- grpc_tcp* tcp = (grpc_tcp*)tcpp;
- grpc_winsocket* handle = tcp->socket;
- grpc_winsocket_callback_info* info = &handle->write_info;
- grpc_closure* cb;
-
+ return;
+ }
+ }
+
+ grpc_socket_notify_on_read(tcp->socket, &tcp->on_read);
+}
+
+/* Asynchronous callback from the IOCP, or the background thread. */
+static void on_write(void* tcpp, grpc_error* error) {
+ grpc_tcp* tcp = (grpc_tcp*)tcpp;
+ grpc_winsocket* handle = tcp->socket;
+ grpc_winsocket_callback_info* info = &handle->write_info;
+ grpc_closure* cb;
+
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_INFO, "TCP:%p on_write", tcp);
}
- GRPC_ERROR_REF(error);
-
- gpr_mu_lock(&tcp->mu);
- cb = tcp->write_cb;
- tcp->write_cb = NULL;
- gpr_mu_unlock(&tcp->mu);
-
- if (error == GRPC_ERROR_NONE) {
- if (info->wsa_error != 0) {
- error = GRPC_WSA_ERROR(info->wsa_error, "WSASend");
- } else {
+ GRPC_ERROR_REF(error);
+
+ gpr_mu_lock(&tcp->mu);
+ cb = tcp->write_cb;
+ tcp->write_cb = NULL;
+ gpr_mu_unlock(&tcp->mu);
+
+ if (error == GRPC_ERROR_NONE) {
+ if (info->wsa_error != 0) {
+ error = GRPC_WSA_ERROR(info->wsa_error, "WSASend");
+ } else {
GPR_ASSERT(info->bytes_transferred == tcp->write_slices->length);
- }
- }
-
- TCP_UNREF(tcp, "write");
+ }
+ }
+
+ TCP_UNREF(tcp, "write");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
-}
-
-/* Initiates a write. */
-static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
+}
+
+/* Initiates a write. */
+static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
grpc_closure* cb, void* arg) {
- grpc_tcp* tcp = (grpc_tcp*)ep;
- grpc_winsocket* socket = tcp->socket;
- grpc_winsocket_callback_info* info = &socket->write_info;
- unsigned i;
- DWORD bytes_sent;
- int status;
+ grpc_tcp* tcp = (grpc_tcp*)ep;
+ grpc_winsocket* socket = tcp->socket;
+ grpc_winsocket_callback_info* info = &socket->write_info;
+ unsigned i;
+ DWORD bytes_sent;
+ int status;
WSABUF local_buffers[MAX_WSABUF_COUNT];
- WSABUF* allocated = NULL;
- WSABUF* buffers = local_buffers;
- size_t len;
-
+ WSABUF* allocated = NULL;
+ WSABUF* buffers = local_buffers;
+ size_t len;
+
if (grpc_tcp_trace.enabled()) {
size_t i;
for (i = 0; i < slices->count; i++) {
@@ -367,168 +367,168 @@ static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices,
}
}
- if (tcp->shutting_down) {
+ 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));
- return;
- }
-
- tcp->write_cb = cb;
- tcp->write_slices = slices;
- GPR_ASSERT(tcp->write_slices->count <= UINT_MAX);
- if (tcp->write_slices->count > GPR_ARRAY_SIZE(local_buffers)) {
- buffers = (WSABUF*)gpr_malloc(sizeof(WSABUF) * tcp->write_slices->count);
- allocated = buffers;
- }
-
- for (i = 0; i < tcp->write_slices->count; i++) {
- len = GRPC_SLICE_LENGTH(tcp->write_slices->slices[i]);
- GPR_ASSERT(len <= ULONG_MAX);
- buffers[i].len = (ULONG)len;
- buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->write_slices->slices[i]);
- }
-
- /* First, let's try a synchronous, non-blocking write. */
- status = WSASend(socket->socket, buffers, (DWORD)tcp->write_slices->count,
- &bytes_sent, 0, NULL, NULL);
- info->wsa_error = status == 0 ? 0 : WSAGetLastError();
-
- /* We would kind of expect to get a WSAEWOULDBLOCK here, especially on a busy
- connection that has its send queue filled up. But if we don't, then we can
- avoid doing an async write operation at all. */
- if (info->wsa_error != WSAEWOULDBLOCK) {
- grpc_error* error = status == 0
- ? GRPC_ERROR_NONE
- : GRPC_WSA_ERROR(info->wsa_error, "WSASend");
+ return;
+ }
+
+ tcp->write_cb = cb;
+ tcp->write_slices = slices;
+ GPR_ASSERT(tcp->write_slices->count <= UINT_MAX);
+ if (tcp->write_slices->count > GPR_ARRAY_SIZE(local_buffers)) {
+ buffers = (WSABUF*)gpr_malloc(sizeof(WSABUF) * tcp->write_slices->count);
+ allocated = buffers;
+ }
+
+ for (i = 0; i < tcp->write_slices->count; i++) {
+ len = GRPC_SLICE_LENGTH(tcp->write_slices->slices[i]);
+ GPR_ASSERT(len <= ULONG_MAX);
+ buffers[i].len = (ULONG)len;
+ buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->write_slices->slices[i]);
+ }
+
+ /* First, let's try a synchronous, non-blocking write. */
+ status = WSASend(socket->socket, buffers, (DWORD)tcp->write_slices->count,
+ &bytes_sent, 0, NULL, NULL);
+ info->wsa_error = status == 0 ? 0 : WSAGetLastError();
+
+ /* We would kind of expect to get a WSAEWOULDBLOCK here, especially on a busy
+ connection that has its send queue filled up. But if we don't, then we can
+ avoid doing an async write operation at all. */
+ if (info->wsa_error != WSAEWOULDBLOCK) {
+ grpc_error* error = status == 0
+ ? GRPC_ERROR_NONE
+ : GRPC_WSA_ERROR(info->wsa_error, "WSASend");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error);
- if (allocated) gpr_free(allocated);
- return;
- }
-
- TCP_REF(tcp, "write");
-
- /* If we got a WSAEWOULDBLOCK earlier, then we need to re-do the same
- operation, this time asynchronously. */
- memset(&socket->write_info.overlapped, 0, sizeof(OVERLAPPED));
- status = WSASend(socket->socket, buffers, (DWORD)tcp->write_slices->count,
- &bytes_sent, 0, &socket->write_info.overlapped, NULL);
- if (allocated) gpr_free(allocated);
-
- if (status != 0) {
- int wsa_error = WSAGetLastError();
- if (wsa_error != WSA_IO_PENDING) {
- TCP_UNREF(tcp, "write");
+ if (allocated) gpr_free(allocated);
+ return;
+ }
+
+ TCP_REF(tcp, "write");
+
+ /* If we got a WSAEWOULDBLOCK earlier, then we need to re-do the same
+ operation, this time asynchronously. */
+ memset(&socket->write_info.overlapped, 0, sizeof(OVERLAPPED));
+ status = WSASend(socket->socket, buffers, (DWORD)tcp->write_slices->count,
+ &bytes_sent, 0, &socket->write_info.overlapped, NULL);
+ if (allocated) gpr_free(allocated);
+
+ if (status != 0) {
+ 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"));
- return;
- }
- }
-
- /* As all is now setup, we can now ask for the IOCP notification. It may
- trigger the callback immediately however, but no matter. */
- grpc_socket_notify_on_write(socket, &tcp->on_write);
-}
-
-static void win_add_to_pollset(grpc_endpoint* ep, grpc_pollset* ps) {
- grpc_tcp* tcp;
- (void)ps;
- tcp = (grpc_tcp*)ep;
- grpc_iocp_add_socket(tcp->socket);
-}
-
-static void win_add_to_pollset_set(grpc_endpoint* ep, grpc_pollset_set* pss) {
- grpc_tcp* tcp;
- (void)pss;
- tcp = (grpc_tcp*)ep;
- grpc_iocp_add_socket(tcp->socket);
-}
-
-static void win_delete_from_pollset_set(grpc_endpoint* ep,
- grpc_pollset_set* pss) {}
-
-/* Initiates a shutdown of the TCP endpoint. This will queue abort callbacks
- for the potential read and write operations. It is up to the caller to
- guarantee this isn't called in parallel to a read or write request, so
- we're not going to protect against these. However the IO Completion Port
- callback will happen from another thread, so we need to protect against
- concurrent access of the data structure in that regard. */
-static void win_shutdown(grpc_endpoint* ep, grpc_error* why) {
- grpc_tcp* tcp = (grpc_tcp*)ep;
- gpr_mu_lock(&tcp->mu);
- /* At that point, what may happen is that we're already inside the IOCP
- callback. See the comments in on_read and on_write. */
- if (!tcp->shutting_down) {
- tcp->shutting_down = 1;
- tcp->shutdown_error = why;
- } else {
- GRPC_ERROR_UNREF(why);
- }
- grpc_winsocket_shutdown(tcp->socket);
- gpr_mu_unlock(&tcp->mu);
- grpc_resource_user_shutdown(tcp->resource_user);
-}
-
-static void win_destroy(grpc_endpoint* ep) {
- grpc_tcp* tcp = (grpc_tcp*)ep;
+ return;
+ }
+ }
+
+ /* As all is now setup, we can now ask for the IOCP notification. It may
+ trigger the callback immediately however, but no matter. */
+ grpc_socket_notify_on_write(socket, &tcp->on_write);
+}
+
+static void win_add_to_pollset(grpc_endpoint* ep, grpc_pollset* ps) {
+ grpc_tcp* tcp;
+ (void)ps;
+ tcp = (grpc_tcp*)ep;
+ grpc_iocp_add_socket(tcp->socket);
+}
+
+static void win_add_to_pollset_set(grpc_endpoint* ep, grpc_pollset_set* pss) {
+ grpc_tcp* tcp;
+ (void)pss;
+ tcp = (grpc_tcp*)ep;
+ grpc_iocp_add_socket(tcp->socket);
+}
+
+static void win_delete_from_pollset_set(grpc_endpoint* ep,
+ grpc_pollset_set* pss) {}
+
+/* Initiates a shutdown of the TCP endpoint. This will queue abort callbacks
+ for the potential read and write operations. It is up to the caller to
+ guarantee this isn't called in parallel to a read or write request, so
+ we're not going to protect against these. However the IO Completion Port
+ callback will happen from another thread, so we need to protect against
+ concurrent access of the data structure in that regard. */
+static void win_shutdown(grpc_endpoint* ep, grpc_error* why) {
+ grpc_tcp* tcp = (grpc_tcp*)ep;
+ gpr_mu_lock(&tcp->mu);
+ /* At that point, what may happen is that we're already inside the IOCP
+ callback. See the comments in on_read and on_write. */
+ if (!tcp->shutting_down) {
+ tcp->shutting_down = 1;
+ tcp->shutdown_error = why;
+ } else {
+ GRPC_ERROR_UNREF(why);
+ }
+ grpc_winsocket_shutdown(tcp->socket);
+ gpr_mu_unlock(&tcp->mu);
+ grpc_resource_user_shutdown(tcp->resource_user);
+}
+
+static void win_destroy(grpc_endpoint* ep) {
+ grpc_tcp* tcp = (grpc_tcp*)ep;
grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer);
- TCP_UNREF(tcp, "destroy");
-}
-
+ TCP_UNREF(tcp, "destroy");
+}
+
static y_absl::string_view win_get_peer(grpc_endpoint* ep) {
- grpc_tcp* tcp = (grpc_tcp*)ep;
+ grpc_tcp* tcp = (grpc_tcp*)ep;
return tcp->peer_string;
-}
-
+}
+
static y_absl::string_view win_get_local_address(grpc_endpoint* ep) {
grpc_tcp* tcp = (grpc_tcp*)ep;
return tcp->local_address;
}
-static grpc_resource_user* win_get_resource_user(grpc_endpoint* ep) {
- grpc_tcp* tcp = (grpc_tcp*)ep;
- return tcp->resource_user;
-}
-
-static int win_get_fd(grpc_endpoint* ep) { return -1; }
-
+static grpc_resource_user* win_get_resource_user(grpc_endpoint* ep) {
+ grpc_tcp* tcp = (grpc_tcp*)ep;
+ return tcp->resource_user;
+}
+
+static int win_get_fd(grpc_endpoint* ep) { return -1; }
+
static bool win_can_track_err(grpc_endpoint* ep) { return false; }
-static grpc_endpoint_vtable vtable = {win_read,
- win_write,
- win_add_to_pollset,
- win_add_to_pollset_set,
- win_delete_from_pollset_set,
- win_shutdown,
- win_destroy,
- win_get_resource_user,
- win_get_peer,
+static grpc_endpoint_vtable vtable = {win_read,
+ win_write,
+ win_add_to_pollset,
+ win_add_to_pollset_set,
+ win_delete_from_pollset_set,
+ win_shutdown,
+ win_destroy,
+ win_get_resource_user,
+ win_get_peer,
win_get_local_address,
win_get_fd,
win_can_track_err};
-
-grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket,
- grpc_channel_args* channel_args,
- const char* peer_string) {
- grpc_resource_quota* resource_quota = grpc_resource_quota_create(NULL);
- if (channel_args != NULL) {
- for (size_t i = 0; i < channel_args->num_args; i++) {
- if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
- grpc_resource_quota_unref_internal(resource_quota);
- resource_quota = grpc_resource_quota_ref_internal(
- (grpc_resource_quota*)channel_args->args[i].value.pointer.p);
- }
- }
- }
+
+grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket,
+ grpc_channel_args* channel_args,
+ const char* peer_string) {
+ grpc_resource_quota* resource_quota = grpc_resource_quota_create(NULL);
+ if (channel_args != NULL) {
+ for (size_t i = 0; i < channel_args->num_args; i++) {
+ if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) {
+ grpc_resource_quota_unref_internal(resource_quota);
+ resource_quota = grpc_resource_quota_ref_internal(
+ (grpc_resource_quota*)channel_args->args[i].value.pointer.p);
+ }
+ }
+ }
grpc_tcp* tcp = new grpc_tcp;
- memset(tcp, 0, sizeof(grpc_tcp));
- tcp->base.vtable = &vtable;
- tcp->socket = socket;
- gpr_mu_init(&tcp->mu);
- gpr_ref_init(&tcp->refcount, 1);
- GRPC_CLOSURE_INIT(&tcp->on_read, on_read, tcp, grpc_schedule_on_exec_ctx);
- GRPC_CLOSURE_INIT(&tcp->on_write, on_write, tcp, grpc_schedule_on_exec_ctx);
+ memset(tcp, 0, sizeof(grpc_tcp));
+ tcp->base.vtable = &vtable;
+ tcp->socket = socket;
+ gpr_mu_init(&tcp->mu);
+ gpr_ref_init(&tcp->refcount, 1);
+ GRPC_CLOSURE_INIT(&tcp->on_read, on_read, tcp, grpc_schedule_on_exec_ctx);
+ GRPC_CLOSURE_INIT(&tcp->on_write, on_write, tcp, grpc_schedule_on_exec_ctx);
grpc_resolved_address resolved_local_addr;
resolved_local_addr.len = sizeof(resolved_local_addr.addr);
if (getsockname(tcp->socket->socket,
@@ -540,10 +540,10 @@ grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket,
}
tcp->peer_string = peer_string;
grpc_slice_buffer_init(&tcp->last_read_buffer);
- tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
- grpc_resource_quota_unref_internal(resource_quota);
-
- return &tcp->base;
-}
-
-#endif /* GRPC_WINSOCK_SOCKET */
+ tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
+ grpc_resource_quota_unref_internal(resource_quota);
+
+ return &tcp->base;
+}
+
+#endif /* GRPC_WINSOCK_SOCKET */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h
index 04ef8102b65..0d686df5d23 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -29,25 +29,25 @@
otherwise specified.
*/
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_WINSOCK_SOCKET
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_WINSOCK_SOCKET
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/socket_windows.h"
/* Create a tcp endpoint given a winsock handle.
* Takes ownership of the handle.
*/
-grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket,
- grpc_channel_args* channel_args,
- const char* peer_string);
+grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket,
+ grpc_channel_args* channel_args,
+ const char* peer_string);
-grpc_error* grpc_tcp_prepare_socket(SOCKET sock);
+grpc_error* grpc_tcp_prepare_socket(SOCKET sock);
grpc_error* grpc_tcp_set_non_block(SOCKET sock);
-#endif
-
+#endif
+
#endif /* GRPC_CORE_LIB_IOMGR_TCP_WINDOWS_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.cc b/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.cc
index 6369e48db0e..4d3e78d107a 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.cc
@@ -1,64 +1,64 @@
-/*
- *
- * 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/iomgr/time_averaged_stats.h"
-
-void grpc_time_averaged_stats_init(grpc_time_averaged_stats* stats,
- double init_avg, double regress_weight,
- double persistence_factor) {
- stats->init_avg = init_avg;
- stats->regress_weight = regress_weight;
- stats->persistence_factor = persistence_factor;
- stats->batch_total_value = 0;
- stats->batch_num_samples = 0;
- stats->aggregate_total_weight = 0;
- stats->aggregate_weighted_avg = init_avg;
-}
-
-void grpc_time_averaged_stats_add_sample(grpc_time_averaged_stats* stats,
- double value) {
- stats->batch_total_value += value;
- ++stats->batch_num_samples;
-}
-
-double grpc_time_averaged_stats_update_average(
- grpc_time_averaged_stats* stats) {
- /* Start with the current batch: */
- double weighted_sum = stats->batch_total_value;
- double total_weight = stats->batch_num_samples;
- if (stats->regress_weight > 0) {
- /* Add in the regression towards init_avg_: */
- weighted_sum += stats->regress_weight * stats->init_avg;
- total_weight += stats->regress_weight;
- }
- if (stats->persistence_factor > 0) {
- /* Add in the persistence: */
- const double prev_sample_weight =
- stats->persistence_factor * stats->aggregate_total_weight;
- weighted_sum += prev_sample_weight * stats->aggregate_weighted_avg;
- total_weight += prev_sample_weight;
- }
- stats->aggregate_weighted_avg =
- (total_weight > 0) ? (weighted_sum / total_weight) : stats->init_avg;
- stats->aggregate_total_weight = total_weight;
- stats->batch_num_samples = 0;
- stats->batch_total_value = 0;
- return stats->aggregate_weighted_avg;
-}
+/*
+ *
+ * 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/iomgr/time_averaged_stats.h"
+
+void grpc_time_averaged_stats_init(grpc_time_averaged_stats* stats,
+ double init_avg, double regress_weight,
+ double persistence_factor) {
+ stats->init_avg = init_avg;
+ stats->regress_weight = regress_weight;
+ stats->persistence_factor = persistence_factor;
+ stats->batch_total_value = 0;
+ stats->batch_num_samples = 0;
+ stats->aggregate_total_weight = 0;
+ stats->aggregate_weighted_avg = init_avg;
+}
+
+void grpc_time_averaged_stats_add_sample(grpc_time_averaged_stats* stats,
+ double value) {
+ stats->batch_total_value += value;
+ ++stats->batch_num_samples;
+}
+
+double grpc_time_averaged_stats_update_average(
+ grpc_time_averaged_stats* stats) {
+ /* Start with the current batch: */
+ double weighted_sum = stats->batch_total_value;
+ double total_weight = stats->batch_num_samples;
+ if (stats->regress_weight > 0) {
+ /* Add in the regression towards init_avg_: */
+ weighted_sum += stats->regress_weight * stats->init_avg;
+ total_weight += stats->regress_weight;
+ }
+ if (stats->persistence_factor > 0) {
+ /* Add in the persistence: */
+ const double prev_sample_weight =
+ stats->persistence_factor * stats->aggregate_total_weight;
+ weighted_sum += prev_sample_weight * stats->aggregate_weighted_avg;
+ total_weight += prev_sample_weight;
+ }
+ stats->aggregate_weighted_avg =
+ (total_weight > 0) ? (weighted_sum / total_weight) : stats->init_avg;
+ stats->aggregate_total_weight = total_weight;
+ stats->batch_num_samples = 0;
+ stats->batch_total_value = 0;
+ return stats->aggregate_weighted_avg;
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.h b/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.h
index 877d1bec0e3..d51ef7eb39d 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/time_averaged_stats.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/core/lib/iomgr/timer.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer.cc
index e647cdefa04..166881ca7bd 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer.cc
@@ -1,45 +1,45 @@
-/*
- *
- * 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/lib/iomgr/timer.h"
-#include "src/core/lib/iomgr/timer_manager.h"
-
-grpc_timer_vtable* grpc_timer_impl;
-
-void grpc_set_timer_impl(grpc_timer_vtable* vtable) {
- grpc_timer_impl = vtable;
-}
-
-void grpc_timer_init(grpc_timer* timer, grpc_millis deadline,
- grpc_closure* closure) {
- grpc_timer_impl->init(timer, deadline, closure);
-}
-
-void grpc_timer_cancel(grpc_timer* timer) { grpc_timer_impl->cancel(timer); }
-
-grpc_timer_check_result grpc_timer_check(grpc_millis* next) {
- return grpc_timer_impl->check(next);
-}
-
-void grpc_timer_list_init() { grpc_timer_impl->list_init(); }
-
-void grpc_timer_list_shutdown() { grpc_timer_impl->list_shutdown(); }
-
-void grpc_timer_consume_kick() { grpc_timer_impl->consume_kick(); }
+/*
+ *
+ * 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/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/timer_manager.h"
+
+grpc_timer_vtable* grpc_timer_impl;
+
+void grpc_set_timer_impl(grpc_timer_vtable* vtable) {
+ grpc_timer_impl = vtable;
+}
+
+void grpc_timer_init(grpc_timer* timer, grpc_millis deadline,
+ grpc_closure* closure) {
+ grpc_timer_impl->init(timer, deadline, closure);
+}
+
+void grpc_timer_cancel(grpc_timer* timer) { grpc_timer_impl->cancel(timer); }
+
+grpc_timer_check_result grpc_timer_check(grpc_millis* next) {
+ return grpc_timer_impl->check(next);
+}
+
+void grpc_timer_list_init() { grpc_timer_impl->list_init(); }
+
+void grpc_timer_list_shutdown() { grpc_timer_impl->list_shutdown(); }
+
+void grpc_timer_consume_kick() { grpc_timer_impl->consume_kick(); }
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer.h b/contrib/libs/grpc/src/core/lib/iomgr/timer.h
index 11da1496523..27d45206ab2 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer.h
@@ -1,65 +1,65 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TIMER_H
#define GRPC_CORE_LIB_IOMGR_TIMER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/port.h"
#include <grpc/support/time.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/iomgr.h"
-typedef struct grpc_timer {
+typedef struct grpc_timer {
grpc_millis deadline;
// 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;
- grpc_closure* closure;
-#ifndef NDEBUG
- struct grpc_timer* hash_table_next;
-#endif
-
- // Optional field used by custom timers
- void* custom_timer;
-} grpc_timer;
-
-typedef enum {
- GRPC_TIMERS_NOT_CHECKED,
- GRPC_TIMERS_CHECKED_AND_EMPTY,
- GRPC_TIMERS_FIRED,
-} grpc_timer_check_result;
-
-typedef struct grpc_timer_vtable {
- void (*init)(grpc_timer* timer, grpc_millis, grpc_closure* closure);
- void (*cancel)(grpc_timer* timer);
-
- /* Internal API */
- grpc_timer_check_result (*check)(grpc_millis* next);
- void (*list_init)();
- void (*list_shutdown)(void);
- void (*consume_kick)(void);
-} grpc_timer_vtable;
-
+ bool pending;
+ struct grpc_timer* next;
+ struct grpc_timer* prev;
+ grpc_closure* closure;
+#ifndef NDEBUG
+ struct grpc_timer* hash_table_next;
+#endif
+
+ // Optional field used by custom timers
+ void* custom_timer;
+} grpc_timer;
+
+typedef enum {
+ GRPC_TIMERS_NOT_CHECKED,
+ GRPC_TIMERS_CHECKED_AND_EMPTY,
+ GRPC_TIMERS_FIRED,
+} grpc_timer_check_result;
+
+typedef struct grpc_timer_vtable {
+ void (*init)(grpc_timer* timer, grpc_millis, grpc_closure* closure);
+ void (*cancel)(grpc_timer* timer);
+
+ /* Internal API */
+ grpc_timer_check_result (*check)(grpc_millis* next);
+ void (*list_init)();
+ void (*list_shutdown)(void);
+ void (*consume_kick)(void);
+} grpc_timer_vtable;
+
/* Initialize *timer. When expired or canceled, closure will be called with
error set to indicate if it expired (GRPC_ERROR_NONE) or was canceled
(GRPC_ERROR_CANCELLED). *closure is guaranteed to be called exactly once, and
@@ -67,13 +67,13 @@ typedef struct grpc_timer_vtable {
application callback is also responsible for maintaining information about
when to free up any user-level state. Behavior is undefined for a deadline of
GRPC_MILLIS_INF_FUTURE. */
-void grpc_timer_init(grpc_timer* timer, grpc_millis deadline,
- grpc_closure* closure);
-
-/* Initialize *timer without setting it. This can later be passed through
- the regular init or cancel */
-void grpc_timer_init_unset(grpc_timer* timer);
+void grpc_timer_init(grpc_timer* timer, grpc_millis deadline,
+ grpc_closure* closure);
+/* Initialize *timer without setting it. This can later be passed through
+ the regular init or cancel */
+void grpc_timer_init_unset(grpc_timer* timer);
+
/* Note that there is no timer destroy function. This is because the
timer is a one-time occurrence with a guarantee that the callback will
be called exactly once, either at expiration or cancellation. Thus, all
@@ -100,7 +100,7 @@ void grpc_timer_init_unset(grpc_timer* timer);
matches this aim.
Requires: cancel() must happen after init() on a given timer */
-void grpc_timer_cancel(grpc_timer* timer);
+void grpc_timer_cancel(grpc_timer* timer);
/* iomgr internal api for dealing with timers */
@@ -111,17 +111,17 @@ void grpc_timer_cancel(grpc_timer* timer);
*next is never guaranteed to be updated on any given execution; however,
with high probability at least one thread in the system will see an update
at any time slice. */
-grpc_timer_check_result grpc_timer_check(grpc_millis* next);
-void grpc_timer_list_init();
-void grpc_timer_list_shutdown();
-
-/* Consume a kick issued by grpc_kick_poller */
-void grpc_timer_consume_kick(void);
+grpc_timer_check_result grpc_timer_check(grpc_millis* next);
+void grpc_timer_list_init();
+void grpc_timer_list_shutdown();
+/* Consume a kick issued by grpc_kick_poller */
+void grpc_timer_consume_kick(void);
+
/* the following must be implemented by each iomgr implementation */
void grpc_kick_poller(void);
-/* Sets the timer implementation */
-void grpc_set_timer_impl(grpc_timer_vtable* vtable);
-
+/* Sets the timer implementation */
+void grpc_set_timer_impl(grpc_timer_vtable* vtable);
+
#endif /* GRPC_CORE_LIB_IOMGR_TIMER_H */
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 c550d441229..c56feb9d55b 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/iomgr/timer_custom.h"
-
-static grpc_custom_timer_vtable* custom_timer_impl;
-
+/*
+ *
+ * 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/iomgr/port.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/timer_custom.h"
+
+static grpc_custom_timer_vtable* custom_timer_impl;
+
void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* /*error*/) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
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 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);
- custom_timer_impl->stop(t);
- gpr_free(t);
-}
-
-static void timer_init(grpc_timer* timer, grpc_millis deadline,
- grpc_closure* closure) {
- uint64_t timeout;
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
- if (deadline <= grpc_core::ExecCtx::Get()->Now()) {
+ custom_timer_impl->stop(t);
+ gpr_free(t);
+}
+
+static void timer_init(grpc_timer* timer, grpc_millis deadline,
+ grpc_closure* closure) {
+ uint64_t timeout;
+ 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);
- timer->pending = false;
- return;
- } else {
- timeout = deadline - now;
- }
- timer->pending = true;
- timer->closure = closure;
- grpc_custom_timer* timer_wrapper =
- (grpc_custom_timer*)gpr_malloc(sizeof(grpc_custom_timer));
- timer_wrapper->timeout_ms = timeout;
- timer->custom_timer = (void*)timer_wrapper;
- timer_wrapper->original = timer;
- custom_timer_impl->start(timer_wrapper);
-}
-
-static void timer_cancel(grpc_timer* timer) {
- GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
- grpc_custom_timer* tw = (grpc_custom_timer*)timer->custom_timer;
- if (timer->pending) {
- timer->pending = 0;
+ timer->pending = false;
+ return;
+ } else {
+ timeout = deadline - now;
+ }
+ timer->pending = true;
+ timer->closure = closure;
+ grpc_custom_timer* timer_wrapper =
+ (grpc_custom_timer*)gpr_malloc(sizeof(grpc_custom_timer));
+ timer_wrapper->timeout_ms = timeout;
+ timer->custom_timer = (void*)timer_wrapper;
+ timer_wrapper->original = timer;
+ custom_timer_impl->start(timer_wrapper);
+}
+
+static void timer_cancel(grpc_timer* timer) {
+ GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
+ 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);
- custom_timer_impl->stop(tw);
- gpr_free(tw);
- }
-}
-
+ custom_timer_impl->stop(tw);
+ gpr_free(tw);
+ }
+}
+
static grpc_timer_check_result timer_check(grpc_millis* /*next*/) {
- return GRPC_TIMERS_NOT_CHECKED;
-}
-
-static void timer_list_init() {}
-static void timer_list_shutdown() {}
-
-static void timer_consume_kick(void) {}
-
-static grpc_timer_vtable custom_timer_vtable = {
- timer_init, timer_cancel, timer_check,
- timer_list_init, timer_list_shutdown, timer_consume_kick};
-
-void grpc_custom_timer_init(grpc_custom_timer_vtable* impl) {
- custom_timer_impl = impl;
- grpc_set_timer_impl(&custom_timer_vtable);
-}
+ return GRPC_TIMERS_NOT_CHECKED;
+}
+
+static void timer_list_init() {}
+static void timer_list_shutdown() {}
+
+static void timer_consume_kick(void) {}
+
+static grpc_timer_vtable custom_timer_vtable = {
+ timer_init, timer_cancel, timer_check,
+ timer_list_init, timer_list_shutdown, timer_consume_kick};
+
+void grpc_custom_timer_init(grpc_custom_timer_vtable* impl) {
+ custom_timer_impl = impl;
+ grpc_set_timer_impl(&custom_timer_vtable);
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.h b/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.h
index bfea8bafa69..81cc039b333 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_custom.h
@@ -1,43 +1,43 @@
-/*
- *
- * 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_TIMER_CUSTOM_H
-#define GRPC_CORE_LIB_IOMGR_TIMER_CUSTOM_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/timer.h"
-
-typedef struct grpc_custom_timer {
- // Implementation defined
- void* timer;
- uint64_t timeout_ms;
-
- grpc_timer* original;
-} grpc_custom_timer;
-
-typedef struct grpc_custom_timer_vtable {
- void (*start)(grpc_custom_timer* t);
- void (*stop)(grpc_custom_timer* t);
-} grpc_custom_timer_vtable;
-
-void grpc_custom_timer_init(grpc_custom_timer_vtable* impl);
-
-void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* error);
-
-#endif /* GRPC_CORE_LIB_IOMGR_TIMER_CUSTOM_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_LIB_IOMGR_TIMER_CUSTOM_H
+#define GRPC_CORE_LIB_IOMGR_TIMER_CUSTOM_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/timer.h"
+
+typedef struct grpc_custom_timer {
+ // Implementation defined
+ void* timer;
+ uint64_t timeout_ms;
+
+ grpc_timer* original;
+} grpc_custom_timer;
+
+typedef struct grpc_custom_timer_vtable {
+ void (*start)(grpc_custom_timer* t);
+ void (*stop)(grpc_custom_timer* t);
+} grpc_custom_timer_vtable;
+
+void grpc_custom_timer_init(grpc_custom_timer_vtable* impl);
+
+void grpc_custom_timer_callback(grpc_custom_timer* t, grpc_error* error);
+
+#endif /* GRPC_CORE_LIB_IOMGR_TIMER_CUSTOM_H */
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 fb0e50c53c9..9bf715ce8c2 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc
@@ -1,217 +1,217 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#include <inttypes.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/iomgr/port.h"
+
+#include <inttypes.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include "src/core/lib/iomgr/timer.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/cpu.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gpr/spinlock.h"
-#include "src/core/lib/gpr/tls.h"
-#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/timer.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/cpu.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gpr/spinlock.h"
+#include "src/core/lib/gpr/tls.h"
+#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/time_averaged_stats.h"
-#include "src/core/lib/iomgr/timer_heap.h"
-
-#define INVALID_HEAP_INDEX 0xffffffffu
-
-#define ADD_DEADLINE_SCALE 0.33
-#define MIN_QUEUE_WINDOW_DURATION 0.01
-#define MAX_QUEUE_WINDOW_DURATION 1
-
-grpc_core::TraceFlag grpc_timer_trace(false, "timer");
-grpc_core::TraceFlag grpc_timer_check_trace(false, "timer_check");
-
-/* A "timer shard". Contains a 'heap' and a 'list' of timers. All timers with
+#include "src/core/lib/iomgr/time_averaged_stats.h"
+#include "src/core/lib/iomgr/timer_heap.h"
+
+#define INVALID_HEAP_INDEX 0xffffffffu
+
+#define ADD_DEADLINE_SCALE 0.33
+#define MIN_QUEUE_WINDOW_DURATION 0.01
+#define MAX_QUEUE_WINDOW_DURATION 1
+
+grpc_core::TraceFlag grpc_timer_trace(false, "timer");
+grpc_core::TraceFlag grpc_timer_check_trace(false, "timer_check");
+
+/* A "timer shard". Contains a 'heap' and a 'list' of timers. All timers with
* deadlines earlier than 'queue_deadline_cap' are maintained in the heap and
- * others are maintained in the list (unordered). This helps to keep the number
- * of elements in the heap low.
- *
- * The 'queue_deadline_cap' gets recomputed periodically based on the timer
- * stats maintained in 'stats' and the relevant timers are then moved from the
+ * others are maintained in the list (unordered). This helps to keep the number
+ * of elements in the heap low.
+ *
+ * The 'queue_deadline_cap' gets recomputed periodically based on the timer
+ * stats maintained in 'stats' and the relevant timers are then moved from the
* 'list' to 'heap'.
- */
+ */
struct timer_shard {
- gpr_mu mu;
- grpc_time_averaged_stats stats;
+ gpr_mu mu;
+ grpc_time_averaged_stats stats;
/* All and only timers with deadlines < this will be in the heap. */
grpc_millis queue_deadline_cap;
/* The deadline of the next timer due in this shard. */
grpc_millis min_deadline;
/* Index of this timer_shard in the g_shard_queue. */
- uint32_t shard_queue_index;
- /* This holds all timers with deadlines < queue_deadline_cap. Timers in this
- list have the top bit of their deadline set to 0. */
- grpc_timer_heap heap;
- /* This holds timers whose deadline is >= queue_deadline_cap. */
- grpc_timer list;
+ uint32_t shard_queue_index;
+ /* This holds all timers with deadlines < queue_deadline_cap. Timers in this
+ list have the top bit of their deadline set to 0. */
+ grpc_timer_heap heap;
+ /* This holds timers whose deadline is >= queue_deadline_cap. */
+ grpc_timer list;
};
-static size_t g_num_shards;
-
-/* Array of timer shards. Whenever a timer (grpc_timer *) is added, its address
- * is hashed to select the timer shard to add the timer to */
-static timer_shard* g_shards;
-
-/* Maintains a sorted list of timer shards (sorted by their min_deadline, i.e
- * the deadline of the next timer in each shard).
- * Access to this is protected by g_shared_mutables.mu */
-static timer_shard** g_shard_queue;
-
-#ifndef NDEBUG
-
+static size_t g_num_shards;
+
+/* Array of timer shards. Whenever a timer (grpc_timer *) is added, its address
+ * is hashed to select the timer shard to add the timer to */
+static timer_shard* g_shards;
+
+/* Maintains a sorted list of timer shards (sorted by their min_deadline, i.e
+ * the deadline of the next timer in each shard).
+ * Access to this is protected by g_shared_mutables.mu */
+static timer_shard** g_shard_queue;
+
+#ifndef NDEBUG
+
/* == DEBUG ONLY: hash table for duplicate timer detection == */
-
-#define NUM_HASH_BUCKETS 1009 /* Prime number close to 1000 */
-
-static gpr_mu g_hash_mu[NUM_HASH_BUCKETS]; /* One mutex per bucket */
-static grpc_timer* g_timer_ht[NUM_HASH_BUCKETS] = {nullptr};
-
-static void init_timer_ht() {
- for (int i = 0; i < NUM_HASH_BUCKETS; i++) {
- gpr_mu_init(&g_hash_mu[i]);
- }
-}
-
-static void destroy_timer_ht() {
- for (int i = 0; i < NUM_HASH_BUCKETS; i++) {
- gpr_mu_destroy(&g_hash_mu[i]);
- }
-}
-
-static bool is_in_ht(grpc_timer* t) {
- size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS);
-
- gpr_mu_lock(&g_hash_mu[i]);
- grpc_timer* p = g_timer_ht[i];
- while (p != nullptr && p != t) {
- p = p->hash_table_next;
- }
- gpr_mu_unlock(&g_hash_mu[i]);
-
- return (p == t);
-}
-
-static void add_to_ht(grpc_timer* t) {
- GPR_ASSERT(!t->hash_table_next);
- size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS);
-
- gpr_mu_lock(&g_hash_mu[i]);
- grpc_timer* p = g_timer_ht[i];
- while (p != nullptr && p != t) {
- p = p->hash_table_next;
- }
-
- if (p == t) {
- grpc_closure* c = t->closure;
- gpr_log(GPR_ERROR,
- "** Duplicate timer (%p) being added. Closure: (%p), created at: "
- "(%s:%d), scheduled at: (%s:%d) **",
- t, c, c->file_created, c->line_created, c->file_initiated,
- c->line_initiated);
- abort();
- }
-
- /* Timer not present in the bucket. Insert at head of the list */
- t->hash_table_next = g_timer_ht[i];
- g_timer_ht[i] = t;
- gpr_mu_unlock(&g_hash_mu[i]);
-}
-
-static void remove_from_ht(grpc_timer* t) {
- size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS);
- bool removed = false;
-
- gpr_mu_lock(&g_hash_mu[i]);
- if (g_timer_ht[i] == t) {
- g_timer_ht[i] = g_timer_ht[i]->hash_table_next;
- removed = true;
- } else if (g_timer_ht[i] != nullptr) {
- grpc_timer* p = g_timer_ht[i];
- while (p->hash_table_next != nullptr && p->hash_table_next != t) {
- p = p->hash_table_next;
- }
-
- if (p->hash_table_next == t) {
- p->hash_table_next = t->hash_table_next;
- removed = true;
- }
- }
- gpr_mu_unlock(&g_hash_mu[i]);
-
- if (!removed) {
- grpc_closure* c = t->closure;
- gpr_log(GPR_ERROR,
- "** Removing timer (%p) that is not added to hash table. Closure "
- "(%p), created at: (%s:%d), scheduled at: (%s:%d) **",
- t, c, c->file_created, c->line_created, c->file_initiated,
- c->line_initiated);
- abort();
- }
-
- t->hash_table_next = nullptr;
-}
-
+
+#define NUM_HASH_BUCKETS 1009 /* Prime number close to 1000 */
+
+static gpr_mu g_hash_mu[NUM_HASH_BUCKETS]; /* One mutex per bucket */
+static grpc_timer* g_timer_ht[NUM_HASH_BUCKETS] = {nullptr};
+
+static void init_timer_ht() {
+ for (int i = 0; i < NUM_HASH_BUCKETS; i++) {
+ gpr_mu_init(&g_hash_mu[i]);
+ }
+}
+
+static void destroy_timer_ht() {
+ for (int i = 0; i < NUM_HASH_BUCKETS; i++) {
+ gpr_mu_destroy(&g_hash_mu[i]);
+ }
+}
+
+static bool is_in_ht(grpc_timer* t) {
+ size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS);
+
+ gpr_mu_lock(&g_hash_mu[i]);
+ grpc_timer* p = g_timer_ht[i];
+ while (p != nullptr && p != t) {
+ p = p->hash_table_next;
+ }
+ gpr_mu_unlock(&g_hash_mu[i]);
+
+ return (p == t);
+}
+
+static void add_to_ht(grpc_timer* t) {
+ GPR_ASSERT(!t->hash_table_next);
+ size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS);
+
+ gpr_mu_lock(&g_hash_mu[i]);
+ grpc_timer* p = g_timer_ht[i];
+ while (p != nullptr && p != t) {
+ p = p->hash_table_next;
+ }
+
+ if (p == t) {
+ grpc_closure* c = t->closure;
+ gpr_log(GPR_ERROR,
+ "** Duplicate timer (%p) being added. Closure: (%p), created at: "
+ "(%s:%d), scheduled at: (%s:%d) **",
+ t, c, c->file_created, c->line_created, c->file_initiated,
+ c->line_initiated);
+ abort();
+ }
+
+ /* Timer not present in the bucket. Insert at head of the list */
+ t->hash_table_next = g_timer_ht[i];
+ g_timer_ht[i] = t;
+ gpr_mu_unlock(&g_hash_mu[i]);
+}
+
+static void remove_from_ht(grpc_timer* t) {
+ size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS);
+ bool removed = false;
+
+ gpr_mu_lock(&g_hash_mu[i]);
+ if (g_timer_ht[i] == t) {
+ g_timer_ht[i] = g_timer_ht[i]->hash_table_next;
+ removed = true;
+ } else if (g_timer_ht[i] != nullptr) {
+ grpc_timer* p = g_timer_ht[i];
+ while (p->hash_table_next != nullptr && p->hash_table_next != t) {
+ p = p->hash_table_next;
+ }
+
+ if (p->hash_table_next == t) {
+ p->hash_table_next = t->hash_table_next;
+ removed = true;
+ }
+ }
+ gpr_mu_unlock(&g_hash_mu[i]);
+
+ if (!removed) {
+ grpc_closure* c = t->closure;
+ gpr_log(GPR_ERROR,
+ "** Removing timer (%p) that is not added to hash table. Closure "
+ "(%p), created at: (%s:%d), scheduled at: (%s:%d) **",
+ t, c, c->file_created, c->line_created, c->file_initiated,
+ c->line_initiated);
+ abort();
+ }
+
+ t->hash_table_next = nullptr;
+}
+
/* If a timer is added to a timer shard (either heap or a list), it must
- * be pending. A timer is added to hash table only-if it is added to the
- * timer shard.
- * Therefore, if timer->pending is false, it cannot be in hash table */
-static void validate_non_pending_timer(grpc_timer* t) {
- if (!t->pending && is_in_ht(t)) {
- grpc_closure* c = t->closure;
- gpr_log(GPR_ERROR,
- "** gpr_timer_cancel() called on a non-pending timer (%p) which "
- "is in the hash table. Closure: (%p), created at: (%s:%d), "
- "scheduled at: (%s:%d) **",
- t, c, c->file_created, c->line_created, c->file_initiated,
- c->line_initiated);
- abort();
- }
-}
-
-#define INIT_TIMER_HASH_TABLE() init_timer_ht()
-#define DESTROY_TIMER_HASH_TABLE() destroy_timer_ht()
-#define ADD_TO_HASH_TABLE(t) add_to_ht((t))
-#define REMOVE_FROM_HASH_TABLE(t) remove_from_ht((t))
-#define VALIDATE_NON_PENDING_TIMER(t) validate_non_pending_timer((t))
-
-#else
-
-#define INIT_TIMER_HASH_TABLE()
-#define DESTROY_TIMER_HASH_TABLE()
-#define ADD_TO_HASH_TABLE(t)
-#define REMOVE_FROM_HASH_TABLE(t)
-#define VALIDATE_NON_PENDING_TIMER(t)
-
-#endif
-
+ * be pending. A timer is added to hash table only-if it is added to the
+ * timer shard.
+ * Therefore, if timer->pending is false, it cannot be in hash table */
+static void validate_non_pending_timer(grpc_timer* t) {
+ if (!t->pending && is_in_ht(t)) {
+ grpc_closure* c = t->closure;
+ gpr_log(GPR_ERROR,
+ "** gpr_timer_cancel() called on a non-pending timer (%p) which "
+ "is in the hash table. Closure: (%p), created at: (%s:%d), "
+ "scheduled at: (%s:%d) **",
+ t, c, c->file_created, c->line_created, c->file_initiated,
+ c->line_initiated);
+ abort();
+ }
+}
+
+#define INIT_TIMER_HASH_TABLE() init_timer_ht()
+#define DESTROY_TIMER_HASH_TABLE() destroy_timer_ht()
+#define ADD_TO_HASH_TABLE(t) add_to_ht((t))
+#define REMOVE_FROM_HASH_TABLE(t) remove_from_ht((t))
+#define VALIDATE_NON_PENDING_TIMER(t) validate_non_pending_timer((t))
+
+#else
+
+#define INIT_TIMER_HASH_TABLE()
+#define DESTROY_TIMER_HASH_TABLE()
+#define ADD_TO_HASH_TABLE(t)
+#define REMOVE_FROM_HASH_TABLE(t)
+#define VALIDATE_NON_PENDING_TIMER(t)
+
+#endif
+
#if GPR_ARCH_64
/* NOTE: TODO(sreek) - Currently the thread local storage support in grpc is
for intptr_t which means on 32-bit machines it is not wide enough to hold
@@ -219,218 +219,218 @@ static void validate_non_pending_timer(grpc_timer* t) {
is a lot of work for very little gain. So we are currently restricting this
optimization to only 64 bit machines */
-/* Thread local variable that stores the deadline of the next timer the thread
- * has last-seen. This is an optimization to prevent the thread from checking
- * shared_mutables.min_timer (which requires acquiring shared_mutables.mu lock,
- * an expensive operation) */
-GPR_TLS_DECL(g_last_seen_min_timer);
+/* Thread local variable that stores the deadline of the next timer the thread
+ * has last-seen. This is an optimization to prevent the thread from checking
+ * shared_mutables.min_timer (which requires acquiring shared_mutables.mu lock,
+ * an expensive operation) */
+GPR_TLS_DECL(g_last_seen_min_timer);
#endif
-
-struct shared_mutables {
- /* The deadline of the next timer due across all timer shards */
+
+struct shared_mutables {
+ /* The deadline of the next timer due across all timer shards */
grpc_millis min_timer;
- /* Allow only one run_some_expired_timers at once */
- gpr_spinlock checker_mu;
- bool initialized;
- /* Protects g_shard_queue (and the shared_mutables struct itself) */
- gpr_mu mu;
-} GPR_ALIGN_STRUCT(GPR_CACHELINE_SIZE);
-
-static struct shared_mutables g_shared_mutables;
-
+ /* Allow only one run_some_expired_timers at once */
+ gpr_spinlock checker_mu;
+ bool initialized;
+ /* Protects g_shard_queue (and the shared_mutables struct itself) */
+ gpr_mu mu;
+} GPR_ALIGN_STRUCT(GPR_CACHELINE_SIZE);
+
+static struct shared_mutables g_shared_mutables;
+
static grpc_millis saturating_add(grpc_millis a, grpc_millis b) {
if (a > GRPC_MILLIS_INF_FUTURE - b) {
return GRPC_MILLIS_INF_FUTURE;
- }
- return a + b;
-}
-
+ }
+ return a + b;
+}
+
static grpc_timer_check_result run_some_expired_timers(grpc_millis now,
grpc_millis* next,
- grpc_error* error);
-
+ grpc_error* error);
+
static grpc_millis compute_min_deadline(timer_shard* shard) {
- return grpc_timer_heap_is_empty(&shard->heap)
- ? saturating_add(shard->queue_deadline_cap, 1)
- : grpc_timer_heap_top(&shard->heap)->deadline;
-}
-
-static void timer_list_init() {
- uint32_t i;
-
+ return grpc_timer_heap_is_empty(&shard->heap)
+ ? saturating_add(shard->queue_deadline_cap, 1)
+ : grpc_timer_heap_top(&shard->heap)->deadline;
+}
+
+static void timer_list_init() {
+ uint32_t i;
+
g_num_shards = GPR_CLAMP(2 * gpr_cpu_num_cores(), 1, 32);
- g_shards =
- static_cast<timer_shard*>(gpr_zalloc(g_num_shards * sizeof(*g_shards)));
- g_shard_queue = static_cast<timer_shard**>(
- gpr_zalloc(g_num_shards * sizeof(*g_shard_queue)));
-
- g_shared_mutables.initialized = true;
- g_shared_mutables.checker_mu = GPR_SPINLOCK_INITIALIZER;
- gpr_mu_init(&g_shared_mutables.mu);
- g_shared_mutables.min_timer = grpc_core::ExecCtx::Get()->Now();
+ g_shards =
+ static_cast<timer_shard*>(gpr_zalloc(g_num_shards * sizeof(*g_shards)));
+ g_shard_queue = static_cast<timer_shard**>(
+ gpr_zalloc(g_num_shards * sizeof(*g_shard_queue)));
+
+ g_shared_mutables.initialized = true;
+ g_shared_mutables.checker_mu = GPR_SPINLOCK_INITIALIZER;
+ gpr_mu_init(&g_shared_mutables.mu);
+ g_shared_mutables.min_timer = grpc_core::ExecCtx::Get()->Now();
#if GPR_ARCH_64
- gpr_tls_init(&g_last_seen_min_timer);
- gpr_tls_set(&g_last_seen_min_timer, 0);
+ gpr_tls_init(&g_last_seen_min_timer);
+ gpr_tls_set(&g_last_seen_min_timer, 0);
#endif
-
- for (i = 0; i < g_num_shards; i++) {
- timer_shard* shard = &g_shards[i];
- gpr_mu_init(&shard->mu);
- grpc_time_averaged_stats_init(&shard->stats, 1.0 / ADD_DEADLINE_SCALE, 0.1,
- 0.5);
- shard->queue_deadline_cap = g_shared_mutables.min_timer;
- shard->shard_queue_index = i;
- grpc_timer_heap_init(&shard->heap);
- shard->list.next = shard->list.prev = &shard->list;
- shard->min_deadline = compute_min_deadline(shard);
- g_shard_queue[i] = shard;
- }
-
- INIT_TIMER_HASH_TABLE();
-}
-
-static void timer_list_shutdown() {
- size_t i;
- run_some_expired_timers(
+
+ for (i = 0; i < g_num_shards; i++) {
+ timer_shard* shard = &g_shards[i];
+ gpr_mu_init(&shard->mu);
+ grpc_time_averaged_stats_init(&shard->stats, 1.0 / ADD_DEADLINE_SCALE, 0.1,
+ 0.5);
+ shard->queue_deadline_cap = g_shared_mutables.min_timer;
+ shard->shard_queue_index = i;
+ grpc_timer_heap_init(&shard->heap);
+ shard->list.next = shard->list.prev = &shard->list;
+ shard->min_deadline = compute_min_deadline(shard);
+ g_shard_queue[i] = shard;
+ }
+
+ INIT_TIMER_HASH_TABLE();
+}
+
+static void timer_list_shutdown() {
+ size_t i;
+ run_some_expired_timers(
GRPC_MILLIS_INF_FUTURE, nullptr,
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Timer list shutdown"));
- for (i = 0; i < g_num_shards; i++) {
- timer_shard* shard = &g_shards[i];
- gpr_mu_destroy(&shard->mu);
- grpc_timer_heap_destroy(&shard->heap);
- }
- gpr_mu_destroy(&g_shared_mutables.mu);
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Timer list shutdown"));
+ for (i = 0; i < g_num_shards; i++) {
+ timer_shard* shard = &g_shards[i];
+ gpr_mu_destroy(&shard->mu);
+ grpc_timer_heap_destroy(&shard->heap);
+ }
+ gpr_mu_destroy(&g_shared_mutables.mu);
#if GPR_ARCH_64
- gpr_tls_destroy(&g_last_seen_min_timer);
-#endif
-
- gpr_free(g_shards);
- gpr_free(g_shard_queue);
- g_shared_mutables.initialized = false;
-
- DESTROY_TIMER_HASH_TABLE();
-}
-
-/* returns true if the first element in the list */
-static void list_join(grpc_timer* head, grpc_timer* timer) {
- timer->next = head;
- timer->prev = head->prev;
- timer->next->prev = timer->prev->next = timer;
-}
-
-static void list_remove(grpc_timer* timer) {
- timer->next->prev = timer->prev;
- timer->prev->next = timer->next;
-}
-
-static void swap_adjacent_shards_in_queue(uint32_t first_shard_queue_index) {
- timer_shard* temp;
- temp = g_shard_queue[first_shard_queue_index];
- g_shard_queue[first_shard_queue_index] =
- g_shard_queue[first_shard_queue_index + 1];
- g_shard_queue[first_shard_queue_index + 1] = temp;
- g_shard_queue[first_shard_queue_index]->shard_queue_index =
- first_shard_queue_index;
- g_shard_queue[first_shard_queue_index + 1]->shard_queue_index =
- first_shard_queue_index + 1;
-}
-
-static void note_deadline_change(timer_shard* shard) {
- while (shard->shard_queue_index > 0 &&
- shard->min_deadline <
- g_shard_queue[shard->shard_queue_index - 1]->min_deadline) {
- swap_adjacent_shards_in_queue(shard->shard_queue_index - 1);
- }
- while (shard->shard_queue_index < g_num_shards - 1 &&
- shard->min_deadline >
- g_shard_queue[shard->shard_queue_index + 1]->min_deadline) {
- swap_adjacent_shards_in_queue(shard->shard_queue_index);
- }
-}
-
-void grpc_timer_init_unset(grpc_timer* timer) { timer->pending = false; }
-
-static void timer_init(grpc_timer* timer, grpc_millis deadline,
- grpc_closure* closure) {
- int is_first_timer = 0;
- timer_shard* shard = &g_shards[GPR_HASH_POINTER(timer, g_num_shards)];
- timer->closure = closure;
- timer->deadline = deadline;
-
-#ifndef NDEBUG
- timer->hash_table_next = nullptr;
+ gpr_tls_destroy(&g_last_seen_min_timer);
#endif
+ gpr_free(g_shards);
+ gpr_free(g_shard_queue);
+ g_shared_mutables.initialized = false;
+
+ DESTROY_TIMER_HASH_TABLE();
+}
+
+/* returns true if the first element in the list */
+static void list_join(grpc_timer* head, grpc_timer* timer) {
+ timer->next = head;
+ timer->prev = head->prev;
+ timer->next->prev = timer->prev->next = timer;
+}
+
+static void list_remove(grpc_timer* timer) {
+ timer->next->prev = timer->prev;
+ timer->prev->next = timer->next;
+}
+
+static void swap_adjacent_shards_in_queue(uint32_t first_shard_queue_index) {
+ timer_shard* temp;
+ temp = g_shard_queue[first_shard_queue_index];
+ g_shard_queue[first_shard_queue_index] =
+ g_shard_queue[first_shard_queue_index + 1];
+ g_shard_queue[first_shard_queue_index + 1] = temp;
+ g_shard_queue[first_shard_queue_index]->shard_queue_index =
+ first_shard_queue_index;
+ g_shard_queue[first_shard_queue_index + 1]->shard_queue_index =
+ first_shard_queue_index + 1;
+}
+
+static void note_deadline_change(timer_shard* shard) {
+ while (shard->shard_queue_index > 0 &&
+ shard->min_deadline <
+ g_shard_queue[shard->shard_queue_index - 1]->min_deadline) {
+ swap_adjacent_shards_in_queue(shard->shard_queue_index - 1);
+ }
+ while (shard->shard_queue_index < g_num_shards - 1 &&
+ shard->min_deadline >
+ g_shard_queue[shard->shard_queue_index + 1]->min_deadline) {
+ swap_adjacent_shards_in_queue(shard->shard_queue_index);
+ }
+}
+
+void grpc_timer_init_unset(grpc_timer* timer) { timer->pending = false; }
+
+static void timer_init(grpc_timer* timer, grpc_millis deadline,
+ grpc_closure* closure) {
+ int is_first_timer = 0;
+ timer_shard* shard = &g_shards[GPR_HASH_POINTER(timer, g_num_shards)];
+ timer->closure = closure;
+ timer->deadline = deadline;
+
+#ifndef NDEBUG
+ timer->hash_table_next = nullptr;
+#endif
+
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);
- }
-
- if (!g_shared_mutables.initialized) {
- timer->pending = false;
+ timer, deadline, grpc_core::ExecCtx::Get()->Now(), closure,
+ closure->cb);
+ }
+
+ 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"));
- return;
- }
-
- gpr_mu_lock(&shard->mu);
- timer->pending = true;
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
- if (deadline <= now) {
- timer->pending = false;
+ return;
+ }
+
+ gpr_mu_lock(&shard->mu);
+ timer->pending = true;
+ 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);
- gpr_mu_unlock(&shard->mu);
- /* early out */
- return;
- }
-
- grpc_time_averaged_stats_add_sample(
- &shard->stats, static_cast<double>(deadline - now) / 1000.0);
-
- ADD_TO_HASH_TABLE(timer);
-
- if (deadline < shard->queue_deadline_cap) {
- is_first_timer = grpc_timer_heap_add(&shard->heap, timer);
- } else {
- timer->heap_index = INVALID_HEAP_INDEX;
- list_join(&shard->list, timer);
- }
+ gpr_mu_unlock(&shard->mu);
+ /* early out */
+ return;
+ }
+
+ grpc_time_averaged_stats_add_sample(
+ &shard->stats, static_cast<double>(deadline - now) / 1000.0);
+
+ ADD_TO_HASH_TABLE(timer);
+
+ if (deadline < shard->queue_deadline_cap) {
+ is_first_timer = grpc_timer_heap_add(&shard->heap, timer);
+ } else {
+ timer->heap_index = INVALID_HEAP_INDEX;
+ list_join(&shard->list, timer);
+ }
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
" .. add to shard %d with queue_deadline_cap=%" PRId64
- " => is_first_timer=%s",
- static_cast<int>(shard - g_shards), shard->queue_deadline_cap,
- is_first_timer ? "true" : "false");
- }
- gpr_mu_unlock(&shard->mu);
-
- /* Deadline may have decreased, we need to adjust the master queue. Note
- that there is a potential racy unlocked region here. There could be a
- reordering of multiple grpc_timer_init calls, at this point, but the < test
- below should ensure that we err on the side of caution. There could
- also be a race with grpc_timer_check, which might beat us to the lock. In
- that case, it is possible that the timer that we added will have already
- run by the time we hold the lock, but that too is a safe error.
- Finally, it's possible that the grpc_timer_check that intervened failed to
- trigger the new timer because the min_deadline hadn't yet been reduced.
- In that case, the timer will simply have to wait for the next
- grpc_timer_check. */
- if (is_first_timer) {
- gpr_mu_lock(&g_shared_mutables.mu);
+ " => is_first_timer=%s",
+ static_cast<int>(shard - g_shards), shard->queue_deadline_cap,
+ is_first_timer ? "true" : "false");
+ }
+ gpr_mu_unlock(&shard->mu);
+
+ /* Deadline may have decreased, we need to adjust the master queue. Note
+ that there is a potential racy unlocked region here. There could be a
+ reordering of multiple grpc_timer_init calls, at this point, but the < test
+ below should ensure that we err on the side of caution. There could
+ also be a race with grpc_timer_check, which might beat us to the lock. In
+ that case, it is possible that the timer that we added will have already
+ run by the time we hold the lock, but that too is a safe error.
+ Finally, it's possible that the grpc_timer_check that intervened failed to
+ trigger the new timer because the min_deadline hadn't yet been reduced.
+ In that case, the timer will simply have to wait for the next
+ grpc_timer_check. */
+ if (is_first_timer) {
+ gpr_mu_lock(&g_shared_mutables.mu);
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) {
gpr_log(GPR_INFO, " .. old shard min_deadline=%" PRId64,
- shard->min_deadline);
- }
- if (deadline < shard->min_deadline) {
+ shard->min_deadline);
+ }
+ if (deadline < shard->min_deadline) {
grpc_millis old_min_deadline = g_shard_queue[0]->min_deadline;
- shard->min_deadline = deadline;
- note_deadline_change(shard);
- if (shard->shard_queue_index == 0 && deadline < old_min_deadline) {
+ shard->min_deadline = deadline;
+ note_deadline_change(shard);
+ if (shard->shard_queue_index == 0 && deadline < old_min_deadline) {
#if GPR_ARCH_64
// TODO: sreek - Using c-style cast here. static_cast<> gives an error
// (on mac platforms complaining that gpr_atm* is (long *) while
@@ -444,147 +444,147 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline,
// g_shared_mutables.min_timer varialbe under g_shared_mutables.mu
g_shared_mutables.min_timer = deadline;
#endif
- grpc_kick_poller();
- }
- }
- gpr_mu_unlock(&g_shared_mutables.mu);
- }
-}
-
-static void timer_consume_kick(void) {
+ grpc_kick_poller();
+ }
+ }
+ gpr_mu_unlock(&g_shared_mutables.mu);
+ }
+}
+
+static void timer_consume_kick(void) {
#if GPR_ARCH_64
/* Force re-evaluation of last seen min */
- gpr_tls_set(&g_last_seen_min_timer, 0);
+ gpr_tls_set(&g_last_seen_min_timer, 0);
#endif
-}
-
-static void timer_cancel(grpc_timer* timer) {
- if (!g_shared_mutables.initialized) {
- /* must have already been cancelled, also the shard mutex is invalid */
- return;
- }
-
- timer_shard* shard = &g_shards[GPR_HASH_POINTER(timer, g_num_shards)];
- gpr_mu_lock(&shard->mu);
+}
+
+static void timer_cancel(grpc_timer* timer) {
+ if (!g_shared_mutables.initialized) {
+ /* must have already been cancelled, also the shard mutex is invalid */
+ return;
+ }
+
+ 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)) {
- gpr_log(GPR_INFO, "TIMER %p: CANCEL pending=%s", timer,
- timer->pending ? "true" : "false");
- }
-
- if (timer->pending) {
- REMOVE_FROM_HASH_TABLE(timer);
-
+ gpr_log(GPR_INFO, "TIMER %p: CANCEL pending=%s", timer,
+ timer->pending ? "true" : "false");
+ }
+
+ if (timer->pending) {
+ REMOVE_FROM_HASH_TABLE(timer);
+
grpc_core::ExecCtx::Run(DEBUG_LOCATION, timer->closure,
GRPC_ERROR_CANCELLED);
- timer->pending = false;
- if (timer->heap_index == INVALID_HEAP_INDEX) {
- list_remove(timer);
- } else {
- grpc_timer_heap_remove(&shard->heap, timer);
- }
- } else {
- VALIDATE_NON_PENDING_TIMER(timer);
- }
- gpr_mu_unlock(&shard->mu);
-}
-
-/* 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.
+ timer->pending = false;
+ if (timer->heap_index == INVALID_HEAP_INDEX) {
+ list_remove(timer);
+ } else {
+ grpc_timer_heap_remove(&shard->heap, timer);
+ }
+ } else {
+ VALIDATE_NON_PENDING_TIMER(timer);
+ }
+ gpr_mu_unlock(&shard->mu);
+}
+
+/* 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
- REQUIRES: shard->mu locked */
+ 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: */
- double computed_deadline_delta =
- grpc_time_averaged_stats_update_average(&shard->stats) *
- ADD_DEADLINE_SCALE;
- double deadline_delta =
- GPR_CLAMP(computed_deadline_delta, MIN_QUEUE_WINDOW_DURATION,
- MAX_QUEUE_WINDOW_DURATION);
- grpc_timer *timer, *next;
-
- /* Compute the new cap and put all timers under it into the queue: */
- shard->queue_deadline_cap =
- saturating_add(GPR_MAX(now, shard->queue_deadline_cap),
+ /* Compute the new queue window width and bound by the limits: */
+ double computed_deadline_delta =
+ grpc_time_averaged_stats_update_average(&shard->stats) *
+ ADD_DEADLINE_SCALE;
+ double deadline_delta =
+ GPR_CLAMP(computed_deadline_delta, MIN_QUEUE_WINDOW_DURATION,
+ MAX_QUEUE_WINDOW_DURATION);
+ grpc_timer *timer, *next;
+
+ /* Compute the new cap and put all timers under it into the queue: */
+ shard->queue_deadline_cap =
+ 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)) {
gpr_log(GPR_INFO, " .. shard[%d]->queue_deadline_cap --> %" PRId64,
- static_cast<int>(shard - g_shards), shard->queue_deadline_cap);
- }
- for (timer = shard->list.next; timer != &shard->list; timer = next) {
- next = timer->next;
-
- if (timer->deadline < shard->queue_deadline_cap) {
+ static_cast<int>(shard - g_shards), shard->queue_deadline_cap);
+ }
+ for (timer = shard->list.next; timer != &shard->list; timer = next) {
+ next = timer->next;
+
+ if (timer->deadline < shard->queue_deadline_cap) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, " .. add timer with deadline %" PRId64 " to heap",
- timer->deadline);
- }
- list_remove(timer);
- grpc_timer_heap_add(&shard->heap, timer);
- }
- }
- return !grpc_timer_heap_is_empty(&shard->heap);
-}
-
-/* This pops the next non-cancelled timer with deadline <= now from the
- queue, or returns NULL if there isn't one.
- REQUIRES: shard->mu locked */
+ timer->deadline);
+ }
+ list_remove(timer);
+ grpc_timer_heap_add(&shard->heap, timer);
+ }
+ }
+ return !grpc_timer_heap_is_empty(&shard->heap);
+}
+
+/* This pops the next non-cancelled timer with deadline <= now from the
+ queue, or returns NULL if there isn't one.
+ REQUIRES: shard->mu locked */
static grpc_timer* pop_one(timer_shard* shard, grpc_millis now) {
- grpc_timer* timer;
- for (;;) {
+ grpc_timer* timer;
+ for (;;) {
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");
- }
- if (grpc_timer_heap_is_empty(&shard->heap)) {
- if (now < shard->queue_deadline_cap) return nullptr;
- if (!refill_heap(shard, now)) return nullptr;
- }
- timer = grpc_timer_heap_top(&shard->heap);
+ gpr_log(GPR_INFO, " .. shard[%d]: heap_empty=%s",
+ static_cast<int>(shard - g_shards),
+ grpc_timer_heap_is_empty(&shard->heap) ? "true" : "false");
+ }
+ if (grpc_timer_heap_is_empty(&shard->heap)) {
+ if (now < shard->queue_deadline_cap) return nullptr;
+ if (!refill_heap(shard, now)) return nullptr;
+ }
+ timer = grpc_timer_heap_top(&shard->heap);
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
" .. check top timer deadline=%" PRId64 " now=%" PRId64,
- timer->deadline, now);
- }
- if (timer->deadline > now) return nullptr;
+ 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);
- }
- timer->pending = false;
- grpc_timer_heap_pop(&shard->heap);
- return timer;
- }
-}
-
-/* REQUIRES: shard->mu unlocked */
+ }
+ timer->pending = false;
+ grpc_timer_heap_pop(&shard->heap);
+ return timer;
+ }
+}
+
+/* REQUIRES: shard->mu unlocked */
static size_t pop_timers(timer_shard* shard, grpc_millis now,
grpc_millis* new_min_deadline, grpc_error* error) {
- size_t n = 0;
- grpc_timer* timer;
- gpr_mu_lock(&shard->mu);
- while ((timer = pop_one(shard, now))) {
- REMOVE_FROM_HASH_TABLE(timer);
+ size_t n = 0;
+ grpc_timer* timer;
+ 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));
- n++;
- }
- *new_min_deadline = compute_min_deadline(shard);
- gpr_mu_unlock(&shard->mu);
+ n++;
+ }
+ *new_min_deadline = compute_min_deadline(shard);
+ gpr_mu_unlock(&shard->mu);
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- gpr_log(GPR_INFO, " .. shard[%d] popped %" PRIdPTR,
- static_cast<int>(shard - g_shards), n);
- }
- return n;
-}
-
+ gpr_log(GPR_INFO, " .. shard[%d] popped %" PRIdPTR,
+ static_cast<int>(shard - g_shards), n);
+ }
+ return n;
+}
+
static grpc_timer_check_result run_some_expired_timers(grpc_millis now,
grpc_millis* next,
- grpc_error* error) {
- grpc_timer_check_result result = GRPC_TIMERS_NOT_CHECKED;
-
+ grpc_error* error) {
+ grpc_timer_check_result result = GRPC_TIMERS_NOT_CHECKED;
+
#if GPR_ARCH_64
// TODO: sreek - Using c-style cast here. static_cast<> gives an error (on
// mac platforms complaining that gpr_atm* is (long *) while
@@ -592,7 +592,7 @@ static grpc_timer_check_result run_some_expired_timers(grpc_millis now,
// safe since we know that both are pointer types and 64-bit wide
grpc_millis min_timer = static_cast<grpc_millis>(
gpr_atm_no_barrier_load((gpr_atm*)(&g_shared_mutables.min_timer)));
- gpr_tls_set(&g_last_seen_min_timer, min_timer);
+ gpr_tls_set(&g_last_seen_min_timer, min_timer);
#else
// On 32-bit systems, gpr_atm_no_barrier_load does not work on 64-bit types
// (like grpc_millis). So all reads and writes to g_shared_mutables.min_timer
@@ -601,85 +601,85 @@ static grpc_timer_check_result run_some_expired_timers(grpc_millis now,
grpc_millis min_timer = g_shared_mutables.min_timer;
gpr_mu_unlock(&g_shared_mutables.mu);
#endif
- if (now < min_timer) {
- if (next != nullptr) *next = GPR_MIN(*next, min_timer);
- return GRPC_TIMERS_CHECKED_AND_EMPTY;
- }
-
- if (gpr_spinlock_trylock(&g_shared_mutables.checker_mu)) {
- gpr_mu_lock(&g_shared_mutables.mu);
- result = GRPC_TIMERS_CHECKED_AND_EMPTY;
-
+ if (now < min_timer) {
+ if (next != nullptr) *next = GPR_MIN(*next, min_timer);
+ return GRPC_TIMERS_CHECKED_AND_EMPTY;
+ }
+
+ if (gpr_spinlock_trylock(&g_shared_mutables.checker_mu)) {
+ gpr_mu_lock(&g_shared_mutables.mu);
+ result = GRPC_TIMERS_CHECKED_AND_EMPTY;
+
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);
- }
-
- while (g_shard_queue[0]->min_deadline < now ||
+ static_cast<int>(g_shard_queue[0] - g_shards),
+ g_shard_queue[0]->min_deadline);
+ }
+
+ while (g_shard_queue[0]->min_deadline < now ||
(now != GRPC_MILLIS_INF_FUTURE &&
g_shard_queue[0]->min_deadline == now)) {
grpc_millis new_min_deadline;
-
- /* For efficiency, we pop as many available timers as we can from the
- shard. This may violate perfect timer deadline ordering, but that
- shouldn't be a big deal because we don't make ordering guarantees. */
- if (pop_timers(g_shard_queue[0], now, &new_min_deadline, error) > 0) {
- result = GRPC_TIMERS_FIRED;
- }
-
+
+ /* For efficiency, we pop as many available timers as we can from the
+ shard. This may violate perfect timer deadline ordering, but that
+ shouldn't be a big deal because we don't make ordering guarantees. */
+ if (pop_timers(g_shard_queue[0], now, &new_min_deadline, error) > 0) {
+ result = GRPC_TIMERS_FIRED;
+ }
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- gpr_log(GPR_INFO,
- " .. result --> %d"
+ gpr_log(GPR_INFO,
+ " .. result --> %d"
", shard[%d]->min_deadline %" PRId64 " --> %" PRId64
", now=%" PRId64,
- result, static_cast<int>(g_shard_queue[0] - g_shards),
- g_shard_queue[0]->min_deadline, new_min_deadline, now);
- }
-
- /* An grpc_timer_init() on the shard could intervene here, adding a new
- timer that is earlier than new_min_deadline. However,
- grpc_timer_init() will block on the master_lock before it can call
- set_min_deadline, so this one will complete first and then the Addtimer
- will reduce the min_deadline (perhaps unnecessarily). */
- g_shard_queue[0]->min_deadline = new_min_deadline;
- note_deadline_change(g_shard_queue[0]);
- }
-
- if (next) {
- *next = GPR_MIN(*next, g_shard_queue[0]->min_deadline);
- }
-
+ result, static_cast<int>(g_shard_queue[0] - g_shards),
+ g_shard_queue[0]->min_deadline, new_min_deadline, now);
+ }
+
+ /* An grpc_timer_init() on the shard could intervene here, adding a new
+ timer that is earlier than new_min_deadline. However,
+ grpc_timer_init() will block on the master_lock before it can call
+ set_min_deadline, so this one will complete first and then the Addtimer
+ will reduce the min_deadline (perhaps unnecessarily). */
+ g_shard_queue[0]->min_deadline = new_min_deadline;
+ note_deadline_change(g_shard_queue[0]);
+ }
+
+ if (next) {
+ *next = GPR_MIN(*next, g_shard_queue[0]->min_deadline);
+ }
+
#if GPR_ARCH_64
// TODO: sreek - Using c-style cast here. static_cast<> gives an error (on
// mac platforms complaining that gpr_atm* is (long *) while
// (&g_shared_mutables.min_timer) is a (long long *). The cast should be
// safe since we know that both are pointer types and 64-bit wide
gpr_atm_no_barrier_store((gpr_atm*)(&g_shared_mutables.min_timer),
- g_shard_queue[0]->min_deadline);
+ g_shard_queue[0]->min_deadline);
#else
// On 32-bit systems, gpr_atm_no_barrier_store does not work on 64-bit
// types (like grpc_millis). So all reads and writes to
// g_shared_mutables.min_timer are done under g_shared_mutables.mu
g_shared_mutables.min_timer = g_shard_queue[0]->min_deadline;
#endif
- gpr_mu_unlock(&g_shared_mutables.mu);
- gpr_spinlock_unlock(&g_shared_mutables.checker_mu);
- }
-
- GRPC_ERROR_UNREF(error);
-
- return result;
-}
-
-static grpc_timer_check_result timer_check(grpc_millis* next) {
- // prelude
- grpc_millis now = grpc_core::ExecCtx::Get()->Now();
-
+ gpr_mu_unlock(&g_shared_mutables.mu);
+ gpr_spinlock_unlock(&g_shared_mutables.checker_mu);
+ }
+
+ GRPC_ERROR_UNREF(error);
+
+ return result;
+}
+
+static grpc_timer_check_result timer_check(grpc_millis* next) {
+ // prelude
+ grpc_millis now = grpc_core::ExecCtx::Get()->Now();
+
#if GPR_ARCH_64
- /* fetch from a thread-local first: this avoids contention on a globally
- mutable cacheline in the common case */
- grpc_millis min_timer = gpr_tls_get(&g_last_seen_min_timer);
+ /* fetch from a thread-local first: this avoids contention on a globally
+ mutable cacheline in the common case */
+ grpc_millis min_timer = gpr_tls_get(&g_last_seen_min_timer);
#else
// On 32-bit systems, we currently do not have thread local support for 64-bit
// types. In this case, directly read from g_shared_mutables.min_timer.
@@ -691,32 +691,32 @@ static grpc_timer_check_result timer_check(grpc_millis* next) {
gpr_mu_unlock(&g_shared_mutables.mu);
#endif
- if (now < min_timer) {
- if (next != nullptr) {
- *next = GPR_MIN(*next, min_timer);
- }
+ if (now < min_timer) {
+ if (next != nullptr) {
+ *next = GPR_MIN(*next, min_timer);
+ }
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
gpr_log(GPR_INFO, "TIMER CHECK SKIP: now=%" PRId64 " min_timer=%" PRId64,
now, min_timer);
- }
- return GRPC_TIMERS_CHECKED_AND_EMPTY;
- }
-
- grpc_error* shutdown_error =
- now != GRPC_MILLIS_INF_FUTURE
- ? GRPC_ERROR_NONE
- : GRPC_ERROR_CREATE_FROM_STATIC_STRING("Shutting down timer system");
-
- // tracing
+ }
+ return GRPC_TIMERS_CHECKED_AND_EMPTY;
+ }
+
+ grpc_error* shutdown_error =
+ now != GRPC_MILLIS_INF_FUTURE
+ ? GRPC_ERROR_NONE
+ : GRPC_ERROR_CREATE_FROM_STATIC_STRING("Shutting down timer system");
+
+ // tracing
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
TString next_str;
- if (next == nullptr) {
+ if (next == nullptr) {
next_str = "NULL";
- } else {
+ } else {
next_str = y_absl::StrCat(*next);
- }
+ }
#if GPR_ARCH_64
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"TIMER CHECK BEGIN: now=%" PRId64 " next=%s tls_min=%" PRId64
" glob_min=%" PRId64,
now, next_str.c_str(), min_timer,
@@ -726,23 +726,23 @@ static grpc_timer_check_result timer_check(grpc_millis* next) {
gpr_log(GPR_INFO, "TIMER CHECK BEGIN: now=%" PRId64 " next=%s min=%" PRId64,
now, next_str.c_str(), min_timer);
#endif
- }
- // actual code
- grpc_timer_check_result r =
- run_some_expired_timers(now, next, shutdown_error);
- // tracing
+ }
+ // actual code
+ grpc_timer_check_result r =
+ run_some_expired_timers(now, next, shutdown_error);
+ // tracing
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
TString next_str;
- if (next == nullptr) {
+ if (next == nullptr) {
next_str = "NULL";
- } else {
+ } else {
next_str = y_absl::StrCat(*next);
- }
+ }
gpr_log(GPR_INFO, "TIMER CHECK END: r=%d; next=%s", r, next_str.c_str());
- }
- return r;
-}
-
-grpc_timer_vtable grpc_generic_timer_vtable = {
- timer_init, timer_cancel, timer_check,
- timer_list_init, timer_list_shutdown, timer_consume_kick};
+ }
+ return r;
+}
+
+grpc_timer_vtable grpc_generic_timer_vtable = {
+ timer_init, timer_cancel, timer_check,
+ timer_list_init, timer_list_shutdown, timer_consume_kick};
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.h b/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.h
index 97a45133553..2225a6691d8 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.h
@@ -1,39 +1,39 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TIMER_GENERIC_H
#define GRPC_CORE_LIB_IOMGR_TIMER_GENERIC_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/support/time.h>
#include "src/core/lib/iomgr/exec_ctx.h"
struct grpc_timer {
- gpr_atm deadline;
+ gpr_atm deadline;
uint32_t heap_index; /* INVALID_HEAP_INDEX if not in heap */
- bool pending;
- struct grpc_timer* next;
- struct grpc_timer* prev;
- grpc_closure* closure;
-#ifndef NDEBUG
- struct grpc_timer* hash_table_next;
-#endif
+ bool pending;
+ struct grpc_timer* next;
+ struct grpc_timer* prev;
+ grpc_closure* closure;
+#ifndef NDEBUG
+ struct grpc_timer* hash_table_next;
+#endif
};
#endif /* GRPC_CORE_LIB_IOMGR_TIMER_GENERIC_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc
index 2c6a599149b..67a2a1a0a1d 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc
@@ -1,135 +1,135 @@
-/*
- *
- * 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/iomgr/port.h"
-
-#include "src/core/lib/iomgr/timer_heap.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-/* Adjusts a heap so as to move a hole at position i closer to the root,
- until a suitable position is found for element t. Then, copies t into that
- position. This functor is called each time immediately after modifying a
- value in the underlying container, with the offset of the modified element as
- its argument. */
-static void adjust_upwards(grpc_timer** first, uint32_t i, grpc_timer* t) {
- while (i > 0) {
- uint32_t parent = static_cast<uint32_t>((static_cast<int>(i) - 1) / 2);
- if (first[parent]->deadline <= t->deadline) break;
- first[i] = first[parent];
- first[i]->heap_index = i;
- i = parent;
- }
- first[i] = t;
- t->heap_index = i;
-}
-
-/* Adjusts a heap so as to move a hole at position i farther away from the root,
- until a suitable position is found for element t. Then, copies t into that
- position. */
-static void adjust_downwards(grpc_timer** first, uint32_t i, uint32_t length,
- grpc_timer* t) {
- for (;;) {
- uint32_t left_child = 1u + 2u * i;
- if (left_child >= length) break;
- uint32_t right_child = left_child + 1;
- uint32_t next_i = right_child < length && first[left_child]->deadline >
- first[right_child]->deadline
- ? right_child
- : left_child;
- if (t->deadline <= first[next_i]->deadline) break;
- first[i] = first[next_i];
- first[i]->heap_index = i;
- i = next_i;
- }
- first[i] = t;
- t->heap_index = i;
-}
-
-#define SHRINK_MIN_ELEMS 8
-#define SHRINK_FULLNESS_FACTOR 2
-
-static void maybe_shrink(grpc_timer_heap* heap) {
- if (heap->timer_count >= 8 &&
- heap->timer_count <= heap->timer_capacity / SHRINK_FULLNESS_FACTOR / 2) {
- heap->timer_capacity = heap->timer_count * SHRINK_FULLNESS_FACTOR;
- heap->timers = static_cast<grpc_timer**>(
- gpr_realloc(heap->timers, heap->timer_capacity * sizeof(grpc_timer*)));
- }
-}
-
-static void note_changed_priority(grpc_timer_heap* heap, grpc_timer* timer) {
- uint32_t i = timer->heap_index;
- uint32_t parent = static_cast<uint32_t>((static_cast<int>(i) - 1) / 2);
- if (heap->timers[parent]->deadline > timer->deadline) {
- adjust_upwards(heap->timers, i, timer);
- } else {
- adjust_downwards(heap->timers, i, heap->timer_count, timer);
- }
-}
-
-void grpc_timer_heap_init(grpc_timer_heap* heap) {
- memset(heap, 0, sizeof(*heap));
-}
-
-void grpc_timer_heap_destroy(grpc_timer_heap* heap) { gpr_free(heap->timers); }
-
+/*
+ *
+ * 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/iomgr/port.h"
+
+#include "src/core/lib/iomgr/timer_heap.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+/* Adjusts a heap so as to move a hole at position i closer to the root,
+ until a suitable position is found for element t. Then, copies t into that
+ position. This functor is called each time immediately after modifying a
+ value in the underlying container, with the offset of the modified element as
+ its argument. */
+static void adjust_upwards(grpc_timer** first, uint32_t i, grpc_timer* t) {
+ while (i > 0) {
+ uint32_t parent = static_cast<uint32_t>((static_cast<int>(i) - 1) / 2);
+ if (first[parent]->deadline <= t->deadline) break;
+ first[i] = first[parent];
+ first[i]->heap_index = i;
+ i = parent;
+ }
+ first[i] = t;
+ t->heap_index = i;
+}
+
+/* Adjusts a heap so as to move a hole at position i farther away from the root,
+ until a suitable position is found for element t. Then, copies t into that
+ position. */
+static void adjust_downwards(grpc_timer** first, uint32_t i, uint32_t length,
+ grpc_timer* t) {
+ for (;;) {
+ uint32_t left_child = 1u + 2u * i;
+ if (left_child >= length) break;
+ uint32_t right_child = left_child + 1;
+ uint32_t next_i = right_child < length && first[left_child]->deadline >
+ first[right_child]->deadline
+ ? right_child
+ : left_child;
+ if (t->deadline <= first[next_i]->deadline) break;
+ first[i] = first[next_i];
+ first[i]->heap_index = i;
+ i = next_i;
+ }
+ first[i] = t;
+ t->heap_index = i;
+}
+
+#define SHRINK_MIN_ELEMS 8
+#define SHRINK_FULLNESS_FACTOR 2
+
+static void maybe_shrink(grpc_timer_heap* heap) {
+ if (heap->timer_count >= 8 &&
+ heap->timer_count <= heap->timer_capacity / SHRINK_FULLNESS_FACTOR / 2) {
+ heap->timer_capacity = heap->timer_count * SHRINK_FULLNESS_FACTOR;
+ heap->timers = static_cast<grpc_timer**>(
+ gpr_realloc(heap->timers, heap->timer_capacity * sizeof(grpc_timer*)));
+ }
+}
+
+static void note_changed_priority(grpc_timer_heap* heap, grpc_timer* timer) {
+ uint32_t i = timer->heap_index;
+ uint32_t parent = static_cast<uint32_t>((static_cast<int>(i) - 1) / 2);
+ if (heap->timers[parent]->deadline > timer->deadline) {
+ adjust_upwards(heap->timers, i, timer);
+ } else {
+ adjust_downwards(heap->timers, i, heap->timer_count, timer);
+ }
+}
+
+void grpc_timer_heap_init(grpc_timer_heap* heap) {
+ memset(heap, 0, sizeof(*heap));
+}
+
+void grpc_timer_heap_destroy(grpc_timer_heap* heap) { gpr_free(heap->timers); }
+
bool grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer) {
- if (heap->timer_count == heap->timer_capacity) {
- heap->timer_capacity =
- GPR_MAX(heap->timer_capacity + 1, heap->timer_capacity * 3 / 2);
- heap->timers = static_cast<grpc_timer**>(
- gpr_realloc(heap->timers, heap->timer_capacity * sizeof(grpc_timer*)));
- }
- timer->heap_index = heap->timer_count;
- adjust_upwards(heap->timers, heap->timer_count, timer);
- heap->timer_count++;
- return timer->heap_index == 0;
-}
-
-void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer) {
- uint32_t i = timer->heap_index;
- if (i == heap->timer_count - 1) {
- heap->timer_count--;
- maybe_shrink(heap);
- return;
- }
- heap->timers[i] = heap->timers[heap->timer_count - 1];
- heap->timers[i]->heap_index = i;
- heap->timer_count--;
- maybe_shrink(heap);
- note_changed_priority(heap, heap->timers[i]);
-}
-
+ if (heap->timer_count == heap->timer_capacity) {
+ heap->timer_capacity =
+ GPR_MAX(heap->timer_capacity + 1, heap->timer_capacity * 3 / 2);
+ heap->timers = static_cast<grpc_timer**>(
+ gpr_realloc(heap->timers, heap->timer_capacity * sizeof(grpc_timer*)));
+ }
+ timer->heap_index = heap->timer_count;
+ adjust_upwards(heap->timers, heap->timer_count, timer);
+ heap->timer_count++;
+ return timer->heap_index == 0;
+}
+
+void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer) {
+ uint32_t i = timer->heap_index;
+ if (i == heap->timer_count - 1) {
+ heap->timer_count--;
+ maybe_shrink(heap);
+ return;
+ }
+ heap->timers[i] = heap->timers[heap->timer_count - 1];
+ heap->timers[i]->heap_index = i;
+ heap->timer_count--;
+ maybe_shrink(heap);
+ note_changed_priority(heap, heap->timers[i]);
+}
+
bool grpc_timer_heap_is_empty(grpc_timer_heap* heap) {
- return heap->timer_count == 0;
-}
-
-grpc_timer* grpc_timer_heap_top(grpc_timer_heap* heap) {
- return heap->timers[0];
-}
-
-void grpc_timer_heap_pop(grpc_timer_heap* heap) {
- grpc_timer_heap_remove(heap, grpc_timer_heap_top(heap));
-}
+ return heap->timer_count == 0;
+}
+
+grpc_timer* grpc_timer_heap_top(grpc_timer_heap* heap) {
+ return heap->timers[0];
+}
+
+void grpc_timer_heap_pop(grpc_timer_heap* heap) {
+ grpc_timer_heap_remove(heap, grpc_timer_heap_top(heap));
+}
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h
index 2b08c651086..5f345cf7133 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h
@@ -1,42 +1,42 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TIMER_HEAP_H
#define GRPC_CORE_LIB_IOMGR_TIMER_HEAP_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/timer.h"
struct grpc_timer_heap {
- grpc_timer** timers;
+ grpc_timer** timers;
uint32_t timer_count;
uint32_t timer_capacity;
};
/* return true if the new timer is the first timer in the heap */
bool grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer);
-void grpc_timer_heap_init(grpc_timer_heap* heap);
-void grpc_timer_heap_destroy(grpc_timer_heap* heap);
+void grpc_timer_heap_init(grpc_timer_heap* heap);
+void grpc_timer_heap_destroy(grpc_timer_heap* heap);
-void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer);
-grpc_timer* grpc_timer_heap_top(grpc_timer_heap* heap);
-void grpc_timer_heap_pop(grpc_timer_heap* heap);
+void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer);
+grpc_timer* grpc_timer_heap_top(grpc_timer_heap* heap);
+void grpc_timer_heap_pop(grpc_timer_heap* heap);
bool grpc_timer_heap_is_empty(grpc_timer_heap* heap);
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 96d502c5108..95d1b777d2c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc
@@ -1,104 +1,104 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/iomgr/timer_manager.h"
-#include <inttypes.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/thd.h"
-#include "src/core/lib/iomgr/timer.h"
-
-struct completed_thread {
- grpc_core::Thread thd;
- completed_thread* next;
-};
-
-extern grpc_core::TraceFlag grpc_timer_check_trace;
-
-// global mutex
-static gpr_mu g_mu;
-// are we multi-threaded
-static bool g_threaded;
-// cv to wait until a thread is needed
-static gpr_cv g_cv_wait;
-// cv for notification when threading ends
-static gpr_cv g_cv_shutdown;
-// number of threads in the system
-static int g_thread_count;
-// number of threads sitting around waiting
-static int g_waiter_count;
-// linked list of threads that have completed (and need joining)
-static completed_thread* g_completed_threads;
-// was the manager kicked by the timer system
-static bool g_kicked;
-// is there a thread waiting until the next timer should fire?
-static bool g_has_timed_waiter;
-// the deadline of the current timed waiter thread (only relevant if
-// g_has_timed_waiter is true)
-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;
+#include <inttypes.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/iomgr/timer.h"
+
+struct completed_thread {
+ grpc_core::Thread thd;
+ completed_thread* next;
+};
+
+extern grpc_core::TraceFlag grpc_timer_check_trace;
+
+// global mutex
+static gpr_mu g_mu;
+// are we multi-threaded
+static bool g_threaded;
+// cv to wait until a thread is needed
+static gpr_cv g_cv_wait;
+// cv for notification when threading ends
+static gpr_cv g_cv_shutdown;
+// number of threads in the system
+static int g_thread_count;
+// number of threads sitting around waiting
+static int g_waiter_count;
+// linked list of threads that have completed (and need joining)
+static completed_thread* g_completed_threads;
+// was the manager kicked by the timer system
+static bool g_kicked;
+// is there a thread waiting until the next timer should fire?
+static bool g_has_timed_waiter;
+// the deadline of the current timed waiter thread (only relevant if
+// g_has_timed_waiter is true)
+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;
-
-static void timer_thread(void* completed_thread_ptr);
-
-static void gc_completed_threads(void) {
- if (g_completed_threads != nullptr) {
- completed_thread* to_gc = g_completed_threads;
- g_completed_threads = nullptr;
- gpr_mu_unlock(&g_mu);
- while (to_gc != nullptr) {
- to_gc->thd.Join();
- completed_thread* next = to_gc->next;
- gpr_free(to_gc);
- to_gc = next;
- }
- gpr_mu_lock(&g_mu);
- }
-}
-
-static void start_timer_thread_and_unlock(void) {
- GPR_ASSERT(g_threaded);
- ++g_waiter_count;
- ++g_thread_count;
- gpr_mu_unlock(&g_mu);
+
+static void timer_thread(void* completed_thread_ptr);
+
+static void gc_completed_threads(void) {
+ if (g_completed_threads != nullptr) {
+ completed_thread* to_gc = g_completed_threads;
+ g_completed_threads = nullptr;
+ gpr_mu_unlock(&g_mu);
+ while (to_gc != nullptr) {
+ to_gc->thd.Join();
+ completed_thread* next = to_gc->next;
+ gpr_free(to_gc);
+ to_gc = next;
+ }
+ gpr_mu_lock(&g_mu);
+ }
+}
+
+static void start_timer_thread_and_unlock(void) {
+ GPR_ASSERT(g_threaded);
+ ++g_waiter_count;
+ ++g_thread_count;
+ gpr_mu_unlock(&g_mu);
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- gpr_log(GPR_INFO, "Spawn timer thread");
- }
- completed_thread* ct =
- static_cast<completed_thread*>(gpr_malloc(sizeof(*ct)));
- ct->thd = grpc_core::Thread("grpc_global_timer", timer_thread, ct);
- ct->thd.Start();
-}
-
-void grpc_timer_manager_tick() {
- grpc_core::ExecCtx exec_ctx;
+ gpr_log(GPR_INFO, "Spawn timer thread");
+ }
+ completed_thread* ct =
+ static_cast<completed_thread*>(gpr_malloc(sizeof(*ct)));
+ ct->thd = grpc_core::Thread("grpc_global_timer", timer_thread, ct);
+ ct->thd.Start();
+}
+
+void grpc_timer_manager_tick() {
+ grpc_core::ExecCtx exec_ctx;
grpc_timer_check(nullptr);
-}
-
-static void run_some_timers() {
+}
+
+static void run_some_timers() {
// In the case of timers, the ExecCtx for the thread is declared
// in the timer thread itself, but this is the point where we
// could start seeing application-level callbacks. No need to
@@ -107,257 +107,257 @@ static void run_some_timers() {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx(
GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD);
- // if there's something to execute...
- gpr_mu_lock(&g_mu);
- // remove a waiter from the pool, and start another thread if necessary
- --g_waiter_count;
- if (g_waiter_count == 0 && g_threaded) {
+ // if there's something to execute...
+ gpr_mu_lock(&g_mu);
+ // remove a waiter from the pool, and start another thread if necessary
+ --g_waiter_count;
+ if (g_waiter_count == 0 && g_threaded) {
// The number of timer threads is always increasing until all the threads
// are stopped. In rare cases, if a large number of timers fire
// simultaneously, we may end up using a large number of threads.
- start_timer_thread_and_unlock();
- } else {
+ start_timer_thread_and_unlock();
+ } else {
// 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) {
+ // waiter so that the next deadline is not missed
+ if (!g_has_timed_waiter) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- gpr_log(GPR_INFO, "kick untimed waiter");
- }
- gpr_cv_signal(&g_cv_wait);
- }
- gpr_mu_unlock(&g_mu);
- }
- // without our lock, flush the exec_ctx
+ gpr_log(GPR_INFO, "kick untimed waiter");
+ }
+ gpr_cv_signal(&g_cv_wait);
+ }
+ gpr_mu_unlock(&g_mu);
+ }
+ // without our lock, flush the exec_ctx
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- gpr_log(GPR_INFO, "flush exec_ctx");
- }
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(&g_mu);
- // garbage collect any threads hanging out that are dead
- gc_completed_threads();
- // get ready to wait again
- ++g_waiter_count;
- gpr_mu_unlock(&g_mu);
-}
-
-// wait until 'next' (or forever if there is already a timed waiter in the pool)
-// returns true if the thread should continue executing (false if it should
-// shutdown)
-static bool wait_until(grpc_millis next) {
- gpr_mu_lock(&g_mu);
- // if we're not threaded anymore, leave
- if (!g_threaded) {
- gpr_mu_unlock(&g_mu);
- return false;
- }
-
- // If g_kicked is true at this point, it means there was a kick from the timer
- // system that the timer-manager threads here missed. We cannot trust 'next'
- // here any longer (since there might be an earlier deadline). So if g_kicked
- // is true at this point, we should quickly exit this and get the next
- // deadline from the timer system
-
- if (!g_kicked) {
- // if there's no timed waiter, we should become one: that waiter waits
- // only until the next timer should expire. All other timers wait forever
- //
- // 'g_timed_waiter_generation' is a global generation counter. The idea here
- // is that the thread becoming a timed-waiter increments and stores this
- // global counter locally in 'my_timed_waiter_generation' before going to
- // sleep. After waking up, if my_timed_waiter_generation ==
- // g_timed_waiter_generation, it can be sure that it was the timed_waiter
- // thread (and that no other thread took over while this was asleep)
- //
- // Initialize my_timed_waiter_generation to some value that is NOT equal to
- // g_timed_waiter_generation
- uint64_t my_timed_waiter_generation = g_timed_waiter_generation - 1;
-
- /* If there's no timed waiter, we should become one: that waiter waits only
- until the next timer should expire. All other timer threads wait forever
- unless their 'next' is earlier than the current timed-waiter's deadline
- (in which case the thread with earlier 'next' takes over as the new timed
- waiter) */
- if (next != GRPC_MILLIS_INF_FUTURE) {
- if (!g_has_timed_waiter || (next < g_timed_waiter_deadline)) {
- my_timed_waiter_generation = ++g_timed_waiter_generation;
- g_has_timed_waiter = true;
- g_timed_waiter_deadline = next;
-
+ gpr_log(GPR_INFO, "flush exec_ctx");
+ }
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_mu_lock(&g_mu);
+ // garbage collect any threads hanging out that are dead
+ gc_completed_threads();
+ // get ready to wait again
+ ++g_waiter_count;
+ gpr_mu_unlock(&g_mu);
+}
+
+// wait until 'next' (or forever if there is already a timed waiter in the pool)
+// returns true if the thread should continue executing (false if it should
+// shutdown)
+static bool wait_until(grpc_millis next) {
+ gpr_mu_lock(&g_mu);
+ // if we're not threaded anymore, leave
+ if (!g_threaded) {
+ gpr_mu_unlock(&g_mu);
+ return false;
+ }
+
+ // If g_kicked is true at this point, it means there was a kick from the timer
+ // system that the timer-manager threads here missed. We cannot trust 'next'
+ // here any longer (since there might be an earlier deadline). So if g_kicked
+ // is true at this point, we should quickly exit this and get the next
+ // deadline from the timer system
+
+ if (!g_kicked) {
+ // if there's no timed waiter, we should become one: that waiter waits
+ // only until the next timer should expire. All other timers wait forever
+ //
+ // 'g_timed_waiter_generation' is a global generation counter. The idea here
+ // is that the thread becoming a timed-waiter increments and stores this
+ // global counter locally in 'my_timed_waiter_generation' before going to
+ // sleep. After waking up, if my_timed_waiter_generation ==
+ // g_timed_waiter_generation, it can be sure that it was the timed_waiter
+ // thread (and that no other thread took over while this was asleep)
+ //
+ // Initialize my_timed_waiter_generation to some value that is NOT equal to
+ // g_timed_waiter_generation
+ uint64_t my_timed_waiter_generation = g_timed_waiter_generation - 1;
+
+ /* If there's no timed waiter, we should become one: that waiter waits only
+ until the next timer should expire. All other timer threads wait forever
+ unless their 'next' is earlier than the current timed-waiter's deadline
+ (in which case the thread with earlier 'next' takes over as the new timed
+ waiter) */
+ if (next != GRPC_MILLIS_INF_FUTURE) {
+ if (!g_has_timed_waiter || (next < g_timed_waiter_deadline)) {
+ my_timed_waiter_generation = ++g_timed_waiter_generation;
+ g_has_timed_waiter = true;
+ g_timed_waiter_deadline = next;
+
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- grpc_millis wait_time = next - grpc_core::ExecCtx::Get()->Now();
+ grpc_millis wait_time = next - grpc_core::ExecCtx::Get()->Now();
gpr_log(GPR_INFO, "sleep for a %" PRId64 " milliseconds", wait_time);
- }
- } else { // g_timed_waiter == true && next >= g_timed_waiter_deadline
- next = GRPC_MILLIS_INF_FUTURE;
- }
- }
-
+ }
+ } else { // g_timed_waiter == true && next >= g_timed_waiter_deadline
+ 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));
-
+ 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)) {
- gpr_log(GPR_INFO, "wait ended: was_timed:%d kicked:%d",
- my_timed_waiter_generation == g_timed_waiter_generation,
- g_kicked);
- }
- // if this was the timed waiter, then we need to check timers, and flag
- // 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) {
+ gpr_log(GPR_INFO, "wait ended: was_timed:%d kicked:%d",
+ my_timed_waiter_generation == g_timed_waiter_generation,
+ g_kicked);
+ }
+ // if this was the timed waiter, then we need to check timers, and flag
+ // 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_has_timed_waiter = false;
- g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE;
- }
- }
-
- // if this was a kick from the timer system, consume it (and don't stop
- // this thread yet)
- if (g_kicked) {
- grpc_timer_consume_kick();
- g_kicked = false;
- }
-
- gpr_mu_unlock(&g_mu);
- return true;
-}
-
-static void timer_main_loop() {
- for (;;) {
- grpc_millis next = GRPC_MILLIS_INF_FUTURE;
- grpc_core::ExecCtx::Get()->InvalidateNow();
-
- // check timer state, updates next to the next time to run a check
- switch (grpc_timer_check(&next)) {
- case GRPC_TIMERS_FIRED:
- run_some_timers();
- break;
- case GRPC_TIMERS_NOT_CHECKED:
- /* This case only happens under contention, meaning more than one timer
- manager thread checked timers concurrently.
-
- If that happens, we're guaranteed that some other thread has just
- checked timers, and this will avalanche into some other thread seeing
- empty timers and doing a timed sleep.
-
- Consequently, we can just sleep forever here and be happy at some
- saved wakeup cycles. */
+ g_has_timed_waiter = false;
+ g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE;
+ }
+ }
+
+ // if this was a kick from the timer system, consume it (and don't stop
+ // this thread yet)
+ if (g_kicked) {
+ grpc_timer_consume_kick();
+ g_kicked = false;
+ }
+
+ gpr_mu_unlock(&g_mu);
+ return true;
+}
+
+static void timer_main_loop() {
+ for (;;) {
+ grpc_millis next = GRPC_MILLIS_INF_FUTURE;
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+
+ // check timer state, updates next to the next time to run a check
+ switch (grpc_timer_check(&next)) {
+ case GRPC_TIMERS_FIRED:
+ run_some_timers();
+ break;
+ case GRPC_TIMERS_NOT_CHECKED:
+ /* This case only happens under contention, meaning more than one timer
+ manager thread checked timers concurrently.
+
+ If that happens, we're guaranteed that some other thread has just
+ checked timers, and this will avalanche into some other thread seeing
+ empty timers and doing a timed sleep.
+
+ Consequently, we can just sleep forever here and be happy at some
+ saved wakeup cycles. */
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;
+ gpr_log(GPR_INFO, "timers not checked: expect another thread to");
+ }
+ next = GRPC_MILLIS_INF_FUTURE;
// fallthrough
- case GRPC_TIMERS_CHECKED_AND_EMPTY:
- if (!wait_until(next)) {
- return;
- }
- break;
- }
- }
-}
-
-static void timer_thread_cleanup(completed_thread* ct) {
- gpr_mu_lock(&g_mu);
- // terminate the thread: drop the waiter count, thread count, and let whomever
- // stopped the threading stuff know that we're done
- --g_waiter_count;
- --g_thread_count;
- if (0 == g_thread_count) {
- gpr_cv_signal(&g_cv_shutdown);
- }
- ct->next = g_completed_threads;
- g_completed_threads = ct;
- gpr_mu_unlock(&g_mu);
+ case GRPC_TIMERS_CHECKED_AND_EMPTY:
+ if (!wait_until(next)) {
+ return;
+ }
+ break;
+ }
+ }
+}
+
+static void timer_thread_cleanup(completed_thread* ct) {
+ gpr_mu_lock(&g_mu);
+ // terminate the thread: drop the waiter count, thread count, and let whomever
+ // stopped the threading stuff know that we're done
+ --g_waiter_count;
+ --g_thread_count;
+ if (0 == g_thread_count) {
+ gpr_cv_signal(&g_cv_shutdown);
+ }
+ ct->next = g_completed_threads;
+ g_completed_threads = ct;
+ gpr_mu_unlock(&g_mu);
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
- gpr_log(GPR_INFO, "End timer thread");
- }
-}
-
-static void timer_thread(void* completed_thread_ptr) {
- // this threads exec_ctx: we try to run things through to completion here
- // since it's easy to spin up new threads
+ gpr_log(GPR_INFO, "End timer thread");
+ }
+}
+
+static void timer_thread(void* completed_thread_ptr) {
+ // this threads exec_ctx: we try to run things through to completion here
+ // since it's easy to spin up new threads
grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD);
- timer_main_loop();
-
- timer_thread_cleanup(static_cast<completed_thread*>(completed_thread_ptr));
-}
-
-static void start_threads(void) {
- gpr_mu_lock(&g_mu);
- if (!g_threaded) {
- g_threaded = true;
- start_timer_thread_and_unlock();
- } else {
- gpr_mu_unlock(&g_mu);
- }
-}
-
-void grpc_timer_manager_init(void) {
- gpr_mu_init(&g_mu);
- gpr_cv_init(&g_cv_wait);
- gpr_cv_init(&g_cv_shutdown);
- g_threaded = false;
- g_thread_count = 0;
- g_waiter_count = 0;
- g_completed_threads = nullptr;
-
- g_has_timed_waiter = false;
- g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE;
-
- start_threads();
-}
-
-static void stop_threads(void) {
- gpr_mu_lock(&g_mu);
+ timer_main_loop();
+
+ timer_thread_cleanup(static_cast<completed_thread*>(completed_thread_ptr));
+}
+
+static void start_threads(void) {
+ gpr_mu_lock(&g_mu);
+ if (!g_threaded) {
+ g_threaded = true;
+ start_timer_thread_and_unlock();
+ } else {
+ gpr_mu_unlock(&g_mu);
+ }
+}
+
+void grpc_timer_manager_init(void) {
+ gpr_mu_init(&g_mu);
+ gpr_cv_init(&g_cv_wait);
+ gpr_cv_init(&g_cv_shutdown);
+ g_threaded = false;
+ g_thread_count = 0;
+ g_waiter_count = 0;
+ g_completed_threads = nullptr;
+
+ g_has_timed_waiter = false;
+ g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE;
+
+ start_threads();
+}
+
+static void stop_threads(void) {
+ gpr_mu_lock(&g_mu);
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);
+ 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)) {
- 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));
+ 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)) {
- gpr_log(GPR_INFO, "num timer threads: %d", g_thread_count);
- }
- gc_completed_threads();
- }
- }
+ gpr_log(GPR_INFO, "num timer threads: %d", g_thread_count);
+ }
+ gc_completed_threads();
+ }
+ }
g_wakeups = 0;
- gpr_mu_unlock(&g_mu);
-}
-
-void grpc_timer_manager_shutdown(void) {
- stop_threads();
-
- gpr_mu_destroy(&g_mu);
- gpr_cv_destroy(&g_cv_wait);
- gpr_cv_destroy(&g_cv_shutdown);
-}
-
-void grpc_timer_manager_set_threading(bool threaded) {
- if (threaded) {
- start_threads();
- } else {
- stop_threads();
- }
-}
-
-void grpc_kick_poller(void) {
- gpr_mu_lock(&g_mu);
- g_kicked = true;
- g_has_timed_waiter = false;
- g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE;
- ++g_timed_waiter_generation;
- gpr_cv_signal(&g_cv_wait);
- gpr_mu_unlock(&g_mu);
-}
+ gpr_mu_unlock(&g_mu);
+}
+
+void grpc_timer_manager_shutdown(void) {
+ stop_threads();
+
+ gpr_mu_destroy(&g_mu);
+ gpr_cv_destroy(&g_cv_wait);
+ gpr_cv_destroy(&g_cv_shutdown);
+}
+
+void grpc_timer_manager_set_threading(bool threaded) {
+ if (threaded) {
+ start_threads();
+ } else {
+ stop_threads();
+ }
+}
+
+void grpc_kick_poller(void) {
+ gpr_mu_lock(&g_mu);
+ g_kicked = true;
+ g_has_timed_waiter = false;
+ g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE;
+ ++g_timed_waiter_generation;
+ gpr_cv_signal(&g_cv_wait);
+ gpr_mu_unlock(&g_mu);
+}
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 d407cbbc2b7..06e806e141d 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h
@@ -1,41 +1,41 @@
-/*
- *
- * 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_IOMGR_TIMER_MANAGER_H
-#define GRPC_CORE_LIB_IOMGR_TIMER_MANAGER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_IOMGR_TIMER_MANAGER_H
+#define GRPC_CORE_LIB_IOMGR_TIMER_MANAGER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
/* Timer Manager tries to keep only one thread waiting for the next timeout at
all times, and thus effectively preventing the thundering herd problem. */
-
-void grpc_timer_manager_init(void);
-void grpc_timer_manager_shutdown(void);
-
-/* enable/disable threading - must be called after grpc_timer_manager_init and
- * before grpc_timer_manager_shutdown */
-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);
+
+void grpc_timer_manager_init(void);
+void grpc_timer_manager_shutdown(void);
+
+/* enable/disable threading - must be called after grpc_timer_manager_init and
+ * before grpc_timer_manager_shutdown */
+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);
-
-#endif /* GRPC_CORE_LIB_IOMGR_TIMER_MANAGER_H */
+
+#endif /* GRPC_CORE_LIB_IOMGR_TIMER_MANAGER_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_uv.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_uv.cc
index 8b10edffa01..5f4b8518d94 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/timer_uv.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_uv.cc
@@ -1,66 +1,66 @@
-/*
- *
- * 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"
-
-#ifdef GRPC_UV
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/iomgr/iomgr_custom.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/iomgr/timer_custom.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"
+
+#ifdef GRPC_UV
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/iomgr/iomgr_custom.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/iomgr/timer_custom.h"
+
#error #include <uv.h>
-
-static void timer_close_callback(uv_handle_t* handle) { gpr_free(handle); }
-
-static void stop_uv_timer(uv_timer_t* handle) {
- uv_timer_stop(handle);
- uv_unref((uv_handle_t*)handle);
- uv_close((uv_handle_t*)handle, timer_close_callback);
-}
-
-void run_expired_timer(uv_timer_t* handle) {
- grpc_custom_timer* timer_wrapper = (grpc_custom_timer*)handle->data;
- grpc_custom_timer_callback(timer_wrapper, GRPC_ERROR_NONE);
-}
-
-static void timer_start(grpc_custom_timer* t) {
- uv_timer_t* uv_timer;
- uv_timer = (uv_timer_t*)gpr_malloc(sizeof(uv_timer_t));
- uv_timer_init(uv_default_loop(), uv_timer);
- uv_timer->data = t;
- t->timer = (void*)uv_timer;
- uv_timer_start(uv_timer, run_expired_timer, t->timeout_ms, 0);
- // 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_timer);
-}
-
-static void timer_stop(grpc_custom_timer* t) {
- stop_uv_timer((uv_timer_t*)t->timer);
-}
-
-grpc_custom_timer_vtable uv_timer_vtable = {timer_start, timer_stop};
-
-#endif
+
+static void timer_close_callback(uv_handle_t* handle) { gpr_free(handle); }
+
+static void stop_uv_timer(uv_timer_t* handle) {
+ uv_timer_stop(handle);
+ uv_unref((uv_handle_t*)handle);
+ uv_close((uv_handle_t*)handle, timer_close_callback);
+}
+
+void run_expired_timer(uv_timer_t* handle) {
+ grpc_custom_timer* timer_wrapper = (grpc_custom_timer*)handle->data;
+ grpc_custom_timer_callback(timer_wrapper, GRPC_ERROR_NONE);
+}
+
+static void timer_start(grpc_custom_timer* t) {
+ uv_timer_t* uv_timer;
+ uv_timer = (uv_timer_t*)gpr_malloc(sizeof(uv_timer_t));
+ uv_timer_init(uv_default_loop(), uv_timer);
+ uv_timer->data = t;
+ t->timer = (void*)uv_timer;
+ uv_timer_start(uv_timer, run_expired_timer, t->timeout_ms, 0);
+ // 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_timer);
+}
+
+static void timer_stop(grpc_custom_timer* t) {
+ stop_uv_timer((uv_timer_t*)t->timer);
+}
+
+grpc_custom_timer_vtable uv_timer_vtable = {timer_start, timer_stop};
+
+#endif
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 1e7734d6818..40e41b875d8 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc
@@ -1,748 +1,748 @@
-/*
- *
- * 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.
- *
- */
-
-/* FIXME: "posix" files shouldn't be depending on _GNU_SOURCE */
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
-#ifndef SO_RXQ_OVFL
-#define SO_RXQ_OVFL 40
-#endif
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/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.
+ *
+ */
+
+/* FIXME: "posix" files shouldn't be depending on _GNU_SOURCE */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#ifndef SO_RXQ_OVFL
+#define SO_RXQ_OVFL 40
+#endif
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
#ifdef GRPC_POSIX_SOCKET_UDP_SERVER
-
-#include "src/core/lib/iomgr/udp_server.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
+
+#include "src/core/lib/iomgr/udp_server.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
#include <util/generic/string.h>
#include <vector>
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.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/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/ev_posix.h"
-#include "src/core/lib/iomgr/executor.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_factory_posix.h"
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
-
-/* A listener which implements basic features of Listening on a port for
- * I/O events*/
-class GrpcUdpListener {
- public:
- GrpcUdpListener(grpc_udp_server* server, int fd,
- const grpc_resolved_address* addr);
- ~GrpcUdpListener();
-
- /* Called when grpc server starts to listening on the grpc_fd. */
+#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/channel/channel_args.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/ev_posix.h"
+#include "src/core/lib/iomgr/executor.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_factory_posix.h"
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
+
+/* A listener which implements basic features of Listening on a port for
+ * I/O events*/
+class GrpcUdpListener {
+ public:
+ GrpcUdpListener(grpc_udp_server* server, int fd,
+ const grpc_resolved_address* addr);
+ ~GrpcUdpListener();
+
+ /* Called when grpc server starts to listening on the grpc_fd. */
void StartListening(const std::vector<grpc_pollset*>* pollsets,
- GrpcUdpHandlerFactory* handler_factory);
-
- /* Called when data is available to read from the socket.
- * Return true if there is more data to read from fd. */
- void OnRead(grpc_error* error, void* do_read_arg);
-
- /* Called when the socket is writeable. The given closure should be scheduled
- * when the socket becomes blocked next time. */
- void OnCanWrite(grpc_error* error, void* do_write_arg);
-
- /* Called when the grpc_fd is about to be orphaned (and the FD closed). */
- void OnFdAboutToOrphan();
-
- /* Called to orphan fd of this listener.*/
- void OrphanFd();
-
- /* Called when this listener is going to be destroyed. */
- void OnDestroy();
-
- int fd() const { return fd_; }
-
- protected:
- grpc_fd* emfd() const { return emfd_; }
-
- gpr_mu* mutex() { return &mutex_; }
-
- private:
- /* event manager callback when reads are ready */
- static void on_read(void* arg, grpc_error* error);
- static void on_write(void* arg, grpc_error* error);
-
- static void do_read(void* arg, grpc_error* error);
- static void do_write(void* arg, grpc_error* error);
- // Wrapper of grpc_fd_notify_on_write() with a grpc_closure callback
- // interface.
- static void fd_notify_on_write_wrapper(void* arg, grpc_error* error);
-
- static void shutdown_fd(void* args, grpc_error* error);
-
- int fd_;
- grpc_fd* emfd_;
- grpc_udp_server* server_;
- grpc_resolved_address addr_;
- grpc_closure read_closure_;
- grpc_closure write_closure_;
- // To be called when corresponding QuicGrpcServer closes all active
- // connections.
- grpc_closure orphan_fd_closure_;
- grpc_closure destroyed_closure_;
- // To be scheduled on another thread to actually read/write.
- grpc_closure do_read_closure_;
- grpc_closure do_write_closure_;
- grpc_closure notify_on_write_closure_;
- // True if orphan_cb is trigered.
- bool orphan_notified_;
- // True if grpc_fd_notify_on_write() is called after on_write() call.
- bool notify_on_write_armed_;
- // True if fd has been shutdown.
- bool already_shutdown_;
- // Object actually handles I/O events. Assigned in StartListening().
- GrpcUdpHandler* udp_handler_ = nullptr;
- // To be notified on destruction.
- GrpcUdpHandlerFactory* handler_factory_ = nullptr;
- // Required to access above fields.
- gpr_mu mutex_;
-};
-
-GrpcUdpListener::GrpcUdpListener(grpc_udp_server* server, int fd,
- const grpc_resolved_address* addr)
- : fd_(fd),
- server_(server),
- orphan_notified_(false),
- already_shutdown_(false) {
+ GrpcUdpHandlerFactory* handler_factory);
+
+ /* Called when data is available to read from the socket.
+ * Return true if there is more data to read from fd. */
+ void OnRead(grpc_error* error, void* do_read_arg);
+
+ /* Called when the socket is writeable. The given closure should be scheduled
+ * when the socket becomes blocked next time. */
+ void OnCanWrite(grpc_error* error, void* do_write_arg);
+
+ /* Called when the grpc_fd is about to be orphaned (and the FD closed). */
+ void OnFdAboutToOrphan();
+
+ /* Called to orphan fd of this listener.*/
+ void OrphanFd();
+
+ /* Called when this listener is going to be destroyed. */
+ void OnDestroy();
+
+ int fd() const { return fd_; }
+
+ protected:
+ grpc_fd* emfd() const { return emfd_; }
+
+ gpr_mu* mutex() { return &mutex_; }
+
+ private:
+ /* event manager callback when reads are ready */
+ static void on_read(void* arg, grpc_error* error);
+ static void on_write(void* arg, grpc_error* error);
+
+ static void do_read(void* arg, grpc_error* error);
+ static void do_write(void* arg, grpc_error* error);
+ // Wrapper of grpc_fd_notify_on_write() with a grpc_closure callback
+ // interface.
+ static void fd_notify_on_write_wrapper(void* arg, grpc_error* error);
+
+ static void shutdown_fd(void* args, grpc_error* error);
+
+ int fd_;
+ grpc_fd* emfd_;
+ grpc_udp_server* server_;
+ grpc_resolved_address addr_;
+ grpc_closure read_closure_;
+ grpc_closure write_closure_;
+ // To be called when corresponding QuicGrpcServer closes all active
+ // connections.
+ grpc_closure orphan_fd_closure_;
+ grpc_closure destroyed_closure_;
+ // To be scheduled on another thread to actually read/write.
+ grpc_closure do_read_closure_;
+ grpc_closure do_write_closure_;
+ grpc_closure notify_on_write_closure_;
+ // True if orphan_cb is trigered.
+ bool orphan_notified_;
+ // True if grpc_fd_notify_on_write() is called after on_write() call.
+ bool notify_on_write_armed_;
+ // True if fd has been shutdown.
+ bool already_shutdown_;
+ // Object actually handles I/O events. Assigned in StartListening().
+ GrpcUdpHandler* udp_handler_ = nullptr;
+ // To be notified on destruction.
+ GrpcUdpHandlerFactory* handler_factory_ = nullptr;
+ // Required to access above fields.
+ gpr_mu mutex_;
+};
+
+GrpcUdpListener::GrpcUdpListener(grpc_udp_server* server, int fd,
+ const grpc_resolved_address* addr)
+ : fd_(fd),
+ server_(server),
+ orphan_notified_(false),
+ already_shutdown_(false) {
TString addr_str = grpc_sockaddr_to_string(addr, true);
TString name = y_absl::StrCat("udp-server-listener:", addr_str);
emfd_ = grpc_fd_create(fd, name.c_str(), true);
- memcpy(&addr_, addr, sizeof(grpc_resolved_address));
- GPR_ASSERT(emfd_);
- gpr_mu_init(&mutex_);
-}
-
-GrpcUdpListener::~GrpcUdpListener() { gpr_mu_destroy(&mutex_); }
-
-/* the overall server */
-struct grpc_udp_server {
- gpr_mu mu;
-
- /* factory to use for creating and binding sockets, or NULL */
- grpc_socket_factory* socket_factory;
-
- /* active port count: how many ports are actually still listening */
- size_t active_ports;
- /* destroyed port count: how many ports are completely destroyed */
- size_t destroyed_ports;
-
- /* is this server shutting down? (boolean) */
- int shutdown;
-
- /* An array of listeners */
+ memcpy(&addr_, addr, sizeof(grpc_resolved_address));
+ GPR_ASSERT(emfd_);
+ gpr_mu_init(&mutex_);
+}
+
+GrpcUdpListener::~GrpcUdpListener() { gpr_mu_destroy(&mutex_); }
+
+/* the overall server */
+struct grpc_udp_server {
+ gpr_mu mu;
+
+ /* factory to use for creating and binding sockets, or NULL */
+ grpc_socket_factory* socket_factory;
+
+ /* active port count: how many ports are actually still listening */
+ size_t active_ports;
+ /* destroyed port count: how many ports are completely destroyed */
+ size_t destroyed_ports;
+
+ /* is this server shutting down? (boolean) */
+ int shutdown;
+
+ /* An array of listeners */
y_absl::InlinedVector<GrpcUdpListener, 16> listeners;
-
- /* factory for use to create udp listeners */
- GrpcUdpHandlerFactory* handler_factory;
-
- /* shutdown callback */
- grpc_closure* shutdown_complete;
-
+
+ /* factory for use to create udp listeners */
+ GrpcUdpHandlerFactory* handler_factory;
+
+ /* shutdown callback */
+ grpc_closure* shutdown_complete;
+
/* all pollsets interested in new connections. The object pointed at is not
* owned by this struct. */
const std::vector<grpc_pollset*>* pollsets;
- /* opaque object to pass to callbacks */
- void* user_data;
-
- /* latch has_so_reuseport during server creation */
- bool so_reuseport;
-};
-
-static grpc_socket_factory* get_socket_factory(const grpc_channel_args* args) {
- if (args) {
- const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_SOCKET_FACTORY);
- if (arg) {
- GPR_ASSERT(arg->type == GRPC_ARG_POINTER);
- return static_cast<grpc_socket_factory*>(arg->value.pointer.p);
- }
- }
- return nullptr;
-}
-
-grpc_udp_server* grpc_udp_server_create(const grpc_channel_args* args) {
+ /* opaque object to pass to callbacks */
+ void* user_data;
+
+ /* latch has_so_reuseport during server creation */
+ bool so_reuseport;
+};
+
+static grpc_socket_factory* get_socket_factory(const grpc_channel_args* args) {
+ if (args) {
+ const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_SOCKET_FACTORY);
+ if (arg) {
+ GPR_ASSERT(arg->type == GRPC_ARG_POINTER);
+ return static_cast<grpc_socket_factory*>(arg->value.pointer.p);
+ }
+ }
+ return nullptr;
+}
+
+grpc_udp_server* grpc_udp_server_create(const grpc_channel_args* args) {
grpc_udp_server* s = new grpc_udp_server();
- gpr_mu_init(&s->mu);
- s->socket_factory = get_socket_factory(args);
- if (s->socket_factory) {
- grpc_socket_factory_ref(s->socket_factory);
- }
- s->active_ports = 0;
- s->destroyed_ports = 0;
- s->shutdown = 0;
- s->so_reuseport = grpc_is_socket_reuse_port_supported();
- return s;
-}
-
-// static
-void GrpcUdpListener::shutdown_fd(void* args, grpc_error* error) {
- if (args == nullptr) {
- // No-op if shutdown args are null.
- return;
- }
- auto sp = static_cast<GrpcUdpListener*>(args);
- gpr_mu_lock(sp->mutex());
- gpr_log(GPR_DEBUG, "shutdown fd %d", sp->fd_);
- grpc_fd_shutdown(sp->emfd_, GRPC_ERROR_REF(error));
- sp->already_shutdown_ = true;
- if (!sp->notify_on_write_armed_) {
- // Re-arm write notification to notify listener with error. This is
- // necessary to decrement active_ports.
- sp->notify_on_write_armed_ = true;
- grpc_fd_notify_on_write(sp->emfd_, &sp->write_closure_);
- }
- gpr_mu_unlock(sp->mutex());
-}
-
-static void finish_shutdown(grpc_udp_server* s) {
- if (s->shutdown_complete != nullptr) {
+ gpr_mu_init(&s->mu);
+ s->socket_factory = get_socket_factory(args);
+ if (s->socket_factory) {
+ grpc_socket_factory_ref(s->socket_factory);
+ }
+ s->active_ports = 0;
+ s->destroyed_ports = 0;
+ s->shutdown = 0;
+ s->so_reuseport = grpc_is_socket_reuse_port_supported();
+ return s;
+}
+
+// static
+void GrpcUdpListener::shutdown_fd(void* args, grpc_error* error) {
+ if (args == nullptr) {
+ // No-op if shutdown args are null.
+ return;
+ }
+ auto sp = static_cast<GrpcUdpListener*>(args);
+ gpr_mu_lock(sp->mutex());
+ gpr_log(GPR_DEBUG, "shutdown fd %d", sp->fd_);
+ grpc_fd_shutdown(sp->emfd_, GRPC_ERROR_REF(error));
+ sp->already_shutdown_ = true;
+ if (!sp->notify_on_write_armed_) {
+ // Re-arm write notification to notify listener with error. This is
+ // necessary to decrement active_ports.
+ sp->notify_on_write_armed_ = true;
+ grpc_fd_notify_on_write(sp->emfd_, &sp->write_closure_);
+ }
+ gpr_mu_unlock(sp->mutex());
+}
+
+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);
- }
-
- gpr_mu_destroy(&s->mu);
-
- gpr_log(GPR_DEBUG, "Destroy all listeners.");
- for (size_t i = 0; i < s->listeners.size(); ++i) {
- s->listeners[i].OnDestroy();
- }
-
- if (s->socket_factory) {
- grpc_socket_factory_unref(s->socket_factory);
- }
-
+ }
+
+ gpr_mu_destroy(&s->mu);
+
+ gpr_log(GPR_DEBUG, "Destroy all listeners.");
+ for (size_t i = 0; i < s->listeners.size(); ++i) {
+ s->listeners[i].OnDestroy();
+ }
+
+ if (s->socket_factory) {
+ grpc_socket_factory_unref(s->socket_factory);
+ }
+
delete s;
-}
-
+}
+
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++;
- if (s->destroyed_ports == s->listeners.size()) {
- gpr_mu_unlock(&s->mu);
- finish_shutdown(s);
- } else {
- gpr_mu_unlock(&s->mu);
- }
-}
-
-/* called when all listening endpoints have been shutdown, so no further
- events will be received on them - at this point it's safe to destroy
- things */
-static void deactivated_all_ports(grpc_udp_server* s) {
- /* delete ALL the things */
- gpr_mu_lock(&s->mu);
-
- GPR_ASSERT(s->shutdown);
-
+ grpc_udp_server* s = static_cast<grpc_udp_server*>(server);
+ gpr_mu_lock(&s->mu);
+ s->destroyed_ports++;
+ if (s->destroyed_ports == s->listeners.size()) {
+ gpr_mu_unlock(&s->mu);
+ finish_shutdown(s);
+ } else {
+ gpr_mu_unlock(&s->mu);
+ }
+}
+
+/* called when all listening endpoints have been shutdown, so no further
+ events will be received on them - at this point it's safe to destroy
+ things */
+static void deactivated_all_ports(grpc_udp_server* s) {
+ /* delete ALL the things */
+ gpr_mu_lock(&s->mu);
+
+ GPR_ASSERT(s->shutdown);
+
if (s->listeners.empty()) {
- gpr_mu_unlock(&s->mu);
- finish_shutdown(s);
- return;
- }
- for (size_t i = 0; i < s->listeners.size(); ++i) {
- s->listeners[i].OrphanFd();
- }
- gpr_mu_unlock(&s->mu);
-}
-
-void GrpcUdpListener::OrphanFd() {
- gpr_log(GPR_DEBUG, "Orphan fd %d, emfd %p", fd_, emfd_);
- grpc_unlink_if_unix_domain_socket(&addr_);
-
- GRPC_CLOSURE_INIT(&destroyed_closure_, destroyed_port, server_,
- grpc_schedule_on_exec_ctx);
- /* Because at this point, all listening sockets have been shutdown already, no
- * need to call OnFdAboutToOrphan() to notify the handler again. */
+ gpr_mu_unlock(&s->mu);
+ finish_shutdown(s);
+ return;
+ }
+ for (size_t i = 0; i < s->listeners.size(); ++i) {
+ s->listeners[i].OrphanFd();
+ }
+ gpr_mu_unlock(&s->mu);
+}
+
+void GrpcUdpListener::OrphanFd() {
+ gpr_log(GPR_DEBUG, "Orphan fd %d, emfd %p", fd_, emfd_);
+ grpc_unlink_if_unix_domain_socket(&addr_);
+
+ GRPC_CLOSURE_INIT(&destroyed_closure_, destroyed_port, server_,
+ grpc_schedule_on_exec_ctx);
+ /* Because at this point, all listening sockets have been shutdown already, no
+ * need to call OnFdAboutToOrphan() to notify the handler again. */
grpc_fd_orphan(emfd_, &destroyed_closure_, nullptr, "udp_listener_shutdown");
-}
-
-void grpc_udp_server_destroy(grpc_udp_server* s, grpc_closure* on_done) {
- gpr_mu_lock(&s->mu);
-
- GPR_ASSERT(!s->shutdown);
- s->shutdown = 1;
-
- s->shutdown_complete = on_done;
-
- gpr_log(GPR_DEBUG, "start to destroy udp_server");
- /* shutdown all fd's */
- if (s->active_ports) {
- for (size_t i = 0; i < s->listeners.size(); ++i) {
- GrpcUdpListener* sp = &s->listeners[i];
- sp->OnFdAboutToOrphan();
- }
- gpr_mu_unlock(&s->mu);
- } else {
- gpr_mu_unlock(&s->mu);
- deactivated_all_ports(s);
- }
-}
-
-void GrpcUdpListener::OnFdAboutToOrphan() {
- gpr_mu_lock(&mutex_);
- grpc_unlink_if_unix_domain_socket(&addr_);
-
- GRPC_CLOSURE_INIT(&destroyed_closure_, destroyed_port, server_,
- grpc_schedule_on_exec_ctx);
- if (!orphan_notified_ && udp_handler_ != nullptr) {
+}
+
+void grpc_udp_server_destroy(grpc_udp_server* s, grpc_closure* on_done) {
+ gpr_mu_lock(&s->mu);
+
+ GPR_ASSERT(!s->shutdown);
+ s->shutdown = 1;
+
+ s->shutdown_complete = on_done;
+
+ gpr_log(GPR_DEBUG, "start to destroy udp_server");
+ /* shutdown all fd's */
+ if (s->active_ports) {
+ for (size_t i = 0; i < s->listeners.size(); ++i) {
+ GrpcUdpListener* sp = &s->listeners[i];
+ sp->OnFdAboutToOrphan();
+ }
+ gpr_mu_unlock(&s->mu);
+ } else {
+ gpr_mu_unlock(&s->mu);
+ deactivated_all_ports(s);
+ }
+}
+
+void GrpcUdpListener::OnFdAboutToOrphan() {
+ gpr_mu_lock(&mutex_);
+ grpc_unlink_if_unix_domain_socket(&addr_);
+
+ 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
- * should no longer be used. */
- GRPC_CLOSURE_INIT(&orphan_fd_closure_, shutdown_fd, this,
- grpc_schedule_on_exec_ctx);
- gpr_log(GPR_DEBUG, "fd %d about to be orphaned", fd_);
- udp_handler_->OnFdAboutToOrphan(&orphan_fd_closure_, server_->user_data);
- orphan_notified_ = true;
- }
- gpr_mu_unlock(&mutex_);
-}
-
-static int bind_socket(grpc_socket_factory* socket_factory, int sockfd,
- const grpc_resolved_address* addr) {
- return (socket_factory != nullptr)
- ? grpc_socket_factory_bind(socket_factory, sockfd, addr)
- : bind(sockfd,
- reinterpret_cast<grpc_sockaddr*>(
- const_cast<char*>(addr->addr)),
- addr->len);
-}
-
-/* Prepare a recently-created socket for listening. */
-static int prepare_socket(grpc_socket_factory* socket_factory, int fd,
- const grpc_resolved_address* addr, int rcv_buf_size,
- int snd_buf_size, bool so_reuseport) {
- grpc_resolved_address sockname_temp;
- grpc_sockaddr* addr_ptr =
- reinterpret_cast<grpc_sockaddr*>(const_cast<char*>(addr->addr));
-
- if (fd < 0) {
- goto error;
- }
-
- if (grpc_set_socket_nonblocking(fd, 1) != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Unable to set nonblocking %d: %s", fd, strerror(errno));
- goto error;
- }
- if (grpc_set_socket_cloexec(fd, 1) != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Unable to set cloexec %d: %s", fd, strerror(errno));
- goto error;
- }
-
- if (grpc_set_socket_ip_pktinfo_if_possible(fd) != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Unable to set ip_pktinfo.");
- goto error;
- } else if (addr_ptr->sa_family == AF_INET6) {
- if (grpc_set_socket_ipv6_recvpktinfo_if_possible(fd) != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Unable to set ipv6_recvpktinfo.");
- goto error;
- }
- }
-
- if (grpc_set_socket_sndbuf(fd, snd_buf_size) != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Failed to set send buffer size to %d bytes",
- snd_buf_size);
- goto error;
- }
-
- if (grpc_set_socket_rcvbuf(fd, rcv_buf_size) != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Failed to set receive buffer size to %d bytes",
- rcv_buf_size);
- goto error;
- }
-
- {
- int get_overflow = 1;
- if (0 != setsockopt(fd, SOL_SOCKET, SO_RXQ_OVFL, &get_overflow,
- sizeof(get_overflow))) {
- gpr_log(GPR_INFO, "Failed to set socket overflow support");
- }
- }
-
- if (so_reuseport && !grpc_is_unix_socket(addr) &&
- grpc_set_socket_reuse_port(fd, 1) != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Failed to set SO_REUSEPORT for fd %d", fd);
- goto error;
- }
-
- if (bind_socket(socket_factory, fd, addr) < 0) {
+ * should no longer be used. */
+ GRPC_CLOSURE_INIT(&orphan_fd_closure_, shutdown_fd, this,
+ grpc_schedule_on_exec_ctx);
+ gpr_log(GPR_DEBUG, "fd %d about to be orphaned", fd_);
+ udp_handler_->OnFdAboutToOrphan(&orphan_fd_closure_, server_->user_data);
+ orphan_notified_ = true;
+ }
+ gpr_mu_unlock(&mutex_);
+}
+
+static int bind_socket(grpc_socket_factory* socket_factory, int sockfd,
+ const grpc_resolved_address* addr) {
+ return (socket_factory != nullptr)
+ ? grpc_socket_factory_bind(socket_factory, sockfd, addr)
+ : bind(sockfd,
+ reinterpret_cast<grpc_sockaddr*>(
+ const_cast<char*>(addr->addr)),
+ addr->len);
+}
+
+/* Prepare a recently-created socket for listening. */
+static int prepare_socket(grpc_socket_factory* socket_factory, int fd,
+ const grpc_resolved_address* addr, int rcv_buf_size,
+ int snd_buf_size, bool so_reuseport) {
+ grpc_resolved_address sockname_temp;
+ grpc_sockaddr* addr_ptr =
+ reinterpret_cast<grpc_sockaddr*>(const_cast<char*>(addr->addr));
+
+ if (fd < 0) {
+ goto error;
+ }
+
+ if (grpc_set_socket_nonblocking(fd, 1) != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "Unable to set nonblocking %d: %s", fd, strerror(errno));
+ goto error;
+ }
+ if (grpc_set_socket_cloexec(fd, 1) != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "Unable to set cloexec %d: %s", fd, strerror(errno));
+ goto error;
+ }
+
+ if (grpc_set_socket_ip_pktinfo_if_possible(fd) != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "Unable to set ip_pktinfo.");
+ goto error;
+ } else if (addr_ptr->sa_family == AF_INET6) {
+ if (grpc_set_socket_ipv6_recvpktinfo_if_possible(fd) != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "Unable to set ipv6_recvpktinfo.");
+ goto error;
+ }
+ }
+
+ if (grpc_set_socket_sndbuf(fd, snd_buf_size) != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "Failed to set send buffer size to %d bytes",
+ snd_buf_size);
+ goto error;
+ }
+
+ if (grpc_set_socket_rcvbuf(fd, rcv_buf_size) != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "Failed to set receive buffer size to %d bytes",
+ rcv_buf_size);
+ goto error;
+ }
+
+ {
+ int get_overflow = 1;
+ if (0 != setsockopt(fd, SOL_SOCKET, SO_RXQ_OVFL, &get_overflow,
+ sizeof(get_overflow))) {
+ gpr_log(GPR_INFO, "Failed to set socket overflow support");
+ }
+ }
+
+ if (so_reuseport && !grpc_is_unix_socket(addr) &&
+ grpc_set_socket_reuse_port(fd, 1) != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "Failed to set SO_REUSEPORT for fd %d", fd);
+ goto error;
+ }
+
+ if (bind_socket(socket_factory, fd, addr) < 0) {
TString addr_str = grpc_sockaddr_to_string(addr, false);
gpr_log(GPR_ERROR, "bind addr=%s: %s", addr_str.c_str(), strerror(errno));
- goto error;
- }
-
- sockname_temp.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
-
- if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(sockname_temp.addr),
- &sockname_temp.len) < 0) {
- gpr_log(GPR_ERROR, "Unable to get the address socket %d is bound to: %s",
- fd, strerror(errno));
- goto error;
- }
-
- return grpc_sockaddr_get_port(&sockname_temp);
-
-error:
- if (fd >= 0) {
- close(fd);
- }
- return -1;
-}
-
-// static
-void GrpcUdpListener::do_read(void* arg, grpc_error* error) {
- GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
- GPR_ASSERT(error == GRPC_ERROR_NONE);
- /* TODO: the reason we hold server->mu here is merely to prevent fd
- * shutdown while we are reading. However, it blocks do_write(). Switch to
- * read lock if available. */
- gpr_mu_lock(sp->mutex());
- /* Tell the registered callback that data is available to read. */
- 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. */
+ goto error;
+ }
+
+ sockname_temp.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
+
+ if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(sockname_temp.addr),
+ &sockname_temp.len) < 0) {
+ gpr_log(GPR_ERROR, "Unable to get the address socket %d is bound to: %s",
+ fd, strerror(errno));
+ goto error;
+ }
+
+ return grpc_sockaddr_get_port(&sockname_temp);
+
+error:
+ if (fd >= 0) {
+ close(fd);
+ }
+ return -1;
+}
+
+// static
+void GrpcUdpListener::do_read(void* arg, grpc_error* error) {
+ GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
+ GPR_ASSERT(error == GRPC_ERROR_NONE);
+ /* TODO: the reason we hold server->mu here is merely to prevent fd
+ * shutdown while we are reading. However, it blocks do_write(). Switch to
+ * read lock if available. */
+ gpr_mu_lock(sp->mutex());
+ /* Tell the registered callback that data is available to read. */
+ 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);
- } 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
- * notification with shutdown error. */
- grpc_fd_notify_on_read(sp->emfd_, &sp->read_closure_);
- }
- gpr_mu_unlock(sp->mutex());
-}
-
-// static
-void GrpcUdpListener::on_read(void* arg, grpc_error* error) {
- GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
- sp->OnRead(error, arg);
-}
-
-void GrpcUdpListener::OnRead(grpc_error* error, void* do_read_arg) {
- if (error != GRPC_ERROR_NONE) {
- gpr_mu_lock(&server_->mu);
- if (0 == --server_->active_ports && server_->shutdown) {
- gpr_mu_unlock(&server_->mu);
- deactivated_all_ports(server_);
- } else {
- gpr_mu_unlock(&server_->mu);
- }
- return;
- }
-
- /* Read once. If there is more data to read, off load the work to another
- * thread to finish. */
- if (udp_handler_->Read()) {
- /* There maybe more packets to read. Schedule read_more_cb_ closure to run
- * after finishing this event loop. */
+ } 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
+ * notification with shutdown error. */
+ grpc_fd_notify_on_read(sp->emfd_, &sp->read_closure_);
+ }
+ gpr_mu_unlock(sp->mutex());
+}
+
+// static
+void GrpcUdpListener::on_read(void* arg, grpc_error* error) {
+ GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
+ sp->OnRead(error, arg);
+}
+
+void GrpcUdpListener::OnRead(grpc_error* error, void* do_read_arg) {
+ if (error != GRPC_ERROR_NONE) {
+ gpr_mu_lock(&server_->mu);
+ if (0 == --server_->active_ports && server_->shutdown) {
+ gpr_mu_unlock(&server_->mu);
+ deactivated_all_ports(server_);
+ } else {
+ gpr_mu_unlock(&server_->mu);
+ }
+ return;
+ }
+
+ /* Read once. If there is more data to read, off load the work to another
+ * thread to finish. */
+ 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);
- } 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
- * notification with shutdown error. */
- grpc_fd_notify_on_read(emfd_, &read_closure_);
- }
-}
-
-// static
-// Wrapper of grpc_fd_notify_on_write() with a grpc_closure callback interface.
+ } 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
+ * notification with shutdown error. */
+ grpc_fd_notify_on_read(emfd_, &read_closure_);
+ }
+}
+
+// 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*/) {
- GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
- gpr_mu_lock(sp->mutex());
- if (!sp->notify_on_write_armed_) {
- grpc_fd_notify_on_write(sp->emfd_, &sp->write_closure_);
- sp->notify_on_write_armed_ = true;
- }
- gpr_mu_unlock(sp->mutex());
-}
-
-// static
-void GrpcUdpListener::do_write(void* arg, grpc_error* error) {
- GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
- gpr_mu_lock(sp->mutex());
- if (sp->already_shutdown_) {
- // If fd has been shutdown, don't write any more and re-arm notification.
- grpc_fd_notify_on_write(sp->emfd_, &sp->write_closure_);
- } else {
- sp->notify_on_write_armed_ = false;
- /* Tell the registered callback that the socket is writeable. */
- GPR_ASSERT(error == GRPC_ERROR_NONE);
- GRPC_CLOSURE_INIT(&sp->notify_on_write_closure_, fd_notify_on_write_wrapper,
- arg, grpc_schedule_on_exec_ctx);
- sp->udp_handler_->OnCanWrite(sp->server_->user_data,
- &sp->notify_on_write_closure_);
- }
- gpr_mu_unlock(sp->mutex());
-}
-
-// static
-void GrpcUdpListener::on_write(void* arg, grpc_error* error) {
- GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
- sp->OnCanWrite(error, arg);
-}
-
-void GrpcUdpListener::OnCanWrite(grpc_error* error, void* do_write_arg) {
- if (error != GRPC_ERROR_NONE) {
- gpr_mu_lock(&server_->mu);
- if (0 == --server_->active_ports && server_->shutdown) {
- gpr_mu_unlock(&server_->mu);
- deactivated_all_ports(server_);
- } else {
- gpr_mu_unlock(&server_->mu);
- }
- return;
- }
-
- /* Schedule actual write in another thread. */
+ GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
+ gpr_mu_lock(sp->mutex());
+ if (!sp->notify_on_write_armed_) {
+ grpc_fd_notify_on_write(sp->emfd_, &sp->write_closure_);
+ sp->notify_on_write_armed_ = true;
+ }
+ gpr_mu_unlock(sp->mutex());
+}
+
+// static
+void GrpcUdpListener::do_write(void* arg, grpc_error* error) {
+ GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
+ gpr_mu_lock(sp->mutex());
+ if (sp->already_shutdown_) {
+ // If fd has been shutdown, don't write any more and re-arm notification.
+ grpc_fd_notify_on_write(sp->emfd_, &sp->write_closure_);
+ } else {
+ sp->notify_on_write_armed_ = false;
+ /* Tell the registered callback that the socket is writeable. */
+ GPR_ASSERT(error == GRPC_ERROR_NONE);
+ GRPC_CLOSURE_INIT(&sp->notify_on_write_closure_, fd_notify_on_write_wrapper,
+ arg, grpc_schedule_on_exec_ctx);
+ sp->udp_handler_->OnCanWrite(sp->server_->user_data,
+ &sp->notify_on_write_closure_);
+ }
+ gpr_mu_unlock(sp->mutex());
+}
+
+// static
+void GrpcUdpListener::on_write(void* arg, grpc_error* error) {
+ GrpcUdpListener* sp = static_cast<GrpcUdpListener*>(arg);
+ sp->OnCanWrite(error, arg);
+}
+
+void GrpcUdpListener::OnCanWrite(grpc_error* error, void* do_write_arg) {
+ if (error != GRPC_ERROR_NONE) {
+ gpr_mu_lock(&server_->mu);
+ if (0 == --server_->active_ports && server_->shutdown) {
+ gpr_mu_unlock(&server_->mu);
+ deactivated_all_ports(server_);
+ } else {
+ gpr_mu_unlock(&server_->mu);
+ }
+ return;
+ }
+
+ /* Schedule actual write in another thread. */
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);
-}
-
-static int add_socket_to_server(grpc_udp_server* s, int fd,
- const grpc_resolved_address* addr,
- int rcv_buf_size, int snd_buf_size) {
- gpr_log(GPR_DEBUG, "add socket %d to server", fd);
-
- int port = prepare_socket(s->socket_factory, fd, addr, rcv_buf_size,
- snd_buf_size, s->so_reuseport);
- if (port >= 0) {
- gpr_mu_lock(&s->mu);
- s->listeners.emplace_back(s, fd, addr);
- gpr_log(GPR_DEBUG,
- "add socket %d to server for port %d, %zu listener(s) in total", fd,
- port, s->listeners.size());
- gpr_mu_unlock(&s->mu);
- }
- return port;
-}
-
-int grpc_udp_server_add_port(grpc_udp_server* s,
- const grpc_resolved_address* addr,
- int rcv_buf_size, int snd_buf_size,
- GrpcUdpHandlerFactory* handler_factory,
- size_t num_listeners) {
- if (num_listeners > 1 && !s->so_reuseport) {
- gpr_log(GPR_ERROR,
- "Try to have multiple listeners on same port, but SO_REUSEPORT is "
- "not supported. Only create 1 listener.");
- }
+}
+
+static int add_socket_to_server(grpc_udp_server* s, int fd,
+ const grpc_resolved_address* addr,
+ int rcv_buf_size, int snd_buf_size) {
+ gpr_log(GPR_DEBUG, "add socket %d to server", fd);
+
+ int port = prepare_socket(s->socket_factory, fd, addr, rcv_buf_size,
+ snd_buf_size, s->so_reuseport);
+ if (port >= 0) {
+ gpr_mu_lock(&s->mu);
+ s->listeners.emplace_back(s, fd, addr);
+ gpr_log(GPR_DEBUG,
+ "add socket %d to server for port %d, %zu listener(s) in total", fd,
+ port, s->listeners.size());
+ gpr_mu_unlock(&s->mu);
+ }
+ return port;
+}
+
+int grpc_udp_server_add_port(grpc_udp_server* s,
+ const grpc_resolved_address* addr,
+ int rcv_buf_size, int snd_buf_size,
+ GrpcUdpHandlerFactory* handler_factory,
+ size_t num_listeners) {
+ if (num_listeners > 1 && !s->so_reuseport) {
+ gpr_log(GPR_ERROR,
+ "Try to have multiple listeners on same port, but SO_REUSEPORT is "
+ "not supported. Only create 1 listener.");
+ }
TString addr_str = grpc_sockaddr_to_string(addr, true);
gpr_log(GPR_DEBUG, "add address: %s to server", addr_str.c_str());
-
- int allocated_port1 = -1;
- int allocated_port2 = -1;
- int fd;
- grpc_dualstack_mode dsmode;
- grpc_resolved_address addr6_v4mapped;
- grpc_resolved_address wild4;
- grpc_resolved_address wild6;
- grpc_resolved_address addr4_copy;
- grpc_resolved_address* allocated_addr = nullptr;
- grpc_resolved_address sockname_temp;
- int port = 0;
-
- /* Check if this is a wildcard port, and if so, try to keep the port the same
- as some previously created listener. */
- if (grpc_sockaddr_get_port(addr) == 0) {
- /* Loop through existing listeners to find the port in use. */
- for (size_t i = 0; i < s->listeners.size(); ++i) {
- sockname_temp.len =
- static_cast<socklen_t>(sizeof(struct sockaddr_storage));
- if (0 == getsockname(s->listeners[i].fd(),
- reinterpret_cast<grpc_sockaddr*>(sockname_temp.addr),
- &sockname_temp.len)) {
- port = grpc_sockaddr_get_port(&sockname_temp);
- if (port > 0) {
- /* Found such a port, update |addr| to reflects this port. */
- allocated_addr = static_cast<grpc_resolved_address*>(
- gpr_malloc(sizeof(grpc_resolved_address)));
- memcpy(allocated_addr, addr, sizeof(grpc_resolved_address));
- grpc_sockaddr_set_port(allocated_addr, port);
- addr = allocated_addr;
- break;
- }
- }
- }
- }
-
- if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
- addr = &addr6_v4mapped;
- }
-
- s->handler_factory = handler_factory;
- for (size_t i = 0; i < num_listeners; ++i) {
- /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
- if (grpc_sockaddr_is_wildcard(addr, &port)) {
- grpc_sockaddr_make_wildcards(port, &wild4, &wild6);
-
- /* Try listening on IPv6 first. */
- addr = &wild6;
- // TODO(rjshade): Test and propagate the returned grpc_error*:
- GRPC_ERROR_UNREF(grpc_create_dualstack_socket_using_factory(
- s->socket_factory, addr, SOCK_DGRAM, IPPROTO_UDP, &dsmode, &fd));
- allocated_port1 =
- add_socket_to_server(s, fd, addr, rcv_buf_size, snd_buf_size);
- if (fd >= 0 && dsmode == GRPC_DSMODE_DUALSTACK) {
- if (port == 0) {
- /* This is the first time to bind to |addr|. If its port is still
- * wildcard port, update |addr| with the ephermeral port returned by
- * kernel. Thus |addr| can have a specific port in following
- * iterations. */
- grpc_sockaddr_set_port(addr, allocated_port1);
- port = allocated_port1;
- } else if (allocated_port1 >= 0) {
+
+ int allocated_port1 = -1;
+ int allocated_port2 = -1;
+ int fd;
+ grpc_dualstack_mode dsmode;
+ grpc_resolved_address addr6_v4mapped;
+ grpc_resolved_address wild4;
+ grpc_resolved_address wild6;
+ grpc_resolved_address addr4_copy;
+ grpc_resolved_address* allocated_addr = nullptr;
+ grpc_resolved_address sockname_temp;
+ int port = 0;
+
+ /* Check if this is a wildcard port, and if so, try to keep the port the same
+ as some previously created listener. */
+ if (grpc_sockaddr_get_port(addr) == 0) {
+ /* Loop through existing listeners to find the port in use. */
+ for (size_t i = 0; i < s->listeners.size(); ++i) {
+ sockname_temp.len =
+ static_cast<socklen_t>(sizeof(struct sockaddr_storage));
+ if (0 == getsockname(s->listeners[i].fd(),
+ reinterpret_cast<grpc_sockaddr*>(sockname_temp.addr),
+ &sockname_temp.len)) {
+ port = grpc_sockaddr_get_port(&sockname_temp);
+ if (port > 0) {
+ /* Found such a port, update |addr| to reflects this port. */
+ allocated_addr = static_cast<grpc_resolved_address*>(
+ gpr_malloc(sizeof(grpc_resolved_address)));
+ memcpy(allocated_addr, addr, sizeof(grpc_resolved_address));
+ grpc_sockaddr_set_port(allocated_addr, port);
+ addr = allocated_addr;
+ break;
+ }
+ }
+ }
+ }
+
+ if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
+ addr = &addr6_v4mapped;
+ }
+
+ s->handler_factory = handler_factory;
+ for (size_t i = 0; i < num_listeners; ++i) {
+ /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */
+ if (grpc_sockaddr_is_wildcard(addr, &port)) {
+ grpc_sockaddr_make_wildcards(port, &wild4, &wild6);
+
+ /* Try listening on IPv6 first. */
+ addr = &wild6;
+ // TODO(rjshade): Test and propagate the returned grpc_error*:
+ GRPC_ERROR_UNREF(grpc_create_dualstack_socket_using_factory(
+ s->socket_factory, addr, SOCK_DGRAM, IPPROTO_UDP, &dsmode, &fd));
+ allocated_port1 =
+ add_socket_to_server(s, fd, addr, rcv_buf_size, snd_buf_size);
+ if (fd >= 0 && dsmode == GRPC_DSMODE_DUALSTACK) {
+ if (port == 0) {
+ /* This is the first time to bind to |addr|. If its port is still
+ * wildcard port, update |addr| with the ephermeral port returned by
+ * kernel. Thus |addr| can have a specific port in following
+ * iterations. */
+ 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 first one. */
- GPR_ASSERT(port == allocated_port1);
- }
- /* A dualstack socket is created, no need to create corresponding IPV4
- * socket. */
- continue;
- }
-
- /* If we didn't get a dualstack socket, also listen on 0.0.0.0. */
- if (port == 0 && allocated_port1 > 0) {
- /* |port| hasn't been assigned to an emphemeral port yet, |wild4| must
- * have a wildcard port. Update it with the emphemeral port created
- * during binding.*/
- grpc_sockaddr_set_port(&wild4, allocated_port1);
- port = allocated_port1;
- }
- /* |wild4| should have been updated with an emphemeral port by now. Use
- * this IPV4 address to create a IPV4 socket. */
- addr = &wild4;
- }
-
- // TODO(rjshade): Test and propagate the returned grpc_error*:
- GRPC_ERROR_UNREF(grpc_create_dualstack_socket_using_factory(
- s->socket_factory, addr, SOCK_DGRAM, IPPROTO_UDP, &dsmode, &fd));
- if (fd < 0) {
- gpr_log(GPR_ERROR, "Unable to create socket: %s", strerror(errno));
- }
- if (dsmode == GRPC_DSMODE_IPV4 &&
- grpc_sockaddr_is_v4mapped(addr, &addr4_copy)) {
- addr = &addr4_copy;
- }
- allocated_port2 =
- add_socket_to_server(s, fd, addr, rcv_buf_size, snd_buf_size);
- if (port == 0) {
- /* Update |addr| with the ephermeral port returned by kernel. So |addr|
- * can have a specific port in following iterations. */
- grpc_sockaddr_set_port(addr, allocated_port2);
- port = allocated_port2;
- } else if (allocated_port2 >= 0) {
- GPR_ASSERT(port == allocated_port2);
- }
- }
-
- gpr_free(allocated_addr);
- return port;
-}
-
-int grpc_udp_server_get_fd(grpc_udp_server* s, unsigned port_index) {
- if (port_index >= s->listeners.size()) {
- return -1;
- }
-
- return s->listeners[port_index].fd();
-}
-
+ * the first one. */
+ GPR_ASSERT(port == allocated_port1);
+ }
+ /* A dualstack socket is created, no need to create corresponding IPV4
+ * socket. */
+ continue;
+ }
+
+ /* If we didn't get a dualstack socket, also listen on 0.0.0.0. */
+ if (port == 0 && allocated_port1 > 0) {
+ /* |port| hasn't been assigned to an emphemeral port yet, |wild4| must
+ * have a wildcard port. Update it with the emphemeral port created
+ * during binding.*/
+ grpc_sockaddr_set_port(&wild4, allocated_port1);
+ port = allocated_port1;
+ }
+ /* |wild4| should have been updated with an emphemeral port by now. Use
+ * this IPV4 address to create a IPV4 socket. */
+ addr = &wild4;
+ }
+
+ // TODO(rjshade): Test and propagate the returned grpc_error*:
+ GRPC_ERROR_UNREF(grpc_create_dualstack_socket_using_factory(
+ s->socket_factory, addr, SOCK_DGRAM, IPPROTO_UDP, &dsmode, &fd));
+ if (fd < 0) {
+ gpr_log(GPR_ERROR, "Unable to create socket: %s", strerror(errno));
+ }
+ if (dsmode == GRPC_DSMODE_IPV4 &&
+ grpc_sockaddr_is_v4mapped(addr, &addr4_copy)) {
+ addr = &addr4_copy;
+ }
+ allocated_port2 =
+ add_socket_to_server(s, fd, addr, rcv_buf_size, snd_buf_size);
+ if (port == 0) {
+ /* Update |addr| with the ephermeral port returned by kernel. So |addr|
+ * can have a specific port in following iterations. */
+ grpc_sockaddr_set_port(addr, allocated_port2);
+ port = allocated_port2;
+ } else if (allocated_port2 >= 0) {
+ GPR_ASSERT(port == allocated_port2);
+ }
+ }
+
+ gpr_free(allocated_addr);
+ return port;
+}
+
+int grpc_udp_server_get_fd(grpc_udp_server* s, unsigned port_index) {
+ if (port_index >= s->listeners.size()) {
+ return -1;
+ }
+
+ return s->listeners[port_index].fd();
+}
+
void grpc_udp_server_start(grpc_udp_server* udp_server,
const std::vector<grpc_pollset*>* pollsets,
void* user_data) {
- gpr_log(GPR_DEBUG, "grpc_udp_server_start");
+ gpr_log(GPR_DEBUG, "grpc_udp_server_start");
gpr_mu_lock(&udp_server->mu);
GPR_ASSERT(udp_server->active_ports == 0);
udp_server->pollsets = pollsets;
udp_server->user_data = user_data;
-
+
for (auto& listener : udp_server->listeners) {
listener.StartListening(pollsets, udp_server->handler_factory);
- }
-
+ }
+
gpr_mu_unlock(&udp_server->mu);
-}
-
+}
+
void GrpcUdpListener::StartListening(const std::vector<grpc_pollset*>* pollsets,
- GrpcUdpHandlerFactory* handler_factory) {
- gpr_mu_lock(&mutex_);
- handler_factory_ = handler_factory;
- udp_handler_ = handler_factory->CreateUdpHandler(emfd_, server_->user_data);
+ GrpcUdpHandlerFactory* handler_factory) {
+ gpr_mu_lock(&mutex_);
+ handler_factory_ = handler_factory;
+ udp_handler_ = handler_factory->CreateUdpHandler(emfd_, server_->user_data);
for (grpc_pollset* pollset : *pollsets) {
grpc_pollset_add_fd(pollset, emfd_);
- }
- GRPC_CLOSURE_INIT(&read_closure_, on_read, this, grpc_schedule_on_exec_ctx);
- grpc_fd_notify_on_read(emfd_, &read_closure_);
-
- GRPC_CLOSURE_INIT(&write_closure_, on_write, this, grpc_schedule_on_exec_ctx);
- notify_on_write_armed_ = true;
- grpc_fd_notify_on_write(emfd_, &write_closure_);
-
- /* Registered for both read and write callbacks: increment active_ports
- * twice to account for this, and delay free-ing of memory until both
- * on_read and on_write have fired. */
- server_->active_ports += 2;
- gpr_mu_unlock(&mutex_);
-}
-
-void GrpcUdpListener::OnDestroy() {
- if (udp_handler_ != nullptr) {
- handler_factory_->DestroyUdpHandler(udp_handler_);
- }
-}
-
-#endif
+ }
+ GRPC_CLOSURE_INIT(&read_closure_, on_read, this, grpc_schedule_on_exec_ctx);
+ grpc_fd_notify_on_read(emfd_, &read_closure_);
+
+ GRPC_CLOSURE_INIT(&write_closure_, on_write, this, grpc_schedule_on_exec_ctx);
+ notify_on_write_armed_ = true;
+ grpc_fd_notify_on_write(emfd_, &write_closure_);
+
+ /* Registered for both read and write callbacks: increment active_ports
+ * twice to account for this, and delay free-ing of memory until both
+ * on_read and on_write have fired. */
+ server_->active_ports += 2;
+ gpr_mu_unlock(&mutex_);
+}
+
+void GrpcUdpListener::OnDestroy() {
+ if (udp_handler_ != nullptr) {
+ handler_factory_->DestroyUdpHandler(udp_handler_);
+ }
+}
+
+#endif
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 6cda332a5bb..046d3bf4dd3 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_UDP_SERVER_H
#define GRPC_CORE_LIB_IOMGR_UDP_SERVER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <vector>
#include "src/core/lib/iomgr/endpoint.h"
@@ -34,71 +34,71 @@ struct grpc_server;
/* Forward decl of grpc_udp_server */
typedef struct grpc_udp_server grpc_udp_server;
-/* An interface associated with a socket. udp server delivers I/O event on that
- * socket to the subclass of this interface which is created through
- * GrpcUdpHandlerFactory.
- * Its implementation should do the real IO work, e.g. read packet and write. */
-class GrpcUdpHandler {
- public:
+/* An interface associated with a socket. udp server delivers I/O event on that
+ * socket to the subclass of this interface which is created through
+ * GrpcUdpHandlerFactory.
+ * Its implementation should do the real IO work, e.g. read packet and write. */
+class GrpcUdpHandler {
+ public:
GrpcUdpHandler(grpc_fd* /* emfd */, void* /* user_data */) {}
- virtual ~GrpcUdpHandler() {}
+ virtual ~GrpcUdpHandler() {}
- // Interfaces to be implemented by subclasses to do the actual setup/tear down
- // or I/O.
+ // Interfaces to be implemented by subclasses to do the actual setup/tear down
+ // or I/O.
- // Called when data is available to read from the socket. Returns true if
- // there is more data to read after this call.
+ // 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;
- // 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,
+ // 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;
- // 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,
+ // 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;
-};
-
-class GrpcUdpHandlerFactory {
- public:
- virtual ~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. */
+};
+
+class GrpcUdpHandlerFactory {
+ public:
+ virtual ~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;
-};
-
+};
+
/* Create a server, initially not bound to any ports */
-grpc_udp_server* grpc_udp_server_create(const grpc_channel_args* args);
+grpc_udp_server* grpc_udp_server_create(const grpc_channel_args* args);
-/* Start listening to bound ports. user_data is passed to callbacks. */
+/* Start listening to bound ports. user_data is passed to callbacks. */
void grpc_udp_server_start(grpc_udp_server* udp_server,
const std::vector<grpc_pollset*>* pollsets,
void* user_data);
-int grpc_udp_server_get_fd(grpc_udp_server* s, unsigned port_index);
+int grpc_udp_server_get_fd(grpc_udp_server* s, unsigned port_index);
/* Add a port to the server, returning port number on success, or negative
on failure.
- Create |num_listeners| sockets for given address to listen on using
- SO_REUSEPORT if supported.
-
+ Create |num_listeners| sockets for given address to listen on using
+ SO_REUSEPORT if supported.
+
The :: and 0.0.0.0 wildcard addresses are treated identically, accepting
- both IPv4 and IPv6 connections, but :: is the preferred style. This usually
- creates |num_listeners| sockets, but possibly 2 * |num_listeners| on systems
- which support IPv6, but not dualstack sockets. */
+ both IPv4 and IPv6 connections, but :: is the preferred style. This usually
+ creates |num_listeners| sockets, but possibly 2 * |num_listeners| on systems
+ which support IPv6, but not dualstack sockets. */
/* TODO(ctiller): deprecate this, and make grpc_udp_server_add_ports to handle
all of the multiple socket port matching logic in one place */
-int grpc_udp_server_add_port(grpc_udp_server* s,
- const grpc_resolved_address* addr,
- int rcv_buf_size, int snd_buf_size,
- GrpcUdpHandlerFactory* handler_factory,
- size_t num_listeners);
+int grpc_udp_server_add_port(grpc_udp_server* s,
+ const grpc_resolved_address* addr,
+ int rcv_buf_size, int snd_buf_size,
+ GrpcUdpHandlerFactory* handler_factory,
+ size_t num_listeners);
-void grpc_udp_server_destroy(grpc_udp_server* server, grpc_closure* on_done);
+void grpc_udp_server_destroy(grpc_udp_server* server, grpc_closure* on_done);
#endif /* GRPC_CORE_LIB_IOMGR_UDP_SERVER_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.cc
index fd26673b38f..a2f973c4879 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.cc
@@ -1,99 +1,99 @@
-/*
- *
- * 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"
-
-#ifdef GRPC_HAVE_UNIX_SOCKET
-
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/un.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"
+
+#ifdef GRPC_HAVE_UNIX_SOCKET
+
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/un.h>
+
#include "y_absl/strings/str_cat.h"
-#include "src/core/lib/iomgr/unix_sockets_posix.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-void grpc_create_socketpair_if_unix(int sv[2]) {
- GPR_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
-}
-
-grpc_error* grpc_resolve_unix_domain_address(const char* name,
- grpc_resolved_addresses** addrs) {
- struct sockaddr_un* un;
- if (strlen(name) >
- GPR_ARRAY_SIZE(((struct sockaddr_un*)nullptr)->sun_path) - 1) {
+#include "src/core/lib/iomgr/unix_sockets_posix.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+void grpc_create_socketpair_if_unix(int sv[2]) {
+ GPR_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
+}
+
+grpc_error* grpc_resolve_unix_domain_address(const char* name,
+ grpc_resolved_addresses** addrs) {
+ struct sockaddr_un* un;
+ if (strlen(name) >
+ GPR_ARRAY_SIZE(((struct sockaddr_un*)nullptr)->sun_path) - 1) {
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Path name should not have more than ",
GPR_ARRAY_SIZE(un->sun_path) - 1, " characters")
.c_str());
- }
- *addrs = static_cast<grpc_resolved_addresses*>(
- gpr_malloc(sizeof(grpc_resolved_addresses)));
- (*addrs)->naddrs = 1;
- (*addrs)->addrs = static_cast<grpc_resolved_address*>(
- gpr_malloc(sizeof(grpc_resolved_address)));
- un = reinterpret_cast<struct sockaddr_un*>((*addrs)->addrs->addr);
- un->sun_family = AF_UNIX;
- strncpy(un->sun_path, name, sizeof(un->sun_path));
- (*addrs)->addrs->len =
- static_cast<socklen_t>(strlen(un->sun_path) + sizeof(un->sun_family) + 1);
- return GRPC_ERROR_NONE;
-}
-
-int grpc_is_unix_socket(const grpc_resolved_address* resolved_addr) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- return addr->sa_family == AF_UNIX;
-}
-
-void grpc_unlink_if_unix_domain_socket(
- const grpc_resolved_address* resolved_addr) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- if (addr->sa_family != AF_UNIX) {
- return;
- }
- struct sockaddr_un* un = reinterpret_cast<struct sockaddr_un*>(
- const_cast<char*>(resolved_addr->addr));
- struct stat st;
-
- if (stat(un->sun_path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFSOCK) {
- unlink(un->sun_path);
- }
-}
-
+ }
+ *addrs = static_cast<grpc_resolved_addresses*>(
+ gpr_malloc(sizeof(grpc_resolved_addresses)));
+ (*addrs)->naddrs = 1;
+ (*addrs)->addrs = static_cast<grpc_resolved_address*>(
+ gpr_malloc(sizeof(grpc_resolved_address)));
+ un = reinterpret_cast<struct sockaddr_un*>((*addrs)->addrs->addr);
+ un->sun_family = AF_UNIX;
+ strncpy(un->sun_path, name, sizeof(un->sun_path));
+ (*addrs)->addrs->len =
+ static_cast<socklen_t>(strlen(un->sun_path) + sizeof(un->sun_family) + 1);
+ return GRPC_ERROR_NONE;
+}
+
+int grpc_is_unix_socket(const grpc_resolved_address* resolved_addr) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ return addr->sa_family == AF_UNIX;
+}
+
+void grpc_unlink_if_unix_domain_socket(
+ const grpc_resolved_address* resolved_addr) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ if (addr->sa_family != AF_UNIX) {
+ return;
+ }
+ struct sockaddr_un* un = reinterpret_cast<struct sockaddr_un*>(
+ const_cast<char*>(resolved_addr->addr));
+ struct stat st;
+
+ if (stat(un->sun_path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFSOCK) {
+ unlink(un->sun_path);
+ }
+}
+
TString grpc_sockaddr_to_uri_unix_if_possible(
- const grpc_resolved_address* resolved_addr) {
- const grpc_sockaddr* addr =
- reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
- if (addr->sa_family != AF_UNIX) {
+ const grpc_resolved_address* resolved_addr) {
+ const grpc_sockaddr* addr =
+ reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
+ if (addr->sa_family != AF_UNIX) {
return "";
- }
+ }
return y_absl::StrCat("unix:", ((struct sockaddr_un*)addr)->sun_path);
-}
-
-#endif
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.h
index 962adde71cd..bdf9a7fee98 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_UNIX_SOCKETS_POSIX_H
#define GRPC_CORE_LIB_IOMGR_UNIX_SOCKETS_POSIX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include "src/core/lib/iomgr/port.h"
@@ -31,15 +31,15 @@
void grpc_create_socketpair_if_unix(int sv[2]);
-grpc_error* grpc_resolve_unix_domain_address(
- const char* name, grpc_resolved_addresses** addresses);
+grpc_error* grpc_resolve_unix_domain_address(
+ const char* name, grpc_resolved_addresses** addresses);
-int grpc_is_unix_socket(const grpc_resolved_address* resolved_addr);
+int grpc_is_unix_socket(const grpc_resolved_address* resolved_addr);
void grpc_unlink_if_unix_domain_socket(
- const grpc_resolved_address* resolved_addr);
+ const grpc_resolved_address* resolved_addr);
TString grpc_sockaddr_to_uri_unix_if_possible(
- const grpc_resolved_address* resolved_addr);
+ const grpc_resolved_address* resolved_addr);
#endif /* GRPC_CORE_LIB_IOMGR_UNIX_SOCKETS_POSIX_H */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix_noop.cc b/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix_noop.cc
index e391914ab5c..e8f55d8cf45 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix_noop.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/unix_sockets_posix_noop.cc
@@ -1,52 +1,52 @@
-/*
- *
- * 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/unix_sockets_posix.h"
-
-#ifndef GRPC_HAVE_UNIX_SOCKET
-
+/*
+ *
+ * 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/unix_sockets_posix.h"
+
+#ifndef GRPC_HAVE_UNIX_SOCKET
+
#include <util/generic/string.h>
-#include <grpc/support/log.h>
-
-void grpc_create_socketpair_if_unix(int sv[2]) {
- // TODO: Either implement this for the non-Unix socket case or make
- // sure that it is never called in any such case. Until then, leave an
- // assertion to notify if this gets called inadvertently
- GPR_ASSERT(0);
-}
-
-grpc_error* grpc_resolve_unix_domain_address(
- const char* name, grpc_resolved_addresses** addresses) {
- *addresses = NULL;
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Unix domain sockets are not supported on Windows");
-}
-
-int grpc_is_unix_socket(const grpc_resolved_address* addr) { return false; }
-
-void grpc_unlink_if_unix_domain_socket(const grpc_resolved_address* addr) {}
-
+#include <grpc/support/log.h>
+
+void grpc_create_socketpair_if_unix(int sv[2]) {
+ // TODO: Either implement this for the non-Unix socket case or make
+ // sure that it is never called in any such case. Until then, leave an
+ // assertion to notify if this gets called inadvertently
+ GPR_ASSERT(0);
+}
+
+grpc_error* grpc_resolve_unix_domain_address(
+ const char* name, grpc_resolved_addresses** addresses) {
+ *addresses = NULL;
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Unix domain sockets are not supported on Windows");
+}
+
+int grpc_is_unix_socket(const grpc_resolved_address* addr) { return false; }
+
+void grpc_unlink_if_unix_domain_socket(const grpc_resolved_address* addr) {}
+
TString grpc_sockaddr_to_uri_unix_if_possible(
const grpc_resolved_address* addr) {
return "";
-}
-
-#endif
+}
+
+#endif
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc
index d68c9ada1f2..d7bbdf945b1 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_LINUX_EVENTFD
-
-#include <errno.h>
-#include <sys/eventfd.h>
-#include <unistd.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-#include "src/core/lib/profiling/timers.h"
-
-static grpc_error* eventfd_create(grpc_wakeup_fd* fd_info) {
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_LINUX_EVENTFD
+
+#include <errno.h>
+#include <sys/eventfd.h>
+#include <unistd.h>
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+#include "src/core/lib/profiling/timers.h"
+
+static grpc_error* eventfd_create(grpc_wakeup_fd* fd_info) {
fd_info->read_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
fd_info->write_fd = -1;
if (fd_info->read_fd < 0) {
- return GRPC_OS_ERROR(errno, "eventfd");
- }
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* eventfd_consume(grpc_wakeup_fd* fd_info) {
- eventfd_t value;
- int err;
- do {
- err = eventfd_read(fd_info->read_fd, &value);
- } while (err < 0 && errno == EINTR);
- if (err < 0 && errno != EAGAIN) {
- return GRPC_OS_ERROR(errno, "eventfd_read");
- }
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* eventfd_wakeup(grpc_wakeup_fd* fd_info) {
- GPR_TIMER_SCOPE("eventfd_wakeup", 0);
- int err;
- do {
- err = eventfd_write(fd_info->read_fd, 1);
- } while (err < 0 && errno == EINTR);
- if (err < 0) {
- return GRPC_OS_ERROR(errno, "eventfd_write");
- }
- return GRPC_ERROR_NONE;
-}
-
-static void eventfd_destroy(grpc_wakeup_fd* fd_info) {
- if (fd_info->read_fd != 0) close(fd_info->read_fd);
-}
-
-static int eventfd_check_availability(void) {
- const int efd = eventfd(0, 0);
- const int is_available = efd >= 0;
- if (is_available) close(efd);
- return is_available;
-}
-
-const grpc_wakeup_fd_vtable grpc_specialized_wakeup_fd_vtable = {
- eventfd_create, eventfd_consume, eventfd_wakeup, eventfd_destroy,
- eventfd_check_availability};
-
-#endif /* GRPC_LINUX_EVENTFD */
+ return GRPC_OS_ERROR(errno, "eventfd");
+ }
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* eventfd_consume(grpc_wakeup_fd* fd_info) {
+ eventfd_t value;
+ int err;
+ do {
+ err = eventfd_read(fd_info->read_fd, &value);
+ } while (err < 0 && errno == EINTR);
+ if (err < 0 && errno != EAGAIN) {
+ return GRPC_OS_ERROR(errno, "eventfd_read");
+ }
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* eventfd_wakeup(grpc_wakeup_fd* fd_info) {
+ GPR_TIMER_SCOPE("eventfd_wakeup", 0);
+ int err;
+ do {
+ err = eventfd_write(fd_info->read_fd, 1);
+ } while (err < 0 && errno == EINTR);
+ if (err < 0) {
+ return GRPC_OS_ERROR(errno, "eventfd_write");
+ }
+ return GRPC_ERROR_NONE;
+}
+
+static void eventfd_destroy(grpc_wakeup_fd* fd_info) {
+ if (fd_info->read_fd != 0) close(fd_info->read_fd);
+}
+
+static int eventfd_check_availability(void) {
+ const int efd = eventfd(0, 0);
+ const int is_available = efd >= 0;
+ if (is_available) close(efd);
+ return is_available;
+}
+
+const grpc_wakeup_fd_vtable grpc_specialized_wakeup_fd_vtable = {
+ eventfd_create, eventfd_consume, eventfd_wakeup, eventfd_destroy,
+ eventfd_check_availability};
+
+#endif /* GRPC_LINUX_EVENTFD */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_nospecial.cc b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_nospecial.cc
index 64778929f00..9aa286cab6e 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_nospecial.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_nospecial.cc
@@ -1,38 +1,38 @@
-/*
- *
- * 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.
- *
- */
-
-/*
- * This is a dummy file to provide an invalid specialized_wakeup_fd_vtable on
- * systems without anything better than pipe.
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_POSIX_NO_SPECIAL_WAKEUP_FD
-
-#include <stddef.h>
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-
-static int check_availability_invalid(void) { return 0; }
-
-const grpc_wakeup_fd_vtable grpc_specialized_wakeup_fd_vtable = {
- nullptr, nullptr, nullptr, nullptr, check_availability_invalid};
-
-#endif /* GRPC_POSIX_NO_SPECIAL_WAKEUP_FD */
+/*
+ *
+ * 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.
+ *
+ */
+
+/*
+ * This is a dummy file to provide an invalid specialized_wakeup_fd_vtable on
+ * systems without anything better than pipe.
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/iomgr/port.h"
+
+#ifdef GRPC_POSIX_NO_SPECIAL_WAKEUP_FD
+
+#include <stddef.h>
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+
+static int check_availability_invalid(void) { return 0; }
+
+const grpc_wakeup_fd_vtable grpc_specialized_wakeup_fd_vtable = {
+ nullptr, nullptr, nullptr, nullptr, check_availability_invalid};
+
+#endif /* GRPC_POSIX_NO_SPECIAL_WAKEUP_FD */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.cc b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.cc
index cb173903a93..546b42e49c8 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.cc
+++ b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.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>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_POSIX_WAKEUP_FD
-
-#include "src/core/lib/iomgr/wakeup_fd_pipe.h"
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-
-#include <errno.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/socket_utils_posix.h"
-
-static grpc_error* pipe_init(grpc_wakeup_fd* fd_info) {
- int pipefd[2];
- int r = pipe(pipefd);
- if (0 != r) {
- gpr_log(GPR_ERROR, "pipe creation failed (%d): %s", errno, strerror(errno));
- return GRPC_OS_ERROR(errno, "pipe");
- }
- grpc_error* err;
- err = grpc_set_socket_nonblocking(pipefd[0], 1);
- if (err != GRPC_ERROR_NONE) return err;
- err = grpc_set_socket_nonblocking(pipefd[1], 1);
- if (err != GRPC_ERROR_NONE) return err;
- fd_info->read_fd = pipefd[0];
- fd_info->write_fd = pipefd[1];
- return GRPC_ERROR_NONE;
-}
-
-static grpc_error* pipe_consume(grpc_wakeup_fd* fd_info) {
- char buf[128];
- ssize_t r;
-
- for (;;) {
- r = read(fd_info->read_fd, buf, sizeof(buf));
- if (r > 0) continue;
- if (r == 0) return GRPC_ERROR_NONE;
- switch (errno) {
- case EAGAIN:
- return GRPC_ERROR_NONE;
- case EINTR:
- continue;
- default:
- return GRPC_OS_ERROR(errno, "read");
- }
- }
-}
-
-static grpc_error* pipe_wakeup(grpc_wakeup_fd* fd_info) {
- char c = 0;
- while (write(fd_info->write_fd, &c, 1) != 1 && errno == EINTR)
- ;
- return GRPC_ERROR_NONE;
-}
-
-static void pipe_destroy(grpc_wakeup_fd* fd_info) {
- if (fd_info->read_fd != 0) close(fd_info->read_fd);
- if (fd_info->write_fd != 0) close(fd_info->write_fd);
-}
-
-static int pipe_check_availability(void) {
- grpc_wakeup_fd fd;
- fd.read_fd = fd.write_fd = -1;
-
- if (pipe_init(&fd) == GRPC_ERROR_NONE) {
- pipe_destroy(&fd);
- return 1;
- } else {
- return 0;
- }
-}
-
-const grpc_wakeup_fd_vtable grpc_pipe_wakeup_fd_vtable = {
- pipe_init, pipe_consume, pipe_wakeup, pipe_destroy,
- pipe_check_availability};
-
-#endif /* GPR_POSIX_WAKUP_FD */
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_POSIX_WAKEUP_FD
+
+#include "src/core/lib/iomgr/wakeup_fd_pipe.h"
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/socket_utils_posix.h"
+
+static grpc_error* pipe_init(grpc_wakeup_fd* fd_info) {
+ int pipefd[2];
+ int r = pipe(pipefd);
+ if (0 != r) {
+ gpr_log(GPR_ERROR, "pipe creation failed (%d): %s", errno, strerror(errno));
+ return GRPC_OS_ERROR(errno, "pipe");
+ }
+ grpc_error* err;
+ err = grpc_set_socket_nonblocking(pipefd[0], 1);
+ if (err != GRPC_ERROR_NONE) return err;
+ err = grpc_set_socket_nonblocking(pipefd[1], 1);
+ if (err != GRPC_ERROR_NONE) return err;
+ fd_info->read_fd = pipefd[0];
+ fd_info->write_fd = pipefd[1];
+ return GRPC_ERROR_NONE;
+}
+
+static grpc_error* pipe_consume(grpc_wakeup_fd* fd_info) {
+ char buf[128];
+ ssize_t r;
+
+ for (;;) {
+ r = read(fd_info->read_fd, buf, sizeof(buf));
+ if (r > 0) continue;
+ if (r == 0) return GRPC_ERROR_NONE;
+ switch (errno) {
+ case EAGAIN:
+ return GRPC_ERROR_NONE;
+ case EINTR:
+ continue;
+ default:
+ return GRPC_OS_ERROR(errno, "read");
+ }
+ }
+}
+
+static grpc_error* pipe_wakeup(grpc_wakeup_fd* fd_info) {
+ char c = 0;
+ while (write(fd_info->write_fd, &c, 1) != 1 && errno == EINTR)
+ ;
+ return GRPC_ERROR_NONE;
+}
+
+static void pipe_destroy(grpc_wakeup_fd* fd_info) {
+ if (fd_info->read_fd != 0) close(fd_info->read_fd);
+ if (fd_info->write_fd != 0) close(fd_info->write_fd);
+}
+
+static int pipe_check_availability(void) {
+ grpc_wakeup_fd fd;
+ fd.read_fd = fd.write_fd = -1;
+
+ if (pipe_init(&fd) == GRPC_ERROR_NONE) {
+ pipe_destroy(&fd);
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+const grpc_wakeup_fd_vtable grpc_pipe_wakeup_fd_vtable = {
+ pipe_init, pipe_consume, pipe_wakeup, pipe_destroy,
+ pipe_check_availability};
+
+#endif /* GPR_POSIX_WAKUP_FD */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.h b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.h
index 17569763059..34ef599f53c 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_pipe.h
@@ -1,28 +1,28 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_WAKEUP_FD_PIPE_H
#define GRPC_CORE_LIB_IOMGR_WAKEUP_FD_PIPE_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-extern const grpc_wakeup_fd_vtable grpc_pipe_wakeup_fd_vtable;
+extern const grpc_wakeup_fd_vtable grpc_pipe_wakeup_fd_vtable;
#endif /* GRPC_CORE_LIB_IOMGR_WAKEUP_FD_PIPE_H */
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 3b66d6f34de..37638c4b53b 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/iomgr/port.h"
-
-#ifdef GRPC_POSIX_WAKEUP_FD
-
-#include <stddef.h>
-#include "src/core/lib/iomgr/wakeup_fd_pipe.h"
-#include "src/core/lib/iomgr/wakeup_fd_posix.h"
-
-static const grpc_wakeup_fd_vtable* wakeup_fd_vtable = nullptr;
-
-int grpc_allow_specialized_wakeup_fd = 1;
-int grpc_allow_pipe_wakeup_fd = 1;
-
-int has_real_wakeup_fd = 1;
-int cv_wakeup_fds_enabled = 0;
-
-void grpc_wakeup_fd_global_init(void) {
- if (grpc_allow_specialized_wakeup_fd &&
- grpc_specialized_wakeup_fd_vtable.check_availability()) {
- wakeup_fd_vtable = &grpc_specialized_wakeup_fd_vtable;
- } else if (grpc_allow_pipe_wakeup_fd &&
- grpc_pipe_wakeup_fd_vtable.check_availability()) {
- wakeup_fd_vtable = &grpc_pipe_wakeup_fd_vtable;
- } else {
- has_real_wakeup_fd = 0;
- }
-}
-
-void grpc_wakeup_fd_global_destroy(void) { wakeup_fd_vtable = nullptr; }
-
-int grpc_has_wakeup_fd(void) { return has_real_wakeup_fd; }
-
-grpc_error* grpc_wakeup_fd_init(grpc_wakeup_fd* fd_info) {
- return wakeup_fd_vtable->init(fd_info);
-}
-
-grpc_error* grpc_wakeup_fd_consume_wakeup(grpc_wakeup_fd* fd_info) {
- return wakeup_fd_vtable->consume(fd_info);
-}
-
-grpc_error* grpc_wakeup_fd_wakeup(grpc_wakeup_fd* fd_info) {
- return wakeup_fd_vtable->wakeup(fd_info);
-}
-
-void grpc_wakeup_fd_destroy(grpc_wakeup_fd* fd_info) {
+/*
+ *
+ * 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/iomgr/port.h"
+
+#ifdef GRPC_POSIX_WAKEUP_FD
+
+#include <stddef.h>
+#include "src/core/lib/iomgr/wakeup_fd_pipe.h"
+#include "src/core/lib/iomgr/wakeup_fd_posix.h"
+
+static const grpc_wakeup_fd_vtable* wakeup_fd_vtable = nullptr;
+
+int grpc_allow_specialized_wakeup_fd = 1;
+int grpc_allow_pipe_wakeup_fd = 1;
+
+int has_real_wakeup_fd = 1;
+int cv_wakeup_fds_enabled = 0;
+
+void grpc_wakeup_fd_global_init(void) {
+ if (grpc_allow_specialized_wakeup_fd &&
+ grpc_specialized_wakeup_fd_vtable.check_availability()) {
+ wakeup_fd_vtable = &grpc_specialized_wakeup_fd_vtable;
+ } else if (grpc_allow_pipe_wakeup_fd &&
+ grpc_pipe_wakeup_fd_vtable.check_availability()) {
+ wakeup_fd_vtable = &grpc_pipe_wakeup_fd_vtable;
+ } else {
+ has_real_wakeup_fd = 0;
+ }
+}
+
+void grpc_wakeup_fd_global_destroy(void) { wakeup_fd_vtable = nullptr; }
+
+int grpc_has_wakeup_fd(void) { return has_real_wakeup_fd; }
+
+grpc_error* grpc_wakeup_fd_init(grpc_wakeup_fd* fd_info) {
+ return wakeup_fd_vtable->init(fd_info);
+}
+
+grpc_error* grpc_wakeup_fd_consume_wakeup(grpc_wakeup_fd* fd_info) {
+ return wakeup_fd_vtable->consume(fd_info);
+}
+
+grpc_error* grpc_wakeup_fd_wakeup(grpc_wakeup_fd* fd_info) {
+ return wakeup_fd_vtable->wakeup(fd_info);
+}
+
+void grpc_wakeup_fd_destroy(grpc_wakeup_fd* fd_info) {
wakeup_fd_vtable->destroy(fd_info);
-}
-
-#endif /* GRPC_POSIX_WAKEUP_FD */
+}
+
+#endif /* GRPC_POSIX_WAKEUP_FD */
diff --git a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.h
index 670c319593b..998e198a943 100644
--- a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.h
+++ b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_posix.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -31,7 +31,7 @@
*
* Setup:
* 1. Before calling anything, call global_init() at least once.
- * 1. Call grpc_wakeup_fd_init() to set up a wakeup_fd.
+ * 1. Call grpc_wakeup_fd_init() to set up a wakeup_fd.
* 2. Add the result of GRPC_WAKEUP_FD_FD to the set of monitored file
* descriptors for the poll() style API you are using. Monitor the file
* descriptor for readability.
@@ -47,8 +47,8 @@
#ifndef GRPC_CORE_LIB_IOMGR_WAKEUP_FD_POSIX_H
#define GRPC_CORE_LIB_IOMGR_WAKEUP_FD_POSIX_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/error.h"
void grpc_wakeup_fd_global_init(void);
diff --git a/contrib/libs/grpc/src/core/lib/json/json.h b/contrib/libs/grpc/src/core/lib/json/json.h
index f426fbf1dde..c73d37a181d 100644
--- a/contrib/libs/grpc/src/core/lib/json/json.h
+++ b/contrib/libs/grpc/src/core/lib/json/json.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_JSON_JSON_H
#define GRPC_CORE_LIB_JSON_JSON_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdlib.h>
#include <map>
@@ -33,7 +33,7 @@
#include "src/core/lib/iomgr/error.h"
namespace grpc_core {
-
+
// A JSON value, which can be any one of object, array, string,
// number, true, false, or null.
class Json {
@@ -67,14 +67,14 @@ class Json {
CopyFrom(other);
return *this;
}
-
+
// Moveable.
Json(Json&& other) { MoveFrom(std::move(other)); }
Json& operator=(Json&& other) {
MoveFrom(std::move(other));
return *this;
}
-
+
// Construct from copying a string.
// If is_number is true, the type will be NUMBER instead of STRING.
Json(const TString& string, bool is_number = false)
diff --git a/contrib/libs/grpc/src/core/lib/json/json_reader.cc b/contrib/libs/grpc/src/core/lib/json/json_reader.cc
index e251cb78824..a4cf6dbbd72 100644
--- a/contrib/libs/grpc/src/core/lib/json/json_reader.cc
+++ b/contrib/libs/grpc/src/core/lib/json/json_reader.cc
@@ -1,34 +1,34 @@
-/*
- *
- * 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <string.h>
-
+/*
+ *
+ * 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/support/log.h>
-
+#include <grpc/support/log.h>
+
#include "src/core/lib/json/json.h"
-
+
#define GRPC_JSON_MAX_DEPTH 255
#define GRPC_JSON_MAX_ERRORS 16
@@ -107,7 +107,7 @@ class JsonReader {
void SetTrue();
void SetFalse();
void SetNull();
-
+
const uint8_t* original_input_;
const uint8_t* input_;
size_t remaining_input_;
@@ -129,8 +129,8 @@ class JsonReader {
void JsonReader::StringAddChar(uint32_t c) {
string_.push_back(static_cast<uint8_t>(c));
-}
-
+}
+
void JsonReader::StringAddUtf32(uint32_t c) {
if (c <= 0x7f) {
StringAddChar(c);
@@ -156,8 +156,8 @@ void JsonReader::StringAddUtf32(uint32_t c) {
StringAddChar(b3);
StringAddChar(b4);
}
-}
-
+}
+
uint32_t JsonReader::ReadChar() {
if (remaining_input_ == 0) return GRPC_JSON_READ_CHAR_EOF;
const uint32_t r = *input_++;
@@ -167,8 +167,8 @@ uint32_t JsonReader::ReadChar() {
return GRPC_JSON_READ_CHAR_EOF;
}
return r;
-}
-
+}
+
Json* JsonReader::CreateAndLinkValue() {
Json* value;
if (stack_.empty()) {
@@ -222,45 +222,45 @@ bool JsonReader::StartContainer(Json::Type type) {
void JsonReader::EndContainer() {
GPR_ASSERT(!stack_.empty());
stack_.pop_back();
-}
-
+}
+
void JsonReader::SetKey() {
key_ = std::move(string_);
string_.clear();
-}
-
+}
+
void JsonReader::SetString() {
Json* value = CreateAndLinkValue();
*value = std::move(string_);
string_.clear();
-}
-
+}
+
bool JsonReader::SetNumber() {
Json* value = CreateAndLinkValue();
*value = Json(string_, /*is_number=*/true);
string_.clear();
return true;
-}
-
+}
+
void JsonReader::SetTrue() {
Json* value = CreateAndLinkValue();
*value = true;
string_.clear();
-}
-
+}
+
void JsonReader::SetFalse() {
Json* value = CreateAndLinkValue();
*value = false;
string_.clear();
-}
-
+}
+
void JsonReader::SetNull() { CreateAndLinkValue(); }
-
+
bool JsonReader::IsComplete() {
return (stack_.empty() && (state_ == State::GRPC_JSON_STATE_END ||
state_ == State::GRPC_JSON_STATE_VALUE_END));
-}
-
+}
+
/* Call this function to start parsing the input. It will return the following:
* . GRPC_JSON_DONE if the input got eof, and the parsing finished
* successfully.
@@ -270,33 +270,33 @@ bool JsonReader::IsComplete() {
*/
JsonReader::Status JsonReader::Run() {
uint32_t c;
-
- /* This state-machine is a strict implementation of ECMA-404 */
+
+ /* This state-machine is a strict implementation of ECMA-404 */
while (true) {
c = ReadChar();
- switch (c) {
+ switch (c) {
/* Let's process the error case first. */
- case GRPC_JSON_READ_CHAR_EOF:
+ case GRPC_JSON_READ_CHAR_EOF:
if (IsComplete()) {
return Status::GRPC_JSON_DONE;
- } else {
+ } else {
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
- /* Processing whitespaces. */
- case ' ':
- case '\t':
- case '\n':
- case '\r':
+ }
+ break;
+
+ /* Processing whitespaces. */
+ case ' ':
+ case '\t':
+ case '\n':
+ case '\r':
switch (state_) {
case State::GRPC_JSON_STATE_OBJECT_KEY_BEGIN:
case State::GRPC_JSON_STATE_OBJECT_KEY_END:
case State::GRPC_JSON_STATE_VALUE_BEGIN:
case State::GRPC_JSON_STATE_VALUE_END:
case State::GRPC_JSON_STATE_END:
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_OBJECT_KEY_STRING:
case State::GRPC_JSON_STATE_VALUE_STRING:
if (c != ' ') return Status::GRPC_JSON_PARSE_ERROR;
@@ -304,34 +304,34 @@ JsonReader::Status JsonReader::Run() {
return Status::GRPC_JSON_PARSE_ERROR;
}
StringAddChar(c);
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER:
case State::GRPC_JSON_STATE_VALUE_NUMBER_WITH_DECIMAL:
case State::GRPC_JSON_STATE_VALUE_NUMBER_ZERO:
case State::GRPC_JSON_STATE_VALUE_NUMBER_EPM:
if (!SetNumber()) return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_END;
- break;
-
- default:
+ break;
+
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
- /* Value, object or array terminations. */
- case ',':
- case '}':
- case ']':
+ }
+ break;
+
+ /* Value, object or array terminations. */
+ case ',':
+ case '}':
+ case ']':
switch (state_) {
case State::GRPC_JSON_STATE_OBJECT_KEY_STRING:
case State::GRPC_JSON_STATE_VALUE_STRING:
if (unicode_high_surrogate_ != 0) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
StringAddChar(c);
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER:
case State::GRPC_JSON_STATE_VALUE_NUMBER_WITH_DECIMAL:
case State::GRPC_JSON_STATE_VALUE_NUMBER_ZERO:
@@ -344,43 +344,43 @@ JsonReader::Status JsonReader::Run() {
return Status::GRPC_JSON_PARSE_ERROR;
} else if (c == ']' && stack_.back()->type() != Json::Type::ARRAY) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
if (!SetNumber()) return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_END;
- /* The missing break here is intentional. */
- /* fallthrough */
-
+ /* The missing break here is intentional. */
+ /* fallthrough */
+
case State::GRPC_JSON_STATE_VALUE_END:
case State::GRPC_JSON_STATE_OBJECT_KEY_BEGIN:
case State::GRPC_JSON_STATE_VALUE_BEGIN:
- if (c == ',') {
+ if (c == ',') {
if (state_ != State::GRPC_JSON_STATE_VALUE_END) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
if (!stack_.empty() &&
stack_.back()->type() == Json::Type::OBJECT) {
state_ = State::GRPC_JSON_STATE_OBJECT_KEY_BEGIN;
} else if (!stack_.empty() &&
stack_.back()->type() == Json::Type::ARRAY) {
state_ = State::GRPC_JSON_STATE_VALUE_BEGIN;
- } else {
+ } else {
return Status::GRPC_JSON_PARSE_ERROR;
- }
- } else {
+ }
+ } else {
if (stack_.empty()) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
if (c == '}' && stack_.back()->type() != Json::Type::OBJECT) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
if (c == '}' &&
state_ == State::GRPC_JSON_STATE_OBJECT_KEY_BEGIN &&
!container_just_begun_) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
if (c == ']' && stack_.back()->type() != Json::Type::ARRAY) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
if (c == ']' && state_ == State::GRPC_JSON_STATE_VALUE_BEGIN &&
!container_just_begun_) {
return Status::GRPC_JSON_PARSE_ERROR;
@@ -390,432 +390,432 @@ JsonReader::Status JsonReader::Run() {
if (stack_.empty()) {
state_ = State::GRPC_JSON_STATE_END;
}
- }
- break;
-
- default:
+ }
+ break;
+
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
- /* In-string escaping. */
- case '\\':
+ }
+ break;
+
+ /* In-string escaping. */
+ case '\\':
switch (state_) {
case State::GRPC_JSON_STATE_OBJECT_KEY_STRING:
escaped_string_was_key_ = true;
state_ = State::GRPC_JSON_STATE_STRING_ESCAPE;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_STRING:
escaped_string_was_key_ = false;
state_ = State::GRPC_JSON_STATE_STRING_ESCAPE;
- break;
-
- /* This is the \\ case. */
+ break;
+
+ /* This is the \\ case. */
case State::GRPC_JSON_STATE_STRING_ESCAPE:
if (unicode_high_surrogate_ != 0)
return Status::GRPC_JSON_PARSE_ERROR;
StringAddChar('\\');
if (escaped_string_was_key_) {
state_ = State::GRPC_JSON_STATE_OBJECT_KEY_STRING;
- } else {
+ } else {
state_ = State::GRPC_JSON_STATE_VALUE_STRING;
- }
- break;
-
- default:
+ }
+ break;
+
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
- default:
+ }
+ break;
+
+ default:
container_just_begun_ = false;
switch (state_) {
case State::GRPC_JSON_STATE_OBJECT_KEY_BEGIN:
if (c != '"') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_OBJECT_KEY_STRING;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_OBJECT_KEY_STRING:
if (unicode_high_surrogate_ != 0) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
- if (c == '"') {
+ }
+ if (c == '"') {
state_ = State::GRPC_JSON_STATE_OBJECT_KEY_END;
SetKey();
- } else {
+ } else {
if (c < 32) return Status::GRPC_JSON_PARSE_ERROR;
StringAddChar(c);
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_VALUE_STRING:
if (unicode_high_surrogate_ != 0) {
return Status::GRPC_JSON_PARSE_ERROR;
- }
- if (c == '"') {
+ }
+ if (c == '"') {
state_ = State::GRPC_JSON_STATE_VALUE_END;
SetString();
- } else {
+ } else {
if (c < 32) return Status::GRPC_JSON_PARSE_ERROR;
StringAddChar(c);
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_OBJECT_KEY_END:
if (c != ':') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_BEGIN;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_BEGIN:
- switch (c) {
- case 't':
+ switch (c) {
+ case 't':
state_ = State::GRPC_JSON_STATE_VALUE_TRUE_R;
- break;
-
- case 'f':
+ break;
+
+ case 'f':
state_ = State::GRPC_JSON_STATE_VALUE_FALSE_A;
- break;
-
- case 'n':
+ break;
+
+ case 'n':
state_ = State::GRPC_JSON_STATE_VALUE_NULL_U;
- break;
-
- case '"':
+ break;
+
+ case '"':
state_ = State::GRPC_JSON_STATE_VALUE_STRING;
- break;
-
- case '0':
+ break;
+
+ case '0':
StringAddChar(c);
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER_ZERO;
- break;
-
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '-':
+ break;
+
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '-':
StringAddChar(c);
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER;
- break;
-
- case '{':
+ break;
+
+ case '{':
container_just_begun_ = true;
if (!StartContainer(Json::Type::OBJECT)) {
return Status::GRPC_JSON_PARSE_ERROR;
}
state_ = State::GRPC_JSON_STATE_OBJECT_KEY_BEGIN;
- break;
-
- case '[':
+ break;
+
+ case '[':
container_just_begun_ = true;
if (!StartContainer(Json::Type::ARRAY)) {
return Status::GRPC_JSON_PARSE_ERROR;
}
- break;
- default:
+ break;
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_STRING_ESCAPE:
if (escaped_string_was_key_) {
state_ = State::GRPC_JSON_STATE_OBJECT_KEY_STRING;
- } else {
+ } else {
state_ = State::GRPC_JSON_STATE_VALUE_STRING;
- }
+ }
if (unicode_high_surrogate_ && c != 'u') {
return Status::GRPC_JSON_PARSE_ERROR;
- }
- switch (c) {
- case '"':
- case '/':
+ }
+ switch (c) {
+ case '"':
+ case '/':
StringAddChar(c);
- break;
- case 'b':
+ break;
+ case 'b':
StringAddChar('\b');
- break;
- case 'f':
+ break;
+ case 'f':
StringAddChar('\f');
- break;
- case 'n':
+ break;
+ case 'n':
StringAddChar('\n');
- break;
- case 'r':
+ break;
+ case 'r':
StringAddChar('\r');
- break;
- case 't':
+ break;
+ case 't':
StringAddChar('\t');
- break;
- case 'u':
+ break;
+ case 'u':
state_ = State::GRPC_JSON_STATE_STRING_ESCAPE_U1;
unicode_char_ = 0;
- break;
- default:
+ break;
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_STRING_ESCAPE_U1:
case State::GRPC_JSON_STATE_STRING_ESCAPE_U2:
case State::GRPC_JSON_STATE_STRING_ESCAPE_U3:
case State::GRPC_JSON_STATE_STRING_ESCAPE_U4:
- if ((c >= '0') && (c <= '9')) {
- c -= '0';
- } else if ((c >= 'A') && (c <= 'F')) {
- c -= 'A' - 10;
- } else if ((c >= 'a') && (c <= 'f')) {
- c -= 'a' - 10;
- } else {
+ if ((c >= '0') && (c <= '9')) {
+ c -= '0';
+ } else if ((c >= 'A') && (c <= 'F')) {
+ c -= 'A' - 10;
+ } else if ((c >= 'a') && (c <= 'f')) {
+ c -= 'a' - 10;
+ } else {
return Status::GRPC_JSON_PARSE_ERROR;
- }
+ }
unicode_char_ = static_cast<uint16_t>(unicode_char_ << 4);
unicode_char_ = static_cast<uint16_t>(unicode_char_ | c);
-
+
switch (state_) {
case State::GRPC_JSON_STATE_STRING_ESCAPE_U1:
state_ = State::GRPC_JSON_STATE_STRING_ESCAPE_U2;
- break;
+ break;
case State::GRPC_JSON_STATE_STRING_ESCAPE_U2:
state_ = State::GRPC_JSON_STATE_STRING_ESCAPE_U3;
- break;
+ break;
case State::GRPC_JSON_STATE_STRING_ESCAPE_U3:
state_ = State::GRPC_JSON_STATE_STRING_ESCAPE_U4;
- break;
+ break;
case State::GRPC_JSON_STATE_STRING_ESCAPE_U4:
- /* See grpc_json_writer_escape_string to have a description
- * of what's going on here.
- */
+ /* See grpc_json_writer_escape_string to have a description
+ * of what's going on here.
+ */
if ((unicode_char_ & 0xfc00) == 0xd800) {
- /* high surrogate utf-16 */
+ /* high surrogate utf-16 */
if (unicode_high_surrogate_ != 0)
return Status::GRPC_JSON_PARSE_ERROR;
unicode_high_surrogate_ = unicode_char_;
} else if ((unicode_char_ & 0xfc00) == 0xdc00) {
- /* low surrogate utf-16 */
- uint32_t utf32;
+ /* low surrogate utf-16 */
+ uint32_t utf32;
if (unicode_high_surrogate_ == 0)
return Status::GRPC_JSON_PARSE_ERROR;
- utf32 = 0x10000;
- utf32 += static_cast<uint32_t>(
+ utf32 = 0x10000;
+ utf32 += static_cast<uint32_t>(
(unicode_high_surrogate_ - 0xd800) * 0x400);
utf32 += static_cast<uint32_t>(unicode_char_ - 0xdc00);
StringAddUtf32(utf32);
unicode_high_surrogate_ = 0;
- } else {
- /* anything else */
+ } else {
+ /* anything else */
if (unicode_high_surrogate_ != 0)
return Status::GRPC_JSON_PARSE_ERROR;
StringAddUtf32(unicode_char_);
- }
+ }
if (escaped_string_was_key_) {
state_ = State::GRPC_JSON_STATE_OBJECT_KEY_STRING;
- } else {
+ } else {
state_ = State::GRPC_JSON_STATE_VALUE_STRING;
- }
- break;
- default:
+ }
+ break;
+ default:
GPR_UNREACHABLE_CODE(return Status::GRPC_JSON_INTERNAL_ERROR);
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER:
StringAddChar(c);
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- break;
- case 'e':
- case 'E':
+ switch (c) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ break;
+ case 'e':
+ case 'E':
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER_E;
- break;
- case '.':
+ break;
+ case '.':
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER_DOT;
- break;
- default:
+ break;
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER_WITH_DECIMAL:
StringAddChar(c);
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- break;
- case 'e':
- case 'E':
+ switch (c) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ break;
+ case 'e':
+ case 'E':
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER_E;
- break;
- default:
+ break;
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER_ZERO:
if (c != '.') return Status::GRPC_JSON_PARSE_ERROR;
StringAddChar(c);
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER_DOT;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER_DOT:
StringAddChar(c);
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
+ switch (c) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER_WITH_DECIMAL;
- break;
- default:
+ break;
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER_E:
StringAddChar(c);
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '+':
- case '-':
+ switch (c) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '+':
+ case '-':
state_ = State::GRPC_JSON_STATE_VALUE_NUMBER_EPM;
- break;
- default:
+ break;
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NUMBER_EPM:
StringAddChar(c);
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- break;
- default:
+ switch (c) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ break;
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_VALUE_TRUE_R:
if (c != 'r') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_TRUE_U;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_TRUE_U:
if (c != 'u') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_TRUE_E;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_TRUE_E:
if (c != 'e') return Status::GRPC_JSON_PARSE_ERROR;
SetTrue();
state_ = State::GRPC_JSON_STATE_VALUE_END;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_FALSE_A:
if (c != 'a') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_FALSE_L;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_FALSE_L:
if (c != 'l') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_FALSE_S;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_FALSE_S:
if (c != 's') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_FALSE_E;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_FALSE_E:
if (c != 'e') return Status::GRPC_JSON_PARSE_ERROR;
SetFalse();
state_ = State::GRPC_JSON_STATE_VALUE_END;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NULL_U:
if (c != 'u') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_NULL_L1;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NULL_L1:
if (c != 'l') return Status::GRPC_JSON_PARSE_ERROR;
state_ = State::GRPC_JSON_STATE_VALUE_NULL_L2;
- break;
-
+ break;
+
case State::GRPC_JSON_STATE_VALUE_NULL_L2:
if (c != 'l') return Status::GRPC_JSON_PARSE_ERROR;
SetNull();
state_ = State::GRPC_JSON_STATE_VALUE_END;
- break;
-
- /* All of the VALUE_END cases are handled in the specialized case
- * above. */
+ break;
+
+ /* All of the VALUE_END cases are handled in the specialized case
+ * above. */
case State::GRPC_JSON_STATE_VALUE_END:
- switch (c) {
- case ',':
- case '}':
- case ']':
+ switch (c) {
+ case ',':
+ case '}':
+ case ']':
GPR_UNREACHABLE_CODE(return Status::GRPC_JSON_INTERNAL_ERROR);
- break;
-
- default:
+ break;
+
+ default:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- break;
-
+ }
+ break;
+
case State::GRPC_JSON_STATE_END:
return Status::GRPC_JSON_PARSE_ERROR;
- }
- }
- }
-
+ }
+ }
+ }
+
GPR_UNREACHABLE_CODE(return Status::GRPC_JSON_INTERNAL_ERROR);
-}
+}
grpc_error* JsonReader::Parse(y_absl::string_view input, Json* output) {
JsonReader reader(input);
diff --git a/contrib/libs/grpc/src/core/lib/json/json_writer.cc b/contrib/libs/grpc/src/core/lib/json/json_writer.cc
index f2043d55a05..4048387e988 100644
--- a/contrib/libs/grpc/src/core/lib/json/json_writer.cc
+++ b/contrib/libs/grpc/src/core/lib/json/json_writer.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 <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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
#include <stdlib.h>
-#include <string.h>
-
+#include <string.h>
+
#include "y_absl/strings/string_view.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-
+
#include "src/core/lib/json/json.h"
namespace grpc_core {
@@ -85,109 +85,109 @@ void JsonWriter::OutputCheck(size_t needed) {
/* Round up by 256 bytes. */
needed = (needed + 0xff) & ~0xffU;
output_.reserve(output_.capacity() + needed);
-}
-
+}
+
void JsonWriter::OutputChar(char c) {
OutputCheck(1);
output_.push_back(c);
-}
-
+}
+
void JsonWriter::OutputString(const y_absl::string_view str) {
OutputCheck(str.size());
output_.append(str.data(), str.size());
-}
-
+}
+
void JsonWriter::OutputIndent() {
- static const char spacesstr[] =
- " "
- " "
- " "
- " ";
+ static const char spacesstr[] =
+ " "
+ " "
+ " "
+ " ";
unsigned spaces = static_cast<unsigned>(depth_ * indent_);
if (indent_ == 0) return;
if (got_key_) {
OutputChar(' ');
- return;
- }
- while (spaces >= (sizeof(spacesstr) - 1)) {
+ return;
+ }
+ while (spaces >= (sizeof(spacesstr) - 1)) {
OutputString(y_absl::string_view(spacesstr, sizeof(spacesstr) - 1));
- spaces -= static_cast<unsigned>(sizeof(spacesstr) - 1);
- }
- if (spaces == 0) return;
+ spaces -= static_cast<unsigned>(sizeof(spacesstr) - 1);
+ }
+ if (spaces == 0) return;
OutputString(
y_absl::string_view(spacesstr + sizeof(spacesstr) - 1 - spaces, spaces));
-}
-
+}
+
void JsonWriter::ValueEnd() {
if (container_empty_) {
container_empty_ = false;
if (indent_ == 0 || depth_ == 0) return;
OutputChar('\n');
- } else {
+ } else {
OutputChar(',');
if (indent_ == 0) return;
OutputChar('\n');
- }
-}
-
+ }
+}
+
void JsonWriter::EscapeUtf16(uint16_t utf16) {
- static const char hex[] = "0123456789abcdef";
+ static const char hex[] = "0123456789abcdef";
OutputString(y_absl::string_view("\\u", 2));
OutputChar(hex[(utf16 >> 12) & 0x0f]);
OutputChar(hex[(utf16 >> 8) & 0x0f]);
OutputChar(hex[(utf16 >> 4) & 0x0f]);
OutputChar(hex[(utf16)&0x0f]);
-}
-
+}
+
void JsonWriter::EscapeString(const TString& string) {
OutputChar('"');
for (size_t idx = 0; idx < string.size(); ++idx) {
uint8_t c = static_cast<uint8_t>(string[idx]);
- if (c == 0) {
- break;
+ if (c == 0) {
+ break;
} else if (c >= 32 && c <= 126) {
if (c == '\\' || c == '"') OutputChar('\\');
OutputChar(static_cast<char>(c));
} else if (c < 32 || c == 127) {
- switch (c) {
- case '\b':
+ switch (c) {
+ case '\b':
OutputString(y_absl::string_view("\\b", 2));
- break;
- case '\f':
+ break;
+ case '\f':
OutputString(y_absl::string_view("\\f", 2));
- break;
- case '\n':
+ break;
+ case '\n':
OutputString(y_absl::string_view("\\n", 2));
- break;
- case '\r':
+ break;
+ case '\r':
OutputString(y_absl::string_view("\\r", 2));
- break;
- case '\t':
+ break;
+ case '\t':
OutputString(y_absl::string_view("\\t", 2));
- break;
- default:
+ break;
+ default:
EscapeUtf16(c);
- break;
- }
- } else {
- uint32_t utf32 = 0;
- int extra = 0;
- int i;
- int valid = 1;
- if ((c & 0xe0) == 0xc0) {
- utf32 = c & 0x1f;
- extra = 1;
- } else if ((c & 0xf0) == 0xe0) {
- utf32 = c & 0x0f;
- extra = 2;
- } else if ((c & 0xf8) == 0xf0) {
- utf32 = c & 0x07;
- extra = 3;
- } else {
- break;
- }
- for (i = 0; i < extra; i++) {
- utf32 <<= 6;
+ break;
+ }
+ } else {
+ uint32_t utf32 = 0;
+ int extra = 0;
+ int i;
+ int valid = 1;
+ if ((c & 0xe0) == 0xc0) {
+ utf32 = c & 0x1f;
+ extra = 1;
+ } else if ((c & 0xf0) == 0xe0) {
+ utf32 = c & 0x0f;
+ extra = 2;
+ } else if ((c & 0xf8) == 0xf0) {
+ utf32 = c & 0x07;
+ extra = 3;
+ } else {
+ break;
+ }
+ for (i = 0; i < extra; i++) {
+ utf32 <<= 6;
++idx;
/* Breaks out and bail if we hit the end of the string. */
if (idx == string.size()) {
@@ -195,48 +195,48 @@ void JsonWriter::EscapeString(const TString& string) {
break;
}
c = static_cast<uint8_t>(string[idx]);
- /* Breaks out and bail on any invalid UTF-8 sequence, including \0. */
- if ((c & 0xc0) != 0x80) {
- valid = 0;
- break;
- }
- utf32 |= c & 0x3f;
- }
- if (!valid) break;
- /* The range 0xd800 - 0xdfff is reserved by the surrogates ad vitam.
- * Any other range is technically reserved for future usage, so if we
- * don't want the software to break in the future, we have to allow
- * anything else. The first non-unicode character is 0x110000. */
- if (((utf32 >= 0xd800) && (utf32 <= 0xdfff)) || (utf32 >= 0x110000))
- break;
- if (utf32 >= 0x10000) {
- /* If utf32 contains a character that is above 0xffff, it needs to be
- * broken down into a utf-16 surrogate pair. A surrogate pair is first
- * a high surrogate, followed by a low surrogate. Each surrogate holds
- * 10 bits of usable data, thus allowing a total of 20 bits of data.
- * The high surrogate marker is 0xd800, while the low surrogate marker
- * is 0xdc00. The low 10 bits of each will be the usable data.
- *
- * After re-combining the 20 bits of data, one has to add 0x10000 to
- * the resulting value, in order to obtain the original character.
- * This is obviously because the range 0x0000 - 0xffff can be written
- * without any special trick.
- *
- * Since 0x10ffff is the highest allowed character, we're working in
- * the range 0x00000 - 0xfffff after we decrement it by 0x10000.
- * That range is exactly 20 bits.
- */
- utf32 -= 0x10000;
+ /* Breaks out and bail on any invalid UTF-8 sequence, including \0. */
+ if ((c & 0xc0) != 0x80) {
+ valid = 0;
+ break;
+ }
+ utf32 |= c & 0x3f;
+ }
+ if (!valid) break;
+ /* The range 0xd800 - 0xdfff is reserved by the surrogates ad vitam.
+ * Any other range is technically reserved for future usage, so if we
+ * don't want the software to break in the future, we have to allow
+ * anything else. The first non-unicode character is 0x110000. */
+ if (((utf32 >= 0xd800) && (utf32 <= 0xdfff)) || (utf32 >= 0x110000))
+ break;
+ if (utf32 >= 0x10000) {
+ /* If utf32 contains a character that is above 0xffff, it needs to be
+ * broken down into a utf-16 surrogate pair. A surrogate pair is first
+ * a high surrogate, followed by a low surrogate. Each surrogate holds
+ * 10 bits of usable data, thus allowing a total of 20 bits of data.
+ * The high surrogate marker is 0xd800, while the low surrogate marker
+ * is 0xdc00. The low 10 bits of each will be the usable data.
+ *
+ * After re-combining the 20 bits of data, one has to add 0x10000 to
+ * the resulting value, in order to obtain the original character.
+ * This is obviously because the range 0x0000 - 0xffff can be written
+ * without any special trick.
+ *
+ * Since 0x10ffff is the highest allowed character, we're working in
+ * the range 0x00000 - 0xfffff after we decrement it by 0x10000.
+ * That range is exactly 20 bits.
+ */
+ utf32 -= 0x10000;
EscapeUtf16(static_cast<uint16_t>(0xd800 | (utf32 >> 10)));
EscapeUtf16(static_cast<uint16_t>(0xdc00 | (utf32 & 0x3ff)));
- } else {
+ } else {
EscapeUtf16(static_cast<uint16_t>(utf32));
- }
- }
- }
+ }
+ }
+ }
OutputChar('"');
}
-
+
void JsonWriter::ContainerBegins(Json::Type type) {
if (!got_key_) ValueEnd();
OutputIndent();
@@ -244,8 +244,8 @@ void JsonWriter::ContainerBegins(Json::Type type) {
container_empty_ = true;
got_key_ = false;
depth_++;
-}
-
+}
+
void JsonWriter::ContainerEnds(Json::Type type) {
if (indent_ && !container_empty_) OutputChar('\n');
depth_--;
@@ -253,30 +253,30 @@ void JsonWriter::ContainerEnds(Json::Type type) {
OutputChar(type == Json::Type::OBJECT ? '}' : ']');
container_empty_ = false;
got_key_ = false;
-}
-
+}
+
void JsonWriter::ObjectKey(const TString& string) {
ValueEnd();
OutputIndent();
EscapeString(string);
OutputChar(':');
got_key_ = true;
-}
-
+}
+
void JsonWriter::ValueRaw(const TString& string) {
if (!got_key_) ValueEnd();
OutputIndent();
OutputString(string);
got_key_ = false;
-}
-
+}
+
void JsonWriter::ValueString(const TString& string) {
if (!got_key_) ValueEnd();
OutputIndent();
EscapeString(string);
got_key_ = false;
-}
-
+}
+
void JsonWriter::DumpObject(const Json::Object& object) {
ContainerBegins(Json::Type::OBJECT);
for (const auto& p : object) {
@@ -284,15 +284,15 @@ void JsonWriter::DumpObject(const Json::Object& object) {
DumpValue(p.second);
}
ContainerEnds(Json::Type::OBJECT);
-}
-
+}
+
void JsonWriter::DumpArray(const Json::Array& array) {
ContainerBegins(Json::Type::ARRAY);
for (const auto& v : array) {
DumpValue(v);
}
ContainerEnds(Json::Type::ARRAY);
-}
+}
void JsonWriter::DumpValue(const Json& value) {
switch (value.type()) {
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 2056940f3a6..ccd8c6962f2 100644
--- a/contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc
+++ b/contrib/libs/grpc/src/core/lib/profiling/basic_timers.cc
@@ -1,293 +1,293 @@
-/*
- *
- * 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/profiling/timers.h"
-
-#ifdef GRPC_BASIC_PROFILER
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-#include <inttypes.h>
-#include <pthread.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/lib/profiling/timers.h"
+
+#ifdef GRPC_BASIC_PROFILER
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <string.h>
+
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/profiling/timers.h"
-
-typedef enum { BEGIN = '{', END = '}', MARK = '.' } marker_type;
-
-typedef struct gpr_timer_entry {
- gpr_timespec tm;
- const char* tagstr;
- const char* file;
- short line;
- char type;
- uint8_t important;
- int thd;
-} gpr_timer_entry;
-
-#define MAX_COUNT 1000000
-
-typedef struct gpr_timer_log {
- size_t num_entries;
- struct gpr_timer_log* next;
- struct gpr_timer_log* prev;
- gpr_timer_entry log[MAX_COUNT];
-} gpr_timer_log;
-
-typedef struct gpr_timer_log_list {
- gpr_timer_log* head;
- /* valid iff head!=NULL */
- gpr_timer_log* tail;
-} gpr_timer_log_list;
-
-static __thread gpr_timer_log* g_thread_log;
-static gpr_once g_once_init = GPR_ONCE_INIT;
-static FILE* output_file;
-static const char* output_filename_or_null = NULL;
-static pthread_mutex_t g_mu;
-static pthread_cond_t g_cv;
-static gpr_timer_log_list g_in_progress_logs;
-static gpr_timer_log_list g_done_logs;
-static int g_shutdown;
-static pthread_t g_writing_thread;
-static __thread int g_thread_id;
-static int g_next_thread_id;
-static int g_writing_enabled = 1;
-
+
+typedef enum { BEGIN = '{', END = '}', MARK = '.' } marker_type;
+
+typedef struct gpr_timer_entry {
+ gpr_timespec tm;
+ const char* tagstr;
+ const char* file;
+ short line;
+ char type;
+ uint8_t important;
+ int thd;
+} gpr_timer_entry;
+
+#define MAX_COUNT 1000000
+
+typedef struct gpr_timer_log {
+ size_t num_entries;
+ struct gpr_timer_log* next;
+ struct gpr_timer_log* prev;
+ gpr_timer_entry log[MAX_COUNT];
+} gpr_timer_log;
+
+typedef struct gpr_timer_log_list {
+ gpr_timer_log* head;
+ /* valid iff head!=NULL */
+ gpr_timer_log* tail;
+} gpr_timer_log_list;
+
+static __thread gpr_timer_log* g_thread_log;
+static gpr_once g_once_init = GPR_ONCE_INIT;
+static FILE* output_file;
+static const char* output_filename_or_null = NULL;
+static pthread_mutex_t g_mu;
+static pthread_cond_t g_cv;
+static gpr_timer_log_list g_in_progress_logs;
+static gpr_timer_log_list g_done_logs;
+static int g_shutdown;
+static pthread_t g_writing_thread;
+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")
-static const char* output_filename() {
- if (output_filename_or_null == NULL) {
+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 {
- output_filename_or_null = "latency_trace.txt";
- }
- }
- return output_filename_or_null;
-}
-
-static int timer_log_push_back(gpr_timer_log_list* list, gpr_timer_log* log) {
- if (list->head == NULL) {
- list->head = list->tail = log;
- log->next = log->prev = NULL;
- return 1;
- } else {
- log->prev = list->tail;
- log->next = NULL;
- list->tail->next = log;
- list->tail = log;
- return 0;
- }
-}
-
-static gpr_timer_log* timer_log_pop_front(gpr_timer_log_list* list) {
- gpr_timer_log* out = list->head;
- if (out != NULL) {
- list->head = out->next;
- if (list->head != NULL) {
- list->head->prev = NULL;
- } else {
- list->tail = NULL;
- }
- }
- return out;
-}
-
-static void timer_log_remove(gpr_timer_log_list* list, gpr_timer_log* log) {
- if (log->prev == NULL) {
- list->head = log->next;
- if (list->head != NULL) {
- list->head->prev = NULL;
- }
- } else {
- log->prev->next = log->next;
- }
- if (log->next == NULL) {
- list->tail = log->prev;
- if (list->tail != NULL) {
- list->tail->next = NULL;
- }
- } else {
- log->next->prev = log->prev;
- }
-}
-
-static void write_log(gpr_timer_log* log) {
- size_t i;
- if (output_file == NULL) {
- output_file = fopen(output_filename(), "w");
- }
- for (i = 0; i < log->num_entries; i++) {
- gpr_timer_entry* entry = &(log->log[i]);
- if (gpr_time_cmp(entry->tm, gpr_time_0(entry->tm.clock_type)) < 0) {
- entry->tm = gpr_time_0(entry->tm.clock_type);
- }
- fprintf(output_file,
- "{\"t\": %" PRId64
- ".%09d, \"thd\": \"%d\", \"type\": \"%c\", \"tag\": "
- "\"%s\", \"file\": \"%s\", \"line\": %d, \"imp\": %d}\n",
- entry->tm.tv_sec, entry->tm.tv_nsec, entry->thd, entry->type,
- entry->tagstr, entry->file, entry->line, entry->important);
- }
-}
-
-static void* writing_thread(void* unused) {
- gpr_timer_log* log;
- pthread_mutex_lock(&g_mu);
- for (;;) {
- while ((log = timer_log_pop_front(&g_done_logs)) == NULL && !g_shutdown) {
- pthread_cond_wait(&g_cv, &g_mu);
- }
- if (log != NULL) {
- pthread_mutex_unlock(&g_mu);
- write_log(log);
- free(log);
- pthread_mutex_lock(&g_mu);
- }
- if (g_shutdown) {
- pthread_mutex_unlock(&g_mu);
- return NULL;
- }
- }
-}
-
-static void flush_logs(gpr_timer_log_list* list) {
- gpr_timer_log* log;
- while ((log = timer_log_pop_front(list)) != NULL) {
- write_log(log);
- free(log);
- }
-}
-
-static void finish_writing(void) {
- pthread_mutex_lock(&g_mu);
- g_shutdown = 1;
- pthread_cond_signal(&g_cv);
- pthread_mutex_unlock(&g_mu);
- pthread_join(g_writing_thread, NULL);
-
- gpr_log(GPR_INFO, "flushing logs");
-
- pthread_mutex_lock(&g_mu);
- flush_logs(&g_done_logs);
- flush_logs(&g_in_progress_logs);
- pthread_mutex_unlock(&g_mu);
-
- if (output_file) {
- fclose(output_file);
- }
-}
-
-void gpr_timers_set_log_filename(const char* filename) {
- output_filename_or_null = filename;
-}
-
-static void init_output() {
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
- pthread_create(&g_writing_thread, &attr, &writing_thread, NULL);
- pthread_attr_destroy(&attr);
-
- atexit(finish_writing);
-}
-
-static void rotate_log() {
- /* Using malloc here, as this code could end up being called by gpr_malloc */
- gpr_timer_log* log = static_cast<gpr_timer_log*>(malloc(sizeof(*log)));
- gpr_once_init(&g_once_init, init_output);
- log->num_entries = 0;
- pthread_mutex_lock(&g_mu);
- if (g_thread_log != NULL) {
- timer_log_remove(&g_in_progress_logs, g_thread_log);
- if (timer_log_push_back(&g_done_logs, g_thread_log)) {
- pthread_cond_signal(&g_cv);
- }
- } else {
- g_thread_id = g_next_thread_id++;
- }
- timer_log_push_back(&g_in_progress_logs, log);
- pthread_mutex_unlock(&g_mu);
- g_thread_log = log;
-}
-
-static void gpr_timers_log_add(const char* tagstr, marker_type type,
- int important, const char* file, int line) {
- gpr_timer_entry* entry;
-
- if (!g_writing_enabled) {
- return;
- }
-
- if (g_thread_log == NULL || g_thread_log->num_entries == MAX_COUNT) {
- rotate_log();
- }
-
- entry = &g_thread_log->log[g_thread_log->num_entries++];
-
- entry->tm = gpr_now(GPR_CLOCK_PRECISE);
- entry->tagstr = tagstr;
- entry->type = type;
- entry->file = file;
- entry->line = (short)line;
- entry->important = important != 0;
- entry->thd = g_thread_id;
-}
-
-/* Latency profiler API implementation. */
-void gpr_timer_add_mark(const char* tagstr, int important, const char* file,
- int line) {
- gpr_timers_log_add(tagstr, MARK, important, file, line);
-}
-
-void gpr_timer_begin(const char* tagstr, int important, const char* file,
- int line) {
- gpr_timers_log_add(tagstr, BEGIN, important, file, line);
-}
-
-void gpr_timer_end(const char* tagstr, int important, const char* file,
- int line) {
- gpr_timers_log_add(tagstr, END, important, file, line);
-}
-
-void gpr_timer_set_enabled(int enabled) { g_writing_enabled = enabled; }
-
-/* Basic profiler specific API functions. */
-void gpr_timers_global_init(void) {}
-
-void gpr_timers_global_destroy(void) {}
-
-#else /* !GRPC_BASIC_PROFILER */
-void gpr_timers_global_init(void) {}
-
-void gpr_timers_global_destroy(void) {}
-
+ output_filename_or_null = "latency_trace.txt";
+ }
+ }
+ return output_filename_or_null;
+}
+
+static int timer_log_push_back(gpr_timer_log_list* list, gpr_timer_log* log) {
+ if (list->head == NULL) {
+ list->head = list->tail = log;
+ log->next = log->prev = NULL;
+ return 1;
+ } else {
+ log->prev = list->tail;
+ log->next = NULL;
+ list->tail->next = log;
+ list->tail = log;
+ return 0;
+ }
+}
+
+static gpr_timer_log* timer_log_pop_front(gpr_timer_log_list* list) {
+ gpr_timer_log* out = list->head;
+ if (out != NULL) {
+ list->head = out->next;
+ if (list->head != NULL) {
+ list->head->prev = NULL;
+ } else {
+ list->tail = NULL;
+ }
+ }
+ return out;
+}
+
+static void timer_log_remove(gpr_timer_log_list* list, gpr_timer_log* log) {
+ if (log->prev == NULL) {
+ list->head = log->next;
+ if (list->head != NULL) {
+ list->head->prev = NULL;
+ }
+ } else {
+ log->prev->next = log->next;
+ }
+ if (log->next == NULL) {
+ list->tail = log->prev;
+ if (list->tail != NULL) {
+ list->tail->next = NULL;
+ }
+ } else {
+ log->next->prev = log->prev;
+ }
+}
+
+static void write_log(gpr_timer_log* log) {
+ size_t i;
+ if (output_file == NULL) {
+ output_file = fopen(output_filename(), "w");
+ }
+ for (i = 0; i < log->num_entries; i++) {
+ gpr_timer_entry* entry = &(log->log[i]);
+ if (gpr_time_cmp(entry->tm, gpr_time_0(entry->tm.clock_type)) < 0) {
+ entry->tm = gpr_time_0(entry->tm.clock_type);
+ }
+ fprintf(output_file,
+ "{\"t\": %" PRId64
+ ".%09d, \"thd\": \"%d\", \"type\": \"%c\", \"tag\": "
+ "\"%s\", \"file\": \"%s\", \"line\": %d, \"imp\": %d}\n",
+ entry->tm.tv_sec, entry->tm.tv_nsec, entry->thd, entry->type,
+ entry->tagstr, entry->file, entry->line, entry->important);
+ }
+}
+
+static void* writing_thread(void* unused) {
+ gpr_timer_log* log;
+ pthread_mutex_lock(&g_mu);
+ for (;;) {
+ while ((log = timer_log_pop_front(&g_done_logs)) == NULL && !g_shutdown) {
+ pthread_cond_wait(&g_cv, &g_mu);
+ }
+ if (log != NULL) {
+ pthread_mutex_unlock(&g_mu);
+ write_log(log);
+ free(log);
+ pthread_mutex_lock(&g_mu);
+ }
+ if (g_shutdown) {
+ pthread_mutex_unlock(&g_mu);
+ return NULL;
+ }
+ }
+}
+
+static void flush_logs(gpr_timer_log_list* list) {
+ gpr_timer_log* log;
+ while ((log = timer_log_pop_front(list)) != NULL) {
+ write_log(log);
+ free(log);
+ }
+}
+
+static void finish_writing(void) {
+ pthread_mutex_lock(&g_mu);
+ g_shutdown = 1;
+ pthread_cond_signal(&g_cv);
+ pthread_mutex_unlock(&g_mu);
+ pthread_join(g_writing_thread, NULL);
+
+ gpr_log(GPR_INFO, "flushing logs");
+
+ pthread_mutex_lock(&g_mu);
+ flush_logs(&g_done_logs);
+ flush_logs(&g_in_progress_logs);
+ pthread_mutex_unlock(&g_mu);
+
+ if (output_file) {
+ fclose(output_file);
+ }
+}
+
+void gpr_timers_set_log_filename(const char* filename) {
+ output_filename_or_null = filename;
+}
+
+static void init_output() {
+ pthread_attr_t attr;
+ pthread_attr_init(&attr);
+ pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
+ pthread_create(&g_writing_thread, &attr, &writing_thread, NULL);
+ pthread_attr_destroy(&attr);
+
+ atexit(finish_writing);
+}
+
+static void rotate_log() {
+ /* Using malloc here, as this code could end up being called by gpr_malloc */
+ gpr_timer_log* log = static_cast<gpr_timer_log*>(malloc(sizeof(*log)));
+ gpr_once_init(&g_once_init, init_output);
+ log->num_entries = 0;
+ pthread_mutex_lock(&g_mu);
+ if (g_thread_log != NULL) {
+ timer_log_remove(&g_in_progress_logs, g_thread_log);
+ if (timer_log_push_back(&g_done_logs, g_thread_log)) {
+ pthread_cond_signal(&g_cv);
+ }
+ } else {
+ g_thread_id = g_next_thread_id++;
+ }
+ timer_log_push_back(&g_in_progress_logs, log);
+ pthread_mutex_unlock(&g_mu);
+ g_thread_log = log;
+}
+
+static void gpr_timers_log_add(const char* tagstr, marker_type type,
+ int important, const char* file, int line) {
+ gpr_timer_entry* entry;
+
+ if (!g_writing_enabled) {
+ return;
+ }
+
+ if (g_thread_log == NULL || g_thread_log->num_entries == MAX_COUNT) {
+ rotate_log();
+ }
+
+ entry = &g_thread_log->log[g_thread_log->num_entries++];
+
+ entry->tm = gpr_now(GPR_CLOCK_PRECISE);
+ entry->tagstr = tagstr;
+ entry->type = type;
+ entry->file = file;
+ entry->line = (short)line;
+ entry->important = important != 0;
+ entry->thd = g_thread_id;
+}
+
+/* Latency profiler API implementation. */
+void gpr_timer_add_mark(const char* tagstr, int important, const char* file,
+ int line) {
+ gpr_timers_log_add(tagstr, MARK, important, file, line);
+}
+
+void gpr_timer_begin(const char* tagstr, int important, const char* file,
+ int line) {
+ gpr_timers_log_add(tagstr, BEGIN, important, file, line);
+}
+
+void gpr_timer_end(const char* tagstr, int important, const char* file,
+ int line) {
+ gpr_timers_log_add(tagstr, END, important, file, line);
+}
+
+void gpr_timer_set_enabled(int enabled) { g_writing_enabled = enabled; }
+
+/* Basic profiler specific API functions. */
+void gpr_timers_global_init(void) {}
+
+void gpr_timers_global_destroy(void) {}
+
+#else /* !GRPC_BASIC_PROFILER */
+void gpr_timers_global_init(void) {}
+
+void gpr_timers_global_destroy(void) {}
+
void gpr_timers_set_log_filename(const char* /*filename*/) {}
-
+
void gpr_timer_set_enabled(int /*enabled*/) {}
-#endif /* GRPC_BASIC_PROFILER */
+#endif /* GRPC_BASIC_PROFILER */
diff --git a/contrib/libs/grpc/src/core/lib/profiling/stap_timers.cc b/contrib/libs/grpc/src/core/lib/profiling/stap_timers.cc
index 77c8ca3277a..d8489590d64 100644
--- a/contrib/libs/grpc/src/core/lib/profiling/stap_timers.cc
+++ b/contrib/libs/grpc/src/core/lib/profiling/stap_timers.cc
@@ -1,50 +1,50 @@
-/*
- *
- * 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 GRPC_STAP_PROFILER
-
-#include "src/core/lib/profiling/timers.h"
-
-#include <sys/sdt.h>
-/* Generated from src/core/profiling/stap_probes.d */
+/*
+ *
+ * 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 GRPC_STAP_PROFILER
+
+#include "src/core/lib/profiling/timers.h"
+
+#include <sys/sdt.h>
+/* Generated from src/core/profiling/stap_probes.d */
#error #include "src/core/lib/profiling/stap_probes.h"
-
-/* Latency profiler API implementation. */
-void gpr_timer_add_mark(int tag, const char* tagstr, void* id, const char* file,
- int line) {
- _STAP_ADD_MARK(tag);
-}
-
-void gpr_timer_add_important_mark(int tag, const char* tagstr, void* id,
- const char* file, int line) {
- _STAP_ADD_IMPORTANT_MARK(tag);
-}
-
-void gpr_timer_begin(int tag, const char* tagstr, void* id, const char* file,
- int line) {
- _STAP_TIMING_NS_BEGIN(tag);
-}
-
-void gpr_timer_end(int tag, const char* tagstr, void* id, const char* file,
- int line) {
- _STAP_TIMING_NS_END(tag);
-}
-
-#endif /* GRPC_STAP_PROFILER */
+
+/* Latency profiler API implementation. */
+void gpr_timer_add_mark(int tag, const char* tagstr, void* id, const char* file,
+ int line) {
+ _STAP_ADD_MARK(tag);
+}
+
+void gpr_timer_add_important_mark(int tag, const char* tagstr, void* id,
+ const char* file, int line) {
+ _STAP_ADD_IMPORTANT_MARK(tag);
+}
+
+void gpr_timer_begin(int tag, const char* tagstr, void* id, const char* file,
+ int line) {
+ _STAP_TIMING_NS_BEGIN(tag);
+}
+
+void gpr_timer_end(int tag, const char* tagstr, void* id, const char* file,
+ int line) {
+ _STAP_TIMING_NS_END(tag);
+}
+
+#endif /* GRPC_STAP_PROFILER */
diff --git a/contrib/libs/grpc/src/core/lib/profiling/timers.h b/contrib/libs/grpc/src/core/lib/profiling/timers.h
index 7ff72783ec9..cab6f9772e6 100644
--- a/contrib/libs/grpc/src/core/lib/profiling/timers.h
+++ b/contrib/libs/grpc/src/core/lib/profiling/timers.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -22,25 +22,25 @@
void gpr_timers_global_init(void);
void gpr_timers_global_destroy(void);
-void gpr_timer_add_mark(const char* tagstr, int important, const char* file,
+void gpr_timer_add_mark(const char* tagstr, int important, const char* file,
int line);
-void gpr_timer_begin(const char* tagstr, int important, const char* file,
+void gpr_timer_begin(const char* tagstr, int important, const char* file,
int line);
-void gpr_timer_end(const char* tagstr, int important, const char* file,
+void gpr_timer_end(const char* tagstr, int important, const char* file,
int line);
-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);
-#if !(defined(GRPC_STAP_PROFILER) + defined(GRPC_BASIC_PROFILER) + \
- defined(GRPC_CUSTOM_PROFILER))
+#if !(defined(GRPC_STAP_PROFILER) + defined(GRPC_BASIC_PROFILER) + \
+ defined(GRPC_CUSTOM_PROFILER))
/* No profiling. No-op all the things. */
#define GPR_TIMER_MARK(tag, important) \
do { \
} while (0)
-#define GPR_TIMER_SCOPE(tag, important) \
+#define GPR_TIMER_SCOPE(tag, important) \
do { \
} while (0)
@@ -49,12 +49,12 @@ void gpr_timer_set_enabled(int enabled);
#if defined(GRPC_STAP_PROFILER) && defined(GRPC_BASIC_PROFILER)
#error "GRPC_STAP_PROFILER and GRPC_BASIC_PROFILER are mutually exclusive."
#endif
-#if defined(GRPC_STAP_PROFILER) && defined(GRPC_CUSTOM_PROFILER)
-#error "GRPC_STAP_PROFILER and GRPC_CUSTOM_PROFILER are mutually exclusive."
-#endif
-#if defined(GRPC_CUSTOM_PROFILER) && defined(GRPC_BASIC_PROFILER)
-#error "GRPC_CUSTOM_PROFILER and GRPC_BASIC_PROFILER are mutually exclusive."
-#endif
+#if defined(GRPC_STAP_PROFILER) && defined(GRPC_CUSTOM_PROFILER)
+#error "GRPC_STAP_PROFILER and GRPC_CUSTOM_PROFILER are mutually exclusive."
+#endif
+#if defined(GRPC_CUSTOM_PROFILER) && defined(GRPC_BASIC_PROFILER)
+#error "GRPC_CUSTOM_PROFILER and GRPC_BASIC_PROFILER are mutually exclusive."
+#endif
/* Generic profiling interface. */
#define GPR_TIMER_MARK(tag, important) \
@@ -71,24 +71,24 @@ void gpr_timer_set_enabled(int enabled);
namespace grpc {
class ProfileScope {
public:
- ProfileScope(const char* desc, bool important, const char* file, int line)
- : desc_(desc) {
- gpr_timer_begin(desc_, important ? 1 : 0, file, line);
+ ProfileScope(const char* desc, bool important, const char* file, int line)
+ : desc_(desc) {
+ gpr_timer_begin(desc_, important ? 1 : 0, file, line);
}
- ~ProfileScope() { gpr_timer_end(desc_, 0, "n/a", 0); }
+ ~ProfileScope() { gpr_timer_end(desc_, 0, "n/a", 0); }
private:
- const char* const desc_;
+ const char* const desc_;
};
-} // namespace grpc
-
-#define GPR_TIMER_SCOPE_NAME_INTERNAL(prefix, line) prefix##line
-#define GPR_TIMER_SCOPE_NAME(prefix, line) \
- GPR_TIMER_SCOPE_NAME_INTERNAL(prefix, line)
-#define GPR_TIMER_SCOPE(tag, important) \
- ::grpc::ProfileScope GPR_TIMER_SCOPE_NAME(_profile_scope_, __LINE__)( \
- (tag), (important), __FILE__, __LINE__)
+} // namespace grpc
-#endif /* at least one profiler requested. */
+#define GPR_TIMER_SCOPE_NAME_INTERNAL(prefix, line) prefix##line
+#define GPR_TIMER_SCOPE_NAME(prefix, line) \
+ GPR_TIMER_SCOPE_NAME_INTERNAL(prefix, line)
+#define GPR_TIMER_SCOPE(tag, important) \
+ ::grpc::ProfileScope GPR_TIMER_SCOPE_NAME(_profile_scope_, __LINE__)( \
+ (tag), (important), __FILE__, __LINE__)
+#endif /* at least one profiler requested. */
+
#endif /* GRPC_CORE_LIB_PROFILING_TIMERS_H */
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 ef60165899d..1ebc3b8f421 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
@@ -1,71 +1,71 @@
-/*
- *
- * 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 <string.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/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 <string.h>
+
+#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/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/security/context/security_context.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/call.h"
-
-#include <grpc/grpc_security.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_auth_context_refcount(
- false, "auth_context_refcount");
-
-/* --- grpc_call --- */
-
-grpc_call_error grpc_call_set_credentials(grpc_call* call,
- grpc_call_credentials* creds) {
- grpc_core::ExecCtx exec_ctx;
- grpc_client_security_context* ctx = nullptr;
- GRPC_API_TRACE("grpc_call_set_credentials(call=%p, creds=%p)", 2,
- (call, creds));
- if (!grpc_call_is_client(call)) {
- gpr_log(GPR_ERROR, "Method is client-side only.");
- return GRPC_CALL_ERROR_NOT_ON_SERVER;
- }
- ctx = static_cast<grpc_client_security_context*>(
- grpc_call_context_get(call, GRPC_CONTEXT_SECURITY));
- if (ctx == nullptr) {
+#include "src/core/lib/security/context/security_context.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/call.h"
+
+#include <grpc/grpc_security.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+grpc_core::DebugOnlyTraceFlag grpc_trace_auth_context_refcount(
+ false, "auth_context_refcount");
+
+/* --- grpc_call --- */
+
+grpc_call_error grpc_call_set_credentials(grpc_call* call,
+ grpc_call_credentials* creds) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_client_security_context* ctx = nullptr;
+ GRPC_API_TRACE("grpc_call_set_credentials(call=%p, creds=%p)", 2,
+ (call, creds));
+ if (!grpc_call_is_client(call)) {
+ gpr_log(GPR_ERROR, "Method is client-side only.");
+ return GRPC_CALL_ERROR_NOT_ON_SERVER;
+ }
+ ctx = static_cast<grpc_client_security_context*>(
+ grpc_call_context_get(call, GRPC_CONTEXT_SECURITY));
+ if (ctx == nullptr) {
ctx = grpc_client_security_context_create(grpc_call_get_arena(call), creds);
- grpc_call_context_set(call, GRPC_CONTEXT_SECURITY, ctx,
- grpc_client_security_context_destroy);
- } else {
+ grpc_call_context_set(call, GRPC_CONTEXT_SECURITY, ctx,
+ grpc_client_security_context_destroy);
+ } else {
ctx->creds = creds != nullptr ? creds->Ref() : nullptr;
- }
-
- return GRPC_CALL_OK;
-}
-
-grpc_auth_context* grpc_call_auth_context(grpc_call* call) {
- void* sec_ctx = grpc_call_context_get(call, GRPC_CONTEXT_SECURITY);
- GRPC_API_TRACE("grpc_call_auth_context(call=%p)", 1, (call));
- if (sec_ctx == nullptr) return nullptr;
+ }
+
+ return GRPC_CALL_OK;
+}
+
+grpc_auth_context* grpc_call_auth_context(grpc_call* call) {
+ void* sec_ctx = grpc_call_context_get(call, GRPC_CONTEXT_SECURITY);
+ GRPC_API_TRACE("grpc_call_auth_context(call=%p)", 1, (call));
+ if (sec_ctx == nullptr) return nullptr;
if (grpc_call_is_client(call)) {
auto* sc = static_cast<grpc_client_security_context*>(sec_ctx);
if (sc->auth_context == nullptr) {
@@ -85,149 +85,149 @@ grpc_auth_context* grpc_call_auth_context(grpc_call* call) {
.release();
}
}
-}
-
-void grpc_auth_context_release(grpc_auth_context* context) {
- GRPC_API_TRACE("grpc_auth_context_release(context=%p)", 1, (context));
+}
+
+void grpc_auth_context_release(grpc_auth_context* context) {
+ GRPC_API_TRACE("grpc_auth_context_release(context=%p)", 1, (context));
if (context == nullptr) return;
context->Unref(DEBUG_LOCATION, "grpc_auth_context_unref");
-}
-
-/* --- grpc_client_security_context --- */
+}
+
+/* --- grpc_client_security_context --- */
grpc_client_security_context::~grpc_client_security_context() {
auth_context.reset(DEBUG_LOCATION, "client_security_context");
if (extension.instance != nullptr && extension.destroy != nullptr) {
extension.destroy(extension.instance);
}
}
-
+
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);
-}
-
-void grpc_client_security_context_destroy(void* ctx) {
- grpc_core::ExecCtx exec_ctx;
- grpc_client_security_context* c =
- static_cast<grpc_client_security_context*>(ctx);
+}
+
+void grpc_client_security_context_destroy(void* ctx) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_client_security_context* c =
+ static_cast<grpc_client_security_context*>(ctx);
c->~grpc_client_security_context();
-}
-
-/* --- grpc_server_security_context --- */
+}
+
+/* --- grpc_server_security_context --- */
grpc_server_security_context::~grpc_server_security_context() {
auth_context.reset(DEBUG_LOCATION, "server_security_context");
if (extension.instance != nullptr && extension.destroy != nullptr) {
extension.destroy(extension.instance);
}
}
-
+
grpc_server_security_context* grpc_server_security_context_create(
grpc_core::Arena* arena) {
return arena->New<grpc_server_security_context>();
-}
-
-void grpc_server_security_context_destroy(void* ctx) {
- grpc_server_security_context* c =
- static_cast<grpc_server_security_context*>(ctx);
+}
+
+void grpc_server_security_context_destroy(void* ctx) {
+ grpc_server_security_context* c =
+ static_cast<grpc_server_security_context*>(ctx);
c->~grpc_server_security_context();
-}
-
-/* --- grpc_auth_context --- */
-
-static grpc_auth_property_iterator empty_iterator = {nullptr, 0, nullptr};
-
-const char* grpc_auth_context_peer_identity_property_name(
- const grpc_auth_context* ctx) {
- GRPC_API_TRACE("grpc_auth_context_peer_identity_property_name(ctx=%p)", 1,
- (ctx));
+}
+
+/* --- grpc_auth_context --- */
+
+static grpc_auth_property_iterator empty_iterator = {nullptr, 0, nullptr};
+
+const char* grpc_auth_context_peer_identity_property_name(
+ const grpc_auth_context* ctx) {
+ GRPC_API_TRACE("grpc_auth_context_peer_identity_property_name(ctx=%p)", 1,
+ (ctx));
return ctx->peer_identity_property_name();
-}
-
-int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context* ctx,
- const char* name) {
- grpc_auth_property_iterator it =
- grpc_auth_context_find_properties_by_name(ctx, name);
- const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it);
- GRPC_API_TRACE(
- "grpc_auth_context_set_peer_identity_property_name(ctx=%p, name=%s)", 2,
- (ctx, name));
- if (prop == nullptr) {
- gpr_log(GPR_ERROR, "Property name %s not found in auth context.",
- name != nullptr ? name : "NULL");
- return 0;
- }
+}
+
+int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context* ctx,
+ const char* name) {
+ grpc_auth_property_iterator it =
+ grpc_auth_context_find_properties_by_name(ctx, name);
+ const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it);
+ GRPC_API_TRACE(
+ "grpc_auth_context_set_peer_identity_property_name(ctx=%p, name=%s)", 2,
+ (ctx, name));
+ if (prop == nullptr) {
+ gpr_log(GPR_ERROR, "Property name %s not found in auth context.",
+ name != nullptr ? name : "NULL");
+ return 0;
+ }
ctx->set_peer_identity_property_name(prop->name);
- return 1;
-}
-
-int grpc_auth_context_peer_is_authenticated(const grpc_auth_context* ctx) {
- GRPC_API_TRACE("grpc_auth_context_peer_is_authenticated(ctx=%p)", 1, (ctx));
+ return 1;
+}
+
+int grpc_auth_context_peer_is_authenticated(const grpc_auth_context* ctx) {
+ GRPC_API_TRACE("grpc_auth_context_peer_is_authenticated(ctx=%p)", 1, (ctx));
return ctx->is_authenticated();
-}
-
-grpc_auth_property_iterator grpc_auth_context_property_iterator(
- const grpc_auth_context* ctx) {
- grpc_auth_property_iterator it = empty_iterator;
- GRPC_API_TRACE("grpc_auth_context_property_iterator(ctx=%p)", 1, (ctx));
- if (ctx == nullptr) return it;
- it.ctx = ctx;
- return it;
-}
-
-const grpc_auth_property* grpc_auth_property_iterator_next(
- grpc_auth_property_iterator* it) {
- GRPC_API_TRACE("grpc_auth_property_iterator_next(it=%p)", 1, (it));
- if (it == nullptr || it->ctx == nullptr) return nullptr;
+}
+
+grpc_auth_property_iterator grpc_auth_context_property_iterator(
+ const grpc_auth_context* ctx) {
+ grpc_auth_property_iterator it = empty_iterator;
+ GRPC_API_TRACE("grpc_auth_context_property_iterator(ctx=%p)", 1, (ctx));
+ if (ctx == nullptr) return it;
+ it.ctx = ctx;
+ return it;
+}
+
+const grpc_auth_property* grpc_auth_property_iterator_next(
+ grpc_auth_property_iterator* it) {
+ GRPC_API_TRACE("grpc_auth_property_iterator_next(it=%p)", 1, (it));
+ if (it == nullptr || it->ctx == nullptr) return nullptr;
while (it->index == it->ctx->properties().count) {
if (it->ctx->chained() == nullptr) return nullptr;
it->ctx = it->ctx->chained();
- it->index = 0;
- }
- if (it->name == nullptr) {
+ it->index = 0;
+ }
+ if (it->name == nullptr) {
return &it->ctx->properties().array[it->index++];
- } else {
+ } else {
while (it->index < it->ctx->properties().count) {
const grpc_auth_property* prop =
&it->ctx->properties().array[it->index++];
- GPR_ASSERT(prop->name != nullptr);
- if (strcmp(it->name, prop->name) == 0) {
- return prop;
- }
- }
- /* We could not find the name, try another round. */
- return grpc_auth_property_iterator_next(it);
- }
-}
-
-grpc_auth_property_iterator grpc_auth_context_find_properties_by_name(
- const grpc_auth_context* ctx, const char* name) {
- grpc_auth_property_iterator it = empty_iterator;
- GRPC_API_TRACE("grpc_auth_context_find_properties_by_name(ctx=%p, name=%s)",
- 2, (ctx, name));
- if (ctx == nullptr || name == nullptr) return empty_iterator;
- it.ctx = ctx;
- it.name = name;
- return it;
-}
-
-grpc_auth_property_iterator grpc_auth_context_peer_identity(
- const grpc_auth_context* ctx) {
- GRPC_API_TRACE("grpc_auth_context_peer_identity(ctx=%p)", 1, (ctx));
- if (ctx == nullptr) return empty_iterator;
- return grpc_auth_context_find_properties_by_name(
+ GPR_ASSERT(prop->name != nullptr);
+ if (strcmp(it->name, prop->name) == 0) {
+ return prop;
+ }
+ }
+ /* We could not find the name, try another round. */
+ return grpc_auth_property_iterator_next(it);
+ }
+}
+
+grpc_auth_property_iterator grpc_auth_context_find_properties_by_name(
+ const grpc_auth_context* ctx, const char* name) {
+ grpc_auth_property_iterator it = empty_iterator;
+ GRPC_API_TRACE("grpc_auth_context_find_properties_by_name(ctx=%p, name=%s)",
+ 2, (ctx, name));
+ if (ctx == nullptr || name == nullptr) return empty_iterator;
+ it.ctx = ctx;
+ it.name = name;
+ return it;
+}
+
+grpc_auth_property_iterator grpc_auth_context_peer_identity(
+ const grpc_auth_context* ctx) {
+ GRPC_API_TRACE("grpc_auth_context_peer_identity(ctx=%p)", 1, (ctx));
+ if (ctx == nullptr) return empty_iterator;
+ return grpc_auth_context_find_properties_by_name(
ctx, ctx->peer_identity_property_name());
-}
-
+}
+
void grpc_auth_context::ensure_capacity() {
if (properties_.count == properties_.capacity) {
properties_.capacity =
GPR_MAX(properties_.capacity + 8, properties_.capacity * 2);
properties_.array = static_cast<grpc_auth_property*>(gpr_realloc(
properties_.array, properties_.capacity * sizeof(grpc_auth_property)));
- }
-}
-
+ }
+}
+
void grpc_auth_context::add_property(const char* name, const char* value,
size_t value_length) {
ensure_capacity();
@@ -239,14 +239,14 @@ void grpc_auth_context::add_property(const char* name, const char* value,
prop->value_length = value_length;
}
-void grpc_auth_context_add_property(grpc_auth_context* ctx, const char* name,
- const char* value, size_t value_length) {
- GRPC_API_TRACE(
- "grpc_auth_context_add_property(ctx=%p, name=%s, value=%*.*s, "
- "value_length=%lu)",
- 6,
- (ctx, name, (int)value_length, (int)value_length, value,
- (unsigned long)value_length));
+void grpc_auth_context_add_property(grpc_auth_context* ctx, const char* name,
+ const char* value, size_t value_length) {
+ GRPC_API_TRACE(
+ "grpc_auth_context_add_property(ctx=%p, name=%s, value=%*.*s, "
+ "value_length=%lu)",
+ 6,
+ (ctx, name, (int)value_length, (int)value_length, value,
+ (unsigned long)value_length));
ctx->add_property(name, value, value_length);
}
@@ -254,68 +254,68 @@ void grpc_auth_context::add_cstring_property(const char* name,
const char* value) {
ensure_capacity();
grpc_auth_property* prop = &properties_.array[properties_.count++];
- prop->name = gpr_strdup(name);
+ prop->name = gpr_strdup(name);
prop->value = gpr_strdup(value);
prop->value_length = strlen(value);
-}
-
-void grpc_auth_context_add_cstring_property(grpc_auth_context* ctx,
- const char* name,
- const char* value) {
- GRPC_API_TRACE(
- "grpc_auth_context_add_cstring_property(ctx=%p, name=%s, value=%s)", 3,
- (ctx, name, value));
+}
+
+void grpc_auth_context_add_cstring_property(grpc_auth_context* ctx,
+ const char* name,
+ const char* value) {
+ GRPC_API_TRACE(
+ "grpc_auth_context_add_cstring_property(ctx=%p, name=%s, value=%s)", 3,
+ (ctx, name, value));
ctx->add_cstring_property(name, value);
-}
-
-void grpc_auth_property_reset(grpc_auth_property* property) {
- gpr_free(property->name);
- gpr_free(property->value);
- memset(property, 0, sizeof(grpc_auth_property));
-}
-
-static void auth_context_pointer_arg_destroy(void* p) {
+}
+
+void grpc_auth_property_reset(grpc_auth_property* property) {
+ gpr_free(property->name);
+ gpr_free(property->value);
+ memset(property, 0, sizeof(grpc_auth_property));
+}
+
+static void auth_context_pointer_arg_destroy(void* p) {
if (p != nullptr) {
static_cast<grpc_auth_context*>(p)->Unref(DEBUG_LOCATION,
"auth_context_pointer_arg");
}
-}
-
-static void* auth_context_pointer_arg_copy(void* p) {
+}
+
+static void* auth_context_pointer_arg_copy(void* p) {
auto* ctx = static_cast<grpc_auth_context*>(p);
return ctx == nullptr
? nullptr
: ctx->Ref(DEBUG_LOCATION, "auth_context_pointer_arg").release();
-}
-
-static int auth_context_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
-
-static const grpc_arg_pointer_vtable auth_context_pointer_vtable = {
- auth_context_pointer_arg_copy, auth_context_pointer_arg_destroy,
- auth_context_pointer_cmp};
-
-grpc_arg grpc_auth_context_to_arg(grpc_auth_context* p) {
- return grpc_channel_arg_pointer_create((char*)GRPC_AUTH_CONTEXT_ARG, p,
- &auth_context_pointer_vtable);
-}
-
-grpc_auth_context* grpc_auth_context_from_arg(const grpc_arg* arg) {
- if (strcmp(arg->key, GRPC_AUTH_CONTEXT_ARG) != 0) return nullptr;
- if (arg->type != GRPC_ARG_POINTER) {
- gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
- GRPC_AUTH_CONTEXT_ARG);
- return nullptr;
- }
- return static_cast<grpc_auth_context*>(arg->value.pointer.p);
-}
-
-grpc_auth_context* grpc_find_auth_context_in_args(
- const grpc_channel_args* args) {
- size_t i;
- if (args == nullptr) return nullptr;
- for (i = 0; i < args->num_args; i++) {
- grpc_auth_context* p = grpc_auth_context_from_arg(&args->args[i]);
- if (p != nullptr) return p;
- }
- return nullptr;
-}
+}
+
+static int auth_context_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
+
+static const grpc_arg_pointer_vtable auth_context_pointer_vtable = {
+ auth_context_pointer_arg_copy, auth_context_pointer_arg_destroy,
+ auth_context_pointer_cmp};
+
+grpc_arg grpc_auth_context_to_arg(grpc_auth_context* p) {
+ return grpc_channel_arg_pointer_create((char*)GRPC_AUTH_CONTEXT_ARG, p,
+ &auth_context_pointer_vtable);
+}
+
+grpc_auth_context* grpc_auth_context_from_arg(const grpc_arg* arg) {
+ if (strcmp(arg->key, GRPC_AUTH_CONTEXT_ARG) != 0) return nullptr;
+ if (arg->type != GRPC_ARG_POINTER) {
+ gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
+ GRPC_AUTH_CONTEXT_ARG);
+ return nullptr;
+ }
+ return static_cast<grpc_auth_context*>(arg->value.pointer.p);
+}
+
+grpc_auth_context* grpc_find_auth_context_in_args(
+ const grpc_channel_args* args) {
+ size_t i;
+ if (args == nullptr) return nullptr;
+ for (i = 0; i < args->num_args; i++) {
+ grpc_auth_context* p = grpc_auth_context_from_arg(&args->args[i]);
+ if (p != nullptr) return p;
+ }
+ return nullptr;
+}
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 b1991089ae5..7e15f3003d2 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
@@ -1,33 +1,33 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CONTEXT_SECURITY_CONTEXT_H
#define GRPC_CORE_LIB_SECURITY_CONTEXT_SECURITY_CONTEXT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.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"
#include "src/core/lib/security/credentials/credentials.h"
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_auth_context_refcount;
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_auth_context_refcount;
/* --- grpc_auth_context ---
@@ -121,7 +121,7 @@ struct grpc_client_security_context {
grpc_client_security_context* grpc_client_security_context_create(
grpc_core::Arena* arena, grpc_call_credentials* creds);
-void grpc_client_security_context_destroy(void* ctx);
+void grpc_client_security_context_destroy(void* ctx);
/* --- grpc_server_security_context ---
@@ -137,14 +137,14 @@ struct grpc_server_security_context {
grpc_server_security_context* grpc_server_security_context_create(
grpc_core::Arena* arena);
-void grpc_server_security_context_destroy(void* ctx);
+void grpc_server_security_context_destroy(void* ctx);
/* --- Channel args for auth context --- */
#define GRPC_AUTH_CONTEXT_ARG "grpc.auth_context"
-grpc_arg grpc_auth_context_to_arg(grpc_auth_context* c);
-grpc_auth_context* grpc_auth_context_from_arg(const grpc_arg* arg);
-grpc_auth_context* grpc_find_auth_context_in_args(
- const grpc_channel_args* args);
+grpc_arg grpc_auth_context_to_arg(grpc_auth_context* c);
+grpc_auth_context* grpc_auth_context_from_arg(const grpc_arg* arg);
+grpc_auth_context* grpc_find_auth_context_in_args(
+ const grpc_channel_args* args);
#endif /* GRPC_CORE_LIB_SECURITY_CONTEXT_SECURITY_CONTEXT_H */
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 1bc76d9c0c6..5b0a78e949a 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
@@ -1,38 +1,38 @@
-/*
- *
- * 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/lib/security/credentials/alts/alts_credentials.h"
-
-#include <cstring>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/security/credentials/alts/check_gcp_environment.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 "src/core/lib/security/credentials/alts/alts_credentials.h"
+
+#include <cstring>
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
#include "src/core/lib/security/security_connector/alts/alts_security_connector.h"
-
-#define GRPC_CREDENTIALS_TYPE_ALTS "Alts"
+
+#define GRPC_CREDENTIALS_TYPE_ALTS "Alts"
#define GRPC_ALTS_HANDSHAKER_SERVICE_URL "metadata.google.internal.:8080"
-
+
grpc_alts_credentials::grpc_alts_credentials(
const grpc_alts_credentials_options* options,
const char* handshaker_service_url)
@@ -43,21 +43,21 @@ grpc_alts_credentials::grpc_alts_credentials(
: 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_);
gpr_free(handshaker_service_url_);
-}
-
+}
+
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*/) {
- return grpc_alts_channel_security_connector_create(
+ return grpc_alts_channel_security_connector_create(
this->Ref(), std::move(call_creds), target_name);
-}
-
+}
+
grpc_alts_server_credentials::grpc_alts_server_credentials(
const grpc_alts_credentials_options* options,
const char* handshaker_service_url)
@@ -72,39 +72,39 @@ grpc_alts_server_credentials::grpc_alts_server_credentials(
grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_alts_server_credentials::create_security_connector() {
return grpc_alts_server_security_connector_create(this->Ref());
-}
-
+}
+
grpc_alts_server_credentials::~grpc_alts_server_credentials() {
grpc_alts_credentials_options_destroy(options_);
gpr_free(handshaker_service_url_);
}
-
-grpc_channel_credentials* grpc_alts_credentials_create_customized(
- const grpc_alts_credentials_options* options,
- const char* handshaker_service_url, bool enable_untrusted_alts) {
- if (!enable_untrusted_alts && !grpc_alts_is_running_on_gcp()) {
- return nullptr;
- }
+
+grpc_channel_credentials* grpc_alts_credentials_create_customized(
+ const grpc_alts_credentials_options* options,
+ const char* handshaker_service_url, bool enable_untrusted_alts) {
+ if (!enable_untrusted_alts && !grpc_alts_is_running_on_gcp()) {
+ return nullptr;
+ }
return new grpc_alts_credentials(options, handshaker_service_url);
-}
-
-grpc_server_credentials* grpc_alts_server_credentials_create_customized(
- const grpc_alts_credentials_options* options,
- const char* handshaker_service_url, bool enable_untrusted_alts) {
- if (!enable_untrusted_alts && !grpc_alts_is_running_on_gcp()) {
- return nullptr;
- }
+}
+
+grpc_server_credentials* grpc_alts_server_credentials_create_customized(
+ const grpc_alts_credentials_options* options,
+ const char* handshaker_service_url, bool enable_untrusted_alts) {
+ if (!enable_untrusted_alts && !grpc_alts_is_running_on_gcp()) {
+ return nullptr;
+ }
return new grpc_alts_server_credentials(options, handshaker_service_url);
-}
-
-grpc_channel_credentials* grpc_alts_credentials_create(
- const grpc_alts_credentials_options* options) {
- return grpc_alts_credentials_create_customized(
- options, GRPC_ALTS_HANDSHAKER_SERVICE_URL, false);
-}
-
-grpc_server_credentials* grpc_alts_server_credentials_create(
- const grpc_alts_credentials_options* options) {
- return grpc_alts_server_credentials_create_customized(
- options, GRPC_ALTS_HANDSHAKER_SERVICE_URL, false);
-}
+}
+
+grpc_channel_credentials* grpc_alts_credentials_create(
+ const grpc_alts_credentials_options* options) {
+ return grpc_alts_credentials_create_customized(
+ options, GRPC_ALTS_HANDSHAKER_SERVICE_URL, false);
+}
+
+grpc_server_credentials* grpc_alts_server_credentials_create(
+ const grpc_alts_credentials_options* options) {
+ return grpc_alts_server_credentials_create_customized(
+ options, GRPC_ALTS_HANDSHAKER_SERVICE_URL, false);
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h
index cc6d5222b16..4ec4451efe6 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h
@@ -1,38 +1,38 @@
-/*
- *
- * 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_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H
-#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc_security.h>
-
-#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
-#include "src/core/lib/security/credentials/credentials.h"
-
-/* Main struct for grpc ALTS channel credential. */
+/*
+ *
+ * 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_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H
+#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc_security.h>
+
+#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
+#include "src/core/lib/security/credentials/credentials.h"
+
+/* Main struct for grpc ALTS channel credential. */
class grpc_alts_credentials final : public grpc_channel_credentials {
public:
grpc_alts_credentials(const grpc_alts_credentials_options* options,
const char* handshaker_service_url);
~grpc_alts_credentials() override;
-
+
grpc_core::RefCountedPtr<grpc_channel_security_connector>
create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
@@ -48,13 +48,13 @@ class grpc_alts_credentials final : public grpc_channel_credentials {
char* handshaker_service_url_;
};
-/* Main struct for grpc ALTS server credential. */
+/* Main struct for grpc ALTS server credential. */
class grpc_alts_server_credentials final : public grpc_server_credentials {
public:
grpc_alts_server_credentials(const grpc_alts_credentials_options* options,
const char* handshaker_service_url);
~grpc_alts_server_credentials() override;
-
+
grpc_core::RefCountedPtr<grpc_server_security_connector>
create_security_connector() override;
@@ -67,43 +67,43 @@ class grpc_alts_server_credentials final : public grpc_server_credentials {
char* handshaker_service_url_;
};
-/**
- * This method creates an ALTS channel credential object with customized
- * information provided by caller.
- *
- * - options: grpc ALTS credentials options instance for client.
- * - handshaker_service_url: address of ALTS handshaker service in the format of
- * "host:port". If it's nullptr, the address of default metadata server will
- * be used.
- * - enable_untrusted_alts: a boolean flag used to enable ALTS in untrusted
- * mode. This mode can be enabled when we are sure ALTS is running on GCP or
- * for testing purpose.
- *
- * It returns nullptr if the flag is disabled AND ALTS is not running on GCP.
- * Otherwise, it returns the created credential object.
- */
-
-grpc_channel_credentials* grpc_alts_credentials_create_customized(
- const grpc_alts_credentials_options* options,
- const char* handshaker_service_url, bool enable_untrusted_alts);
-
-/**
- * This method creates an ALTS server credential object with customized
- * information provided by caller.
- *
- * - options: grpc ALTS credentials options instance for server.
- * - handshaker_service_url: address of ALTS handshaker service in the format of
- * "host:port". If it's nullptr, the address of default metadata server will
- * be used.
- * - enable_untrusted_alts: a boolean flag used to enable ALTS in untrusted
- * mode. This mode can be enabled when we are sure ALTS is running on GCP or
- * for testing purpose.
- *
- * It returns nullptr if the flag is disabled and ALTS is not running on GCP.
- * Otherwise, it returns the created credential object.
- */
-grpc_server_credentials* grpc_alts_server_credentials_create_customized(
- const grpc_alts_credentials_options* options,
- const char* handshaker_service_url, bool enable_untrusted_alts);
-
-#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H */
+/**
+ * This method creates an ALTS channel credential object with customized
+ * information provided by caller.
+ *
+ * - options: grpc ALTS credentials options instance for client.
+ * - handshaker_service_url: address of ALTS handshaker service in the format of
+ * "host:port". If it's nullptr, the address of default metadata server will
+ * be used.
+ * - enable_untrusted_alts: a boolean flag used to enable ALTS in untrusted
+ * mode. This mode can be enabled when we are sure ALTS is running on GCP or
+ * for testing purpose.
+ *
+ * It returns nullptr if the flag is disabled AND ALTS is not running on GCP.
+ * Otherwise, it returns the created credential object.
+ */
+
+grpc_channel_credentials* grpc_alts_credentials_create_customized(
+ const grpc_alts_credentials_options* options,
+ const char* handshaker_service_url, bool enable_untrusted_alts);
+
+/**
+ * This method creates an ALTS server credential object with customized
+ * information provided by caller.
+ *
+ * - options: grpc ALTS credentials options instance for server.
+ * - handshaker_service_url: address of ALTS handshaker service in the format of
+ * "host:port". If it's nullptr, the address of default metadata server will
+ * be used.
+ * - enable_untrusted_alts: a boolean flag used to enable ALTS in untrusted
+ * mode. This mode can be enabled when we are sure ALTS is running on GCP or
+ * for testing purpose.
+ *
+ * It returns nullptr if the flag is disabled and ALTS is not running on GCP.
+ * Otherwise, it returns the created credential object.
+ */
+grpc_server_credentials* grpc_alts_server_credentials_create_customized(
+ const grpc_alts_credentials_options* options,
+ const char* handshaker_service_url, bool enable_untrusted_alts);
+
+#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_ALTS_CREDENTIALS_H */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.cc
index 9c98d7a5f4f..5c3effd4031 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
-
-#include <ctype.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-const size_t kBiosDataBufferSize = 256;
-
-static char* trim(const char* src) {
+/*
+ *
+ * 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/lib/security/credentials/alts/check_gcp_environment.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+const size_t kBiosDataBufferSize = 256;
+
+static char* trim(const char* src) {
if (src == nullptr || *src == '\0') {
- return nullptr;
- }
- char* des = nullptr;
- size_t start = 0, end = strlen(src) - 1;
- /* find the last character that is not a whitespace. */
- while (end != 0 && isspace(src[end])) {
- end--;
- }
- /* find the first character that is not a whitespace. */
- while (start < strlen(src) && isspace(src[start])) {
- start++;
- }
- if (start <= end) {
- des = static_cast<char*>(
- gpr_zalloc(sizeof(char) * (end - start + 2 /* '\0' */)));
- memcpy(des, src + start, end - start + 1);
- }
- return des;
-}
-
-namespace grpc_core {
-namespace internal {
-
-char* read_bios_file(const char* bios_file) {
- FILE* fp = fopen(bios_file, "r");
- if (!fp) {
- gpr_log(GPR_ERROR, "BIOS data file cannot be opened.");
- return nullptr;
- }
- char buf[kBiosDataBufferSize + 1];
- size_t ret = fread(buf, sizeof(char), kBiosDataBufferSize, fp);
- buf[ret] = '\0';
- char* trimmed_buf = trim(buf);
- fclose(fp);
- return trimmed_buf;
-}
-
-} // namespace internal
-} // namespace grpc_core
+ return nullptr;
+ }
+ char* des = nullptr;
+ size_t start = 0, end = strlen(src) - 1;
+ /* find the last character that is not a whitespace. */
+ while (end != 0 && isspace(src[end])) {
+ end--;
+ }
+ /* find the first character that is not a whitespace. */
+ while (start < strlen(src) && isspace(src[start])) {
+ start++;
+ }
+ if (start <= end) {
+ des = static_cast<char*>(
+ gpr_zalloc(sizeof(char) * (end - start + 2 /* '\0' */)));
+ memcpy(des, src + start, end - start + 1);
+ }
+ return des;
+}
+
+namespace grpc_core {
+namespace internal {
+
+char* read_bios_file(const char* bios_file) {
+ FILE* fp = fopen(bios_file, "r");
+ if (!fp) {
+ gpr_log(GPR_ERROR, "BIOS data file cannot be opened.");
+ return nullptr;
+ }
+ char buf[kBiosDataBufferSize + 1];
+ size_t ret = fread(buf, sizeof(char), kBiosDataBufferSize, fp);
+ buf[ret] = '\0';
+ char* trimmed_buf = trim(buf);
+ fclose(fp);
+ return trimmed_buf;
+}
+
+} // namespace internal
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.h b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.h
index aea4cea6432..2ba25705dec 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment.h
@@ -1,57 +1,57 @@
-/*
- *
- * 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_SECURITY_CREDENTIALS_ALTS_CHECK_GCP_ENVIRONMENT_H
-#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_CHECK_GCP_ENVIRONMENT_H
-
-namespace grpc_core {
-namespace internal {
-
-/**
- * This method is a helper function that reads a file containing system bios
- * data. Exposed for testing only.
- *
- * - bios_file: a file containing BIOS data used to determine GCE tenancy
- * information.
- *
- * It returns a buffer containing the data read from the file.
- */
-char* read_bios_file(const char* bios_file);
-
-/**
- * This method checks if system BIOS data contains Google-specific phrases.
- * Exposed for testing only.
- *
- * - bios_data: a buffer containing system BIOS data.
- *
- * It returns true if the BIOS data contains Google-specific phrases, and false
- * otherwise.
- */
-bool check_bios_data(const char* bios_data);
-
-} // namespace internal
-} // namespace grpc_core
-
-/**
- * This method checks if a VM (Windows or Linux) is running within Google
- * compute Engine (GCE) or not. It returns true if the VM is running in GCE and
- * false otherwise.
- */
-bool grpc_alts_is_running_on_gcp();
-
-#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_CHECK_GCP_ENVIRONMENT_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_LIB_SECURITY_CREDENTIALS_ALTS_CHECK_GCP_ENVIRONMENT_H
+#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_CHECK_GCP_ENVIRONMENT_H
+
+namespace grpc_core {
+namespace internal {
+
+/**
+ * This method is a helper function that reads a file containing system bios
+ * data. Exposed for testing only.
+ *
+ * - bios_file: a file containing BIOS data used to determine GCE tenancy
+ * information.
+ *
+ * It returns a buffer containing the data read from the file.
+ */
+char* read_bios_file(const char* bios_file);
+
+/**
+ * This method checks if system BIOS data contains Google-specific phrases.
+ * Exposed for testing only.
+ *
+ * - bios_data: a buffer containing system BIOS data.
+ *
+ * It returns true if the BIOS data contains Google-specific phrases, and false
+ * otherwise.
+ */
+bool check_bios_data(const char* bios_data);
+
+} // namespace internal
+} // namespace grpc_core
+
+/**
+ * This method checks if a VM (Windows or Linux) is running within Google
+ * compute Engine (GCE) or not. It returns true if the VM is running in GCE and
+ * false otherwise.
+ */
+bool grpc_alts_is_running_on_gcp();
+
+#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_CHECK_GCP_ENVIRONMENT_H */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc
index 8454fd7558c..0b190e160fd 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc
@@ -1,68 +1,68 @@
-/*
- *
- * 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>
-
-#ifdef GPR_LINUX
-
-#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/sync.h>
-
-#include <string.h>
-
-#define GRPC_ALTS_EXPECT_NAME_GOOGLE "Google"
-#define GRPC_ALTS_EXPECT_NAME_GCE "Google Compute Engine"
-#define GRPC_ALTS_PRODUCT_NAME_FILE "/sys/class/dmi/id/product_name"
-
-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;
-
-namespace grpc_core {
-namespace internal {
-
-bool check_bios_data(const char* bios_data_file) {
- char* bios_data = read_bios_file(bios_data_file);
+/*
+ *
+ * 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>
+
+#ifdef GPR_LINUX
+
+#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/sync.h>
+
+#include <string.h>
+
+#define GRPC_ALTS_EXPECT_NAME_GOOGLE "Google"
+#define GRPC_ALTS_EXPECT_NAME_GCE "Google Compute Engine"
+#define GRPC_ALTS_PRODUCT_NAME_FILE "/sys/class/dmi/id/product_name"
+
+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;
+
+namespace grpc_core {
+namespace internal {
+
+bool check_bios_data(const char* bios_data_file) {
+ char* bios_data = read_bios_file(bios_data_file);
bool result =
bios_data && ((!strcmp(bios_data, GRPC_ALTS_EXPECT_NAME_GOOGLE)) ||
(!strcmp(bios_data, GRPC_ALTS_EXPECT_NAME_GCE)));
- gpr_free(bios_data);
- return result;
-}
-
-} // namespace internal
-} // namespace grpc_core
-
-static void init_mu(void) { gpr_mu_init(&g_mu); }
-
-bool grpc_alts_is_running_on_gcp() {
- 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_bios_data(GRPC_ALTS_PRODUCT_NAME_FILE);
- g_compute_engine_detection_done = true;
- }
- gpr_mu_unlock(&g_mu);
- return g_is_on_compute_engine;
-}
-
-#endif // GPR_LINUX
+ gpr_free(bios_data);
+ return result;
+}
+
+} // namespace internal
+} // namespace grpc_core
+
+static void init_mu(void) { gpr_mu_init(&g_mu); }
+
+bool grpc_alts_is_running_on_gcp() {
+ 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_bios_data(GRPC_ALTS_PRODUCT_NAME_FILE);
+ g_compute_engine_detection_done = true;
+ }
+ gpr_mu_unlock(&g_mu);
+ return g_is_on_compute_engine;
+}
+
+#endif // GPR_LINUX
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc
index b71f66a536a..60acb75c511 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc
@@ -1,33 +1,33 @@
-/*
- *
- * 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>
-
-#if !defined(GPR_LINUX) && !defined(GPR_WINDOWS)
-
-#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
-
-#include <grpc/support/log.h>
-
-bool grpc_alts_is_running_on_gcp() {
+/*
+ *
+ * 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>
+
+#if !defined(GPR_LINUX) && !defined(GPR_WINDOWS)
+
+#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
+
+#include <grpc/support/log.h>
+
+bool grpc_alts_is_running_on_gcp() {
gpr_log(GPR_INFO,
"ALTS: Platforms other than Linux and Windows are not supported");
- return false;
-}
-
-#endif // !defined(LINUX) && !defined(GPR_WINDOWS)
+ return false;
+}
+
+#endif // !defined(LINUX) && !defined(GPR_WINDOWS)
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 59432cff361..3ee99e9ecb0 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
@@ -1,47 +1,47 @@
-/*
- *
- * 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>
-
-#ifdef GPR_WINDOWS
-
-#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
-
-#include <shellapi.h>
-#include <stdio.h>
-#include <tchar.h>
-#include <windows.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-namespace grpc_core {
-namespace internal {
-
+/*
+ *
+ * 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>
+
+#ifdef GPR_WINDOWS
+
+#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
+
+#include <shellapi.h>
+#include <stdio.h>
+#include <tchar.h>
+#include <windows.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+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{};
@@ -53,10 +53,10 @@ bool check_windows_registry_product_name(HKEY root_key,
if (rc != 0) {
return false;
}
-
+
if (buffer_size > kProductNameBufferSize) {
- return false;
- }
+ return false;
+ }
// Retrieve the product name string.
char buffer[kProductNameBufferSize];
@@ -67,12 +67,12 @@ bool check_windows_registry_product_name(HKEY root_key,
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 false;
+ }
return strstr(buffer, expected_substr) != nullptr;
-}
-
+}
+
} // namespace internal
} // namespace grpc_core
@@ -83,20 +83,20 @@ 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() {
+bool grpc_alts_is_running_on_gcp() {
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 =
+ 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);
- g_compute_engine_detection_done = true;
- }
- gpr_mu_unlock(&g_mu);
- return g_is_on_compute_engine;
-}
-
-#endif // GPR_WINDOWS
+ g_compute_engine_detection_done = true;
+ }
+ gpr_mu_unlock(&g_mu);
+ return g_is_on_compute_engine;
+}
+
+#endif // GPR_WINDOWS
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc
index 118d18d1191..346d568426d 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc
@@ -1,127 +1,127 @@
-/*
- *
- * 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 <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
-#include "src/core/tsi/alts/handshaker/transport_security_common_api.h"
-
-static grpc_alts_credentials_options* alts_client_options_copy(
- const grpc_alts_credentials_options* options);
-
-static void alts_client_options_destroy(grpc_alts_credentials_options* options);
-
-static target_service_account* target_service_account_create(
- const char* service_account) {
- if (service_account == nullptr) {
- return nullptr;
- }
- auto* sa = static_cast<target_service_account*>(
- gpr_zalloc(sizeof(target_service_account)));
- sa->data = gpr_strdup(service_account);
- return sa;
-}
-
-void grpc_alts_credentials_client_options_add_target_service_account(
- grpc_alts_credentials_options* options, const char* service_account) {
- if (options == nullptr || service_account == nullptr) {
- gpr_log(
- GPR_ERROR,
- "Invalid nullptr arguments to "
- "grpc_alts_credentials_client_options_add_target_service_account()");
- return;
- }
- auto client_options =
- reinterpret_cast<grpc_alts_credentials_client_options*>(options);
- target_service_account* node = target_service_account_create(service_account);
- node->next = client_options->target_account_list_head;
- client_options->target_account_list_head = node;
-}
-
-static void target_service_account_destroy(
- target_service_account* service_account) {
- if (service_account == nullptr) {
- return;
- }
- gpr_free(service_account->data);
- gpr_free(service_account);
-}
-
-static const grpc_alts_credentials_options_vtable vtable = {
- alts_client_options_copy, alts_client_options_destroy};
-
+/*
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
+#include "src/core/tsi/alts/handshaker/transport_security_common_api.h"
+
+static grpc_alts_credentials_options* alts_client_options_copy(
+ const grpc_alts_credentials_options* options);
+
+static void alts_client_options_destroy(grpc_alts_credentials_options* options);
+
+static target_service_account* target_service_account_create(
+ const char* service_account) {
+ if (service_account == nullptr) {
+ return nullptr;
+ }
+ auto* sa = static_cast<target_service_account*>(
+ gpr_zalloc(sizeof(target_service_account)));
+ sa->data = gpr_strdup(service_account);
+ return sa;
+}
+
+void grpc_alts_credentials_client_options_add_target_service_account(
+ grpc_alts_credentials_options* options, const char* service_account) {
+ if (options == nullptr || service_account == nullptr) {
+ gpr_log(
+ GPR_ERROR,
+ "Invalid nullptr arguments to "
+ "grpc_alts_credentials_client_options_add_target_service_account()");
+ return;
+ }
+ auto client_options =
+ reinterpret_cast<grpc_alts_credentials_client_options*>(options);
+ target_service_account* node = target_service_account_create(service_account);
+ node->next = client_options->target_account_list_head;
+ client_options->target_account_list_head = node;
+}
+
+static void target_service_account_destroy(
+ target_service_account* service_account) {
+ if (service_account == nullptr) {
+ return;
+ }
+ gpr_free(service_account->data);
+ gpr_free(service_account);
+}
+
+static const grpc_alts_credentials_options_vtable vtable = {
+ alts_client_options_copy, alts_client_options_destroy};
+
grpc_alts_credentials_options* grpc_alts_credentials_client_options_create(
void) {
- auto client_options = static_cast<grpc_alts_credentials_client_options*>(
- gpr_zalloc(sizeof(grpc_alts_credentials_client_options)));
- client_options->base.vtable = &vtable;
- return &client_options->base;
-}
-
-static grpc_alts_credentials_options* alts_client_options_copy(
- const grpc_alts_credentials_options* options) {
- if (options == nullptr) {
- return nullptr;
- }
- grpc_alts_credentials_options* new_options =
- grpc_alts_credentials_client_options_create();
- auto new_client_options =
- reinterpret_cast<grpc_alts_credentials_client_options*>(new_options);
- /* Copy target service accounts. */
- target_service_account* prev = nullptr;
- auto node =
- (reinterpret_cast<const grpc_alts_credentials_client_options*>(options))
- ->target_account_list_head;
- while (node != nullptr) {
- target_service_account* new_node =
- target_service_account_create(node->data);
- if (prev == nullptr) {
- new_client_options->target_account_list_head = new_node;
- } else {
- prev->next = new_node;
- }
- prev = new_node;
- node = node->next;
- }
- /* Copy rpc protocol versions. */
- grpc_gcp_rpc_protocol_versions_copy(&options->rpc_versions,
- &new_options->rpc_versions);
- return new_options;
-}
-
-static void alts_client_options_destroy(
- grpc_alts_credentials_options* options) {
- if (options == nullptr) {
- return;
- }
- auto* client_options =
- reinterpret_cast<grpc_alts_credentials_client_options*>(options);
- target_service_account* node = client_options->target_account_list_head;
- while (node != nullptr) {
- target_service_account* next_node = node->next;
- target_service_account_destroy(node);
- node = next_node;
- }
-}
+ auto client_options = static_cast<grpc_alts_credentials_client_options*>(
+ gpr_zalloc(sizeof(grpc_alts_credentials_client_options)));
+ client_options->base.vtable = &vtable;
+ return &client_options->base;
+}
+
+static grpc_alts_credentials_options* alts_client_options_copy(
+ const grpc_alts_credentials_options* options) {
+ if (options == nullptr) {
+ return nullptr;
+ }
+ grpc_alts_credentials_options* new_options =
+ grpc_alts_credentials_client_options_create();
+ auto new_client_options =
+ reinterpret_cast<grpc_alts_credentials_client_options*>(new_options);
+ /* Copy target service accounts. */
+ target_service_account* prev = nullptr;
+ auto node =
+ (reinterpret_cast<const grpc_alts_credentials_client_options*>(options))
+ ->target_account_list_head;
+ while (node != nullptr) {
+ target_service_account* new_node =
+ target_service_account_create(node->data);
+ if (prev == nullptr) {
+ new_client_options->target_account_list_head = new_node;
+ } else {
+ prev->next = new_node;
+ }
+ prev = new_node;
+ node = node->next;
+ }
+ /* Copy rpc protocol versions. */
+ grpc_gcp_rpc_protocol_versions_copy(&options->rpc_versions,
+ &new_options->rpc_versions);
+ return new_options;
+}
+
+static void alts_client_options_destroy(
+ grpc_alts_credentials_options* options) {
+ if (options == nullptr) {
+ return;
+ }
+ auto* client_options =
+ reinterpret_cast<grpc_alts_credentials_client_options*>(options);
+ target_service_account* node = client_options->target_account_list_head;
+ while (node != nullptr) {
+ target_service_account* next_node = node->next;
+ target_service_account_destroy(node);
+ node = next_node;
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc
index d4281715409..1ff9e3f01dd 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-grpc_alts_credentials_options* grpc_alts_credentials_options_copy(
- const grpc_alts_credentials_options* options) {
- if (options != nullptr && options->vtable != nullptr &&
- options->vtable->copy != nullptr) {
- return options->vtable->copy(options);
- }
- /* An error occurred. */
- gpr_log(GPR_ERROR,
- "Invalid arguments to grpc_alts_credentials_options_copy()");
- return nullptr;
-}
-
-void grpc_alts_credentials_options_destroy(
- grpc_alts_credentials_options* options) {
- if (options != nullptr) {
- if (options->vtable != nullptr && options->vtable->destruct != nullptr) {
- options->vtable->destruct(options);
- }
- gpr_free(options);
- }
-}
+/*
+ *
+ * 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/lib/security/credentials/alts/grpc_alts_credentials_options.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+grpc_alts_credentials_options* grpc_alts_credentials_options_copy(
+ const grpc_alts_credentials_options* options) {
+ if (options != nullptr && options->vtable != nullptr &&
+ options->vtable->copy != nullptr) {
+ return options->vtable->copy(options);
+ }
+ /* An error occurred. */
+ gpr_log(GPR_ERROR,
+ "Invalid arguments to grpc_alts_credentials_options_copy()");
+ return nullptr;
+}
+
+void grpc_alts_credentials_options_destroy(
+ grpc_alts_credentials_options* options) {
+ if (options != nullptr) {
+ if (options->vtable != nullptr && options->vtable->destruct != nullptr) {
+ options->vtable->destruct(options);
+ }
+ gpr_free(options);
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h
index 320af718bd3..c04a5a8c650 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h
@@ -1,75 +1,75 @@
-/*
- *
- * 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_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_H
-#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc_security.h>
-
-#include "src/core/tsi/alts/handshaker/transport_security_common_api.h"
-
-/* V-table for grpc_alts_credentials_options */
-typedef struct grpc_alts_credentials_options_vtable {
- grpc_alts_credentials_options* (*copy)(
- const grpc_alts_credentials_options* options);
- void (*destruct)(grpc_alts_credentials_options* options);
-} grpc_alts_credentials_options_vtable;
-
-struct grpc_alts_credentials_options {
- const struct grpc_alts_credentials_options_vtable* vtable;
- grpc_gcp_rpc_protocol_versions rpc_versions;
-};
-
-typedef struct target_service_account {
- struct target_service_account* next;
- char* data;
-} target_service_account;
-
-/**
- * Main struct for ALTS client credentials options. The options contain a
- * a list of target service accounts (if specified) used for secure naming
- * check.
- */
-typedef struct grpc_alts_credentials_client_options {
- grpc_alts_credentials_options base;
- target_service_account* target_account_list_head;
-} grpc_alts_credentials_client_options;
-
-/**
- * Main struct for ALTS server credentials options. The options currently
- * do not contain any server-specific fields.
- */
-typedef struct grpc_alts_credentials_server_options {
- grpc_alts_credentials_options base;
-} grpc_alts_credentials_server_options;
-
-/**
- * This method performs a deep copy on grpc_alts_credentials_options instance.
- *
- * - options: a grpc_alts_credentials_options instance that needs to be copied.
- *
- * It returns a new grpc_alts_credentials_options instance on success and NULL
- * on failure.
- */
-grpc_alts_credentials_options* grpc_alts_credentials_options_copy(
- const grpc_alts_credentials_options* options);
-
-#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_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_LIB_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_H
+#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc_security.h>
+
+#include "src/core/tsi/alts/handshaker/transport_security_common_api.h"
+
+/* V-table for grpc_alts_credentials_options */
+typedef struct grpc_alts_credentials_options_vtable {
+ grpc_alts_credentials_options* (*copy)(
+ const grpc_alts_credentials_options* options);
+ void (*destruct)(grpc_alts_credentials_options* options);
+} grpc_alts_credentials_options_vtable;
+
+struct grpc_alts_credentials_options {
+ const struct grpc_alts_credentials_options_vtable* vtable;
+ grpc_gcp_rpc_protocol_versions rpc_versions;
+};
+
+typedef struct target_service_account {
+ struct target_service_account* next;
+ char* data;
+} target_service_account;
+
+/**
+ * Main struct for ALTS client credentials options. The options contain a
+ * a list of target service accounts (if specified) used for secure naming
+ * check.
+ */
+typedef struct grpc_alts_credentials_client_options {
+ grpc_alts_credentials_options base;
+ target_service_account* target_account_list_head;
+} grpc_alts_credentials_client_options;
+
+/**
+ * Main struct for ALTS server credentials options. The options currently
+ * do not contain any server-specific fields.
+ */
+typedef struct grpc_alts_credentials_server_options {
+ grpc_alts_credentials_options base;
+} grpc_alts_credentials_server_options;
+
+/**
+ * This method performs a deep copy on grpc_alts_credentials_options instance.
+ *
+ * - options: a grpc_alts_credentials_options instance that needs to be copied.
+ *
+ * It returns a new grpc_alts_credentials_options instance on success and NULL
+ * on failure.
+ */
+grpc_alts_credentials_options* grpc_alts_credentials_options_copy(
+ const grpc_alts_credentials_options* options);
+
+#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_ALTS_GRPC_ALTS_CREDENTIALS_OPTIONS_H \
+ */
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 72c654211f1..2c1f1785722 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
@@ -1,59 +1,59 @@
-/*
- *
- * 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 <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
-#include "src/core/tsi/alts/handshaker/transport_security_common_api.h"
-
-static grpc_alts_credentials_options* alts_server_options_copy(
- const grpc_alts_credentials_options* options);
-
-static void alts_server_options_destroy(
+/*
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
+#include "src/core/tsi/alts/handshaker/transport_security_common_api.h"
+
+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*/) {}
-
-static const grpc_alts_credentials_options_vtable vtable = {
- alts_server_options_copy, alts_server_options_destroy};
-
+
+static const grpc_alts_credentials_options_vtable vtable = {
+ alts_server_options_copy, alts_server_options_destroy};
+
grpc_alts_credentials_options* grpc_alts_credentials_server_options_create(
void) {
- grpc_alts_credentials_server_options* server_options =
- static_cast<grpc_alts_credentials_server_options*>(
- gpr_zalloc(sizeof(*server_options)));
- server_options->base.vtable = &vtable;
- return &server_options->base;
-}
-
-static grpc_alts_credentials_options* alts_server_options_copy(
- const grpc_alts_credentials_options* options) {
- if (options == nullptr) {
- return nullptr;
- }
- grpc_alts_credentials_options* new_options =
- grpc_alts_credentials_server_options_create();
- /* Copy rpc protocol versions. */
- grpc_gcp_rpc_protocol_versions_copy(&options->rpc_versions,
- &new_options->rpc_versions);
- return new_options;
-}
+ grpc_alts_credentials_server_options* server_options =
+ static_cast<grpc_alts_credentials_server_options*>(
+ gpr_zalloc(sizeof(*server_options)));
+ server_options->base.vtable = &vtable;
+ return &server_options->base;
+}
+
+static grpc_alts_credentials_options* alts_server_options_copy(
+ const grpc_alts_credentials_options* options) {
+ if (options == nullptr) {
+ return nullptr;
+ }
+ grpc_alts_credentials_options* new_options =
+ grpc_alts_credentials_server_options_create();
+ /* Copy rpc protocol versions. */
+ grpc_gcp_rpc_protocol_versions_copy(&options->rpc_versions,
+ &new_options->rpc_versions);
+ return new_options;
+}
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 a6c82d47741..12811ce682d 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
@@ -1,41 +1,41 @@
-/*
- *
- * 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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/credentials/composite/composite_credentials.h"
-
+/*
+ *
+ * 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/security/credentials/composite/composite_credentials.h"
+
#include <cstring>
#include <new>
#include <vector>
-
+
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_join.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/polling_entity.h"
-#include "src/core/lib/surface/api_trace.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-/* -- Composite call credentials. -- */
-
+#include "src/core/lib/iomgr/polling_entity.h"
+#include "src/core/lib/surface/api_trace.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+/* -- Composite call credentials. -- */
+
static void composite_call_metadata_cb(void* arg, grpc_error* error);
namespace {
@@ -54,71 +54,71 @@ struct grpc_composite_call_credentials_metadata_context {
this, grpc_schedule_on_exec_ctx);
}
- grpc_composite_call_credentials* composite_creds;
+ grpc_composite_call_credentials* composite_creds;
size_t creds_index = 0;
- grpc_polling_entity* pollent;
- grpc_auth_metadata_context auth_md_context;
- grpc_credentials_mdelem_array* md_array;
- grpc_closure* on_request_metadata;
- grpc_closure internal_on_request_metadata;
+ grpc_polling_entity* pollent;
+ grpc_auth_metadata_context auth_md_context;
+ grpc_credentials_mdelem_array* md_array;
+ grpc_closure* on_request_metadata;
+ grpc_closure internal_on_request_metadata;
};
} // namespace
-
-static void composite_call_metadata_cb(void* arg, grpc_error* error) {
- grpc_composite_call_credentials_metadata_context* ctx =
- static_cast<grpc_composite_call_credentials_metadata_context*>(arg);
- if (error == GRPC_ERROR_NONE) {
+
+static void composite_call_metadata_cb(void* arg, grpc_error* error) {
+ grpc_composite_call_credentials_metadata_context* ctx =
+ static_cast<grpc_composite_call_credentials_metadata_context*>(arg);
+ if (error == GRPC_ERROR_NONE) {
const grpc_composite_call_credentials::CallCredentialsList& inner =
ctx->composite_creds->inner();
- /* See if we need to get some more metadata. */
+ /* See if we need to get some more metadata. */
if (ctx->creds_index < inner.size()) {
if (inner[ctx->creds_index++]->get_request_metadata(
ctx->pollent, ctx->auth_md_context, ctx->md_array,
- &ctx->internal_on_request_metadata, &error)) {
- // Synchronous response, so call ourselves recursively.
- composite_call_metadata_cb(arg, error);
- GRPC_ERROR_UNREF(error);
- }
- return;
- }
- // We're done!
- }
+ &ctx->internal_on_request_metadata, &error)) {
+ // Synchronous response, so call ourselves recursively.
+ composite_call_metadata_cb(arg, error);
+ GRPC_ERROR_UNREF(error);
+ }
+ return;
+ }
+ // We're done!
+ }
grpc_core::ExecCtx::Run(DEBUG_LOCATION, ctx->on_request_metadata,
GRPC_ERROR_REF(error));
delete ctx;
-}
-
+}
+
bool grpc_composite_call_credentials::get_request_metadata(
grpc_polling_entity* pollent, grpc_auth_metadata_context auth_md_context,
- grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata,
- grpc_error** error) {
- grpc_composite_call_credentials_metadata_context* ctx;
+ 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(
this, pollent, auth_md_context, md_array, on_request_metadata);
- bool synchronous = true;
+ bool synchronous = true;
const CallCredentialsList& inner = ctx->composite_creds->inner();
while (ctx->creds_index < inner.size()) {
if (inner[ctx->creds_index++]->get_request_metadata(
ctx->pollent, ctx->auth_md_context, ctx->md_array,
- &ctx->internal_on_request_metadata, error)) {
- if (*error != GRPC_ERROR_NONE) break;
- } else {
- synchronous = false; // Async return.
- break;
- }
- }
+ &ctx->internal_on_request_metadata, error)) {
+ if (*error != GRPC_ERROR_NONE) break;
+ } else {
+ synchronous = false; // Async return.
+ break;
+ }
+ }
if (synchronous) delete ctx;
- return synchronous;
-}
-
+ return synchronous;
+}
+
void grpc_composite_call_credentials::cancel_get_request_metadata(
grpc_credentials_mdelem_array* md_array, grpc_error* error) {
for (size_t i = 0; i < inner_.size(); ++i) {
inner_[i]->cancel_get_request_metadata(md_array, GRPC_ERROR_REF(error));
- }
- GRPC_ERROR_UNREF(error);
-}
-
+ }
+ GRPC_ERROR_UNREF(error);
+}
+
TString grpc_composite_call_credentials::debug_string() {
std::vector<TString> outputs;
for (auto& inner_cred : inner_) {
@@ -136,20 +136,20 @@ static size_t get_creds_array_size(const grpc_call_credentials* creds,
.size()
: 1;
}
-
+
void grpc_composite_call_credentials::push_to_inner(
grpc_core::RefCountedPtr<grpc_call_credentials> creds, bool is_composite) {
if (!is_composite) {
inner_.push_back(std::move(creds));
return;
- }
+ }
auto composite_creds =
static_cast<grpc_composite_call_credentials*>(creds.get());
for (size_t i = 0; i < composite_creds->inner().size(); ++i) {
inner_.push_back(std::move(composite_creds->inner_[i]));
}
-}
-
+}
+
grpc_composite_call_credentials::grpc_composite_call_credentials(
grpc_core::RefCountedPtr<grpc_call_credentials> creds1,
grpc_core::RefCountedPtr<grpc_call_credentials> creds2)
@@ -180,50 +180,50 @@ composite_call_credentials_create(
std::move(creds1), std::move(creds2));
}
-grpc_call_credentials* grpc_composite_call_credentials_create(
- grpc_call_credentials* creds1, grpc_call_credentials* creds2,
- void* reserved) {
- GRPC_API_TRACE(
- "grpc_composite_call_credentials_create(creds1=%p, creds2=%p, "
- "reserved=%p)",
- 3, (creds1, creds2, reserved));
- GPR_ASSERT(reserved == nullptr);
- GPR_ASSERT(creds1 != nullptr);
- GPR_ASSERT(creds2 != nullptr);
-
+grpc_call_credentials* grpc_composite_call_credentials_create(
+ grpc_call_credentials* creds1, grpc_call_credentials* creds2,
+ void* reserved) {
+ GRPC_API_TRACE(
+ "grpc_composite_call_credentials_create(creds1=%p, creds2=%p, "
+ "reserved=%p)",
+ 3, (creds1, creds2, reserved));
+ GPR_ASSERT(reserved == nullptr);
+ GPR_ASSERT(creds1 != nullptr);
+ GPR_ASSERT(creds2 != nullptr);
+
return composite_call_credentials_create(creds1->Ref(), creds2->Ref())
.release();
-}
-
-/* -- Composite channel credentials. -- */
-
+}
+
+/* -- Composite channel credentials. -- */
+
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_composite_channel_credentials::create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
- const char* target, const grpc_channel_args* args,
+ const char* target, const grpc_channel_args* args,
grpc_channel_args** new_args) {
GPR_ASSERT(inner_creds_ != nullptr && call_creds_ != nullptr);
- /* If we are passed a call_creds, create a call composite to pass it
- downstream. */
- if (call_creds != nullptr) {
+ /* If we are passed a call_creds, create a call composite to pass it
+ downstream. */
+ if (call_creds != nullptr) {
return inner_creds_->create_security_connector(
composite_call_credentials_create(call_creds_, std::move(call_creds)),
target, args, new_args);
- } else {
+ } else {
return inner_creds_->create_security_connector(call_creds_, target, args,
new_args);
- }
-}
-
-grpc_channel_credentials* grpc_composite_channel_credentials_create(
- grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds,
- void* reserved) {
- GPR_ASSERT(channel_creds != nullptr && call_creds != nullptr &&
- reserved == nullptr);
- GRPC_API_TRACE(
- "grpc_composite_channel_credentials_create(channel_creds=%p, "
- "call_creds=%p, reserved=%p)",
- 3, (channel_creds, call_creds, reserved));
+ }
+}
+
+grpc_channel_credentials* grpc_composite_channel_credentials_create(
+ grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds,
+ void* reserved) {
+ GPR_ASSERT(channel_creds != nullptr && call_creds != nullptr &&
+ reserved == nullptr);
+ GRPC_API_TRACE(
+ "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());
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h
index 5bebb9bd5ae..846c8825a6d 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_COMPOSITE_COMPOSITE_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_COMPOSITE_COMPOSITE_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include "y_absl/container/inlined_vector.h"
@@ -103,4 +103,4 @@ class grpc_composite_call_credentials : public grpc_call_credentials {
};
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_COMPOSITE_COMPOSITE_CREDENTIALS_H \
- */
+ */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc
index 90452d68d61..dc945833cc0 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc
@@ -1,162 +1,162 @@
-/*
- *
- * 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/security/credentials/credentials.h"
-
-#include <stdio.h>
-#include <string.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/http/httpcli.h"
-#include "src/core/lib/http/parser.h"
-#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/json/json.h"
-#include "src/core/lib/surface/api_trace.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>
-
-/* -- Common. -- */
-
-void grpc_channel_credentials_release(grpc_channel_credentials* creds) {
- GRPC_API_TRACE("grpc_channel_credentials_release(creds=%p)", 1, (creds));
- grpc_core::ExecCtx exec_ctx;
+/*
+ *
+ * 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/security/credentials/credentials.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/http/httpcli.h"
+#include "src/core/lib/http/parser.h"
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/json/json.h"
+#include "src/core/lib/surface/api_trace.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>
+
+/* -- Common. -- */
+
+void grpc_channel_credentials_release(grpc_channel_credentials* creds) {
+ GRPC_API_TRACE("grpc_channel_credentials_release(creds=%p)", 1, (creds));
+ grpc_core::ExecCtx exec_ctx;
if (creds) creds->Unref();
-}
-
-void grpc_call_credentials_release(grpc_call_credentials* creds) {
- GRPC_API_TRACE("grpc_call_credentials_release(creds=%p)", 1, (creds));
- grpc_core::ExecCtx exec_ctx;
+}
+
+void grpc_call_credentials_release(grpc_call_credentials* creds) {
+ GRPC_API_TRACE("grpc_call_credentials_release(creds=%p)", 1, (creds));
+ grpc_core::ExecCtx exec_ctx;
if (creds) creds->Unref();
-}
-
-static void credentials_pointer_arg_destroy(void* p) {
+}
+
+static void credentials_pointer_arg_destroy(void* p) {
static_cast<grpc_channel_credentials*>(p)->Unref();
-}
-
-static void* credentials_pointer_arg_copy(void* p) {
+}
+
+static void* credentials_pointer_arg_copy(void* p) {
return static_cast<grpc_channel_credentials*>(p)->Ref().release();
-}
-
-static int credentials_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
-
-static const grpc_arg_pointer_vtable credentials_pointer_vtable = {
- credentials_pointer_arg_copy, credentials_pointer_arg_destroy,
- credentials_pointer_cmp};
-
-grpc_arg grpc_channel_credentials_to_arg(
- grpc_channel_credentials* credentials) {
- return grpc_channel_arg_pointer_create((char*)GRPC_ARG_CHANNEL_CREDENTIALS,
- credentials,
- &credentials_pointer_vtable);
-}
-
-grpc_channel_credentials* grpc_channel_credentials_from_arg(
- const grpc_arg* arg) {
- if (strcmp(arg->key, GRPC_ARG_CHANNEL_CREDENTIALS)) return nullptr;
- if (arg->type != GRPC_ARG_POINTER) {
- gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
- GRPC_ARG_CHANNEL_CREDENTIALS);
- return nullptr;
- }
- return static_cast<grpc_channel_credentials*>(arg->value.pointer.p);
-}
-
-grpc_channel_credentials* grpc_channel_credentials_find_in_args(
- const grpc_channel_args* args) {
- size_t i;
- if (args == nullptr) return nullptr;
- for (i = 0; i < args->num_args; i++) {
- grpc_channel_credentials* credentials =
- grpc_channel_credentials_from_arg(&args->args[i]);
- if (credentials != nullptr) return credentials;
- }
- return nullptr;
-}
-
-void grpc_server_credentials_release(grpc_server_credentials* creds) {
- GRPC_API_TRACE("grpc_server_credentials_release(creds=%p)", 1, (creds));
- grpc_core::ExecCtx exec_ctx;
+}
+
+static int credentials_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); }
+
+static const grpc_arg_pointer_vtable credentials_pointer_vtable = {
+ credentials_pointer_arg_copy, credentials_pointer_arg_destroy,
+ credentials_pointer_cmp};
+
+grpc_arg grpc_channel_credentials_to_arg(
+ grpc_channel_credentials* credentials) {
+ return grpc_channel_arg_pointer_create((char*)GRPC_ARG_CHANNEL_CREDENTIALS,
+ credentials,
+ &credentials_pointer_vtable);
+}
+
+grpc_channel_credentials* grpc_channel_credentials_from_arg(
+ const grpc_arg* arg) {
+ if (strcmp(arg->key, GRPC_ARG_CHANNEL_CREDENTIALS)) return nullptr;
+ if (arg->type != GRPC_ARG_POINTER) {
+ gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
+ GRPC_ARG_CHANNEL_CREDENTIALS);
+ return nullptr;
+ }
+ return static_cast<grpc_channel_credentials*>(arg->value.pointer.p);
+}
+
+grpc_channel_credentials* grpc_channel_credentials_find_in_args(
+ const grpc_channel_args* args) {
+ size_t i;
+ if (args == nullptr) return nullptr;
+ for (i = 0; i < args->num_args; i++) {
+ grpc_channel_credentials* credentials =
+ grpc_channel_credentials_from_arg(&args->args[i]);
+ if (credentials != nullptr) return credentials;
+ }
+ return nullptr;
+}
+
+void grpc_server_credentials_release(grpc_server_credentials* creds) {
+ GRPC_API_TRACE("grpc_server_credentials_release(creds=%p)", 1, (creds));
+ grpc_core::ExecCtx exec_ctx;
if (creds) creds->Unref();
-}
-
+}
+
void grpc_server_credentials::set_auth_metadata_processor(
const grpc_auth_metadata_processor& processor) {
- GRPC_API_TRACE(
- "grpc_server_credentials_set_auth_metadata_processor("
- "creds=%p, "
- "processor=grpc_auth_metadata_processor { process: %p, state: %p })",
+ GRPC_API_TRACE(
+ "grpc_server_credentials_set_auth_metadata_processor("
+ "creds=%p, "
+ "processor=grpc_auth_metadata_processor { process: %p, state: %p })",
3, (this, (void*)(intptr_t)processor.process, processor.state));
DestroyProcessor();
processor_ = processor;
-}
-
+}
+
void grpc_server_credentials_set_auth_metadata_processor(
grpc_server_credentials* creds, grpc_auth_metadata_processor processor) {
GPR_DEBUG_ASSERT(creds != nullptr);
creds->set_auth_metadata_processor(processor);
}
-static void server_credentials_pointer_arg_destroy(void* p) {
+static void server_credentials_pointer_arg_destroy(void* p) {
static_cast<grpc_server_credentials*>(p)->Unref();
-}
-
-static void* server_credentials_pointer_arg_copy(void* p) {
+}
+
+static void* server_credentials_pointer_arg_copy(void* p) {
return static_cast<grpc_server_credentials*>(p)->Ref().release();
-}
-
-static int server_credentials_pointer_cmp(void* a, void* b) {
- return GPR_ICMP(a, b);
-}
-
-static const grpc_arg_pointer_vtable cred_ptr_vtable = {
- server_credentials_pointer_arg_copy, server_credentials_pointer_arg_destroy,
- server_credentials_pointer_cmp};
-
-grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* p) {
- return grpc_channel_arg_pointer_create((char*)GRPC_SERVER_CREDENTIALS_ARG, p,
- &cred_ptr_vtable);
-}
-
-grpc_server_credentials* grpc_server_credentials_from_arg(const grpc_arg* arg) {
- if (strcmp(arg->key, GRPC_SERVER_CREDENTIALS_ARG) != 0) return nullptr;
- if (arg->type != GRPC_ARG_POINTER) {
- gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
- GRPC_SERVER_CREDENTIALS_ARG);
- return nullptr;
- }
- return static_cast<grpc_server_credentials*>(arg->value.pointer.p);
-}
-
-grpc_server_credentials* grpc_find_server_credentials_in_args(
- const grpc_channel_args* args) {
- size_t i;
- if (args == nullptr) return nullptr;
- for (i = 0; i < args->num_args; i++) {
- grpc_server_credentials* p =
- grpc_server_credentials_from_arg(&args->args[i]);
- if (p != nullptr) return p;
- }
- return nullptr;
-}
+}
+
+static int server_credentials_pointer_cmp(void* a, void* b) {
+ return GPR_ICMP(a, b);
+}
+
+static const grpc_arg_pointer_vtable cred_ptr_vtable = {
+ server_credentials_pointer_arg_copy, server_credentials_pointer_arg_destroy,
+ server_credentials_pointer_cmp};
+
+grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* p) {
+ return grpc_channel_arg_pointer_create((char*)GRPC_SERVER_CREDENTIALS_ARG, p,
+ &cred_ptr_vtable);
+}
+
+grpc_server_credentials* grpc_server_credentials_from_arg(const grpc_arg* arg) {
+ if (strcmp(arg->key, GRPC_SERVER_CREDENTIALS_ARG) != 0) return nullptr;
+ if (arg->type != GRPC_ARG_POINTER) {
+ gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
+ GRPC_SERVER_CREDENTIALS_ARG);
+ return nullptr;
+ }
+ return static_cast<grpc_server_credentials*>(arg->value.pointer.p);
+}
+
+grpc_server_credentials* grpc_find_server_credentials_in_args(
+ const grpc_channel_args* args) {
+ size_t i;
+ if (args == nullptr) return nullptr;
+ for (i = 0; i < args->num_args; i++) {
+ grpc_server_credentials* p =
+ grpc_server_credentials_from_arg(&args->args[i]);
+ if (p != nullptr) return p;
+ }
+ return nullptr;
+}
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 15a85cbd0be..cc6f37423ee 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <string.h>
#include <util/generic/string.h>
@@ -34,7 +34,7 @@
#include "src/core/lib/http/httpcli.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/polling_entity.h"
-#include "src/core/lib/security/security_connector/security_connector.h"
+#include "src/core/lib/security/security_connector/security_connector.h"
struct grpc_http_response;
@@ -93,8 +93,8 @@ void grpc_override_well_known_credentials_path_getter(
/* --- grpc_channel_credentials. --- */
-#define GRPC_ARG_CHANNEL_CREDENTIALS "grpc.channel_credentials"
-
+#define GRPC_ARG_CHANNEL_CREDENTIALS "grpc.channel_credentials"
+
// This type is forward declared as a C struct and we cannot define it as a
// class. Otherwise, compiler will complain about type mismatch due to
// -Wmismatched-tags.
@@ -111,7 +111,7 @@ struct grpc_channel_credentials
virtual grpc_core::RefCountedPtr<grpc_channel_security_connector>
create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
- const char* target, const grpc_channel_args* args,
+ const char* target, const grpc_channel_args* args,
grpc_channel_args** new_args) = 0;
// Creates a version of the channel credentials without any attached call
@@ -137,33 +137,33 @@ struct grpc_channel_credentials
const char* type_;
};
-/* Util to encapsulate the channel credentials in a channel arg. */
-grpc_arg grpc_channel_credentials_to_arg(grpc_channel_credentials* credentials);
-
-/* Util to get the channel credentials from a channel arg. */
-grpc_channel_credentials* grpc_channel_credentials_from_arg(
- const grpc_arg* arg);
+/* Util to encapsulate the channel credentials in a channel arg. */
+grpc_arg grpc_channel_credentials_to_arg(grpc_channel_credentials* credentials);
-/* Util to find the channel credentials from channel args. */
-grpc_channel_credentials* grpc_channel_credentials_find_in_args(
- const grpc_channel_args* args);
-
-/* --- grpc_credentials_mdelem_array. --- */
+/* Util to get the channel credentials from a channel arg. */
+grpc_channel_credentials* grpc_channel_credentials_from_arg(
+ const grpc_arg* arg);
+/* Util to find the channel credentials from channel args. */
+grpc_channel_credentials* grpc_channel_credentials_find_in_args(
+ const grpc_channel_args* args);
+
+/* --- grpc_credentials_mdelem_array. --- */
+
struct grpc_credentials_mdelem_array {
grpc_mdelem* md = nullptr;
size_t size = 0;
};
-/// Takes a new ref to \a md.
-void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list,
- grpc_mdelem md);
-
-/// Appends all elements from \a src to \a dst, taking a new ref to each one.
-void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array* dst,
- grpc_credentials_mdelem_array* src);
+/// Takes a new ref to \a md.
+void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list,
+ grpc_mdelem md);
-void grpc_credentials_mdelem_array_destroy(grpc_credentials_mdelem_array* list);
+/// Appends all elements from \a src to \a dst, taking a new ref to each one.
+void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array* dst,
+ grpc_credentials_mdelem_array* src);
+void grpc_credentials_mdelem_array_destroy(grpc_credentials_mdelem_array* list);
+
/* --- grpc_call_credentials. --- */
// This type is forward declared as a C struct and we cannot define it as a
@@ -204,7 +204,7 @@ struct grpc_call_credentials
}
const char* type() const { return type_; }
-
+
private:
const char* type_;
const grpc_security_level min_security_level_;
@@ -212,8 +212,8 @@ struct grpc_call_credentials
/* Metadata-only credentials with the specified key and value where
asynchronicity can be simulated for testing. */
-grpc_call_credentials* grpc_md_only_test_credentials_create(
- const char* md_key, const char* md_value, bool is_async);
+grpc_call_credentials* grpc_md_only_test_credentials_create(
+ const char* md_key, const char* md_value, bool is_async);
/* --- grpc_server_credentials. --- */
@@ -252,10 +252,10 @@ struct grpc_server_credentials
#define GRPC_SERVER_CREDENTIALS_ARG "grpc.server_credentials"
-grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* c);
-grpc_server_credentials* grpc_server_credentials_from_arg(const grpc_arg* arg);
-grpc_server_credentials* grpc_find_server_credentials_in_args(
- const grpc_channel_args* args);
+grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* c);
+grpc_server_credentials* grpc_server_credentials_from_arg(const grpc_arg* arg);
+grpc_server_credentials* grpc_find_server_credentials_in_args(
+ const grpc_channel_args* args);
/* -- Credentials Metadata Request. -- */
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/credentials_metadata.cc b/contrib/libs/grpc/src/core/lib/security/credentials/credentials_metadata.cc
index 703de4aaafd..ddbfe52b022 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/credentials_metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/credentials_metadata.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/credentials/credentials.h"
-
-#include <grpc/support/alloc.h>
-
-#include <string.h>
-
-#include "src/core/lib/slice/slice_internal.h"
-
-static void mdelem_list_ensure_capacity(grpc_credentials_mdelem_array* list,
- size_t additional_space_needed) {
- size_t target_size = list->size + additional_space_needed;
- // Find the next power of two greater than the target size (i.e.,
- // whenever we add more space, we double what we already have).
- size_t new_size = 2;
- while (new_size < target_size) {
- new_size *= 2;
- }
- list->md = static_cast<grpc_mdelem*>(
- gpr_realloc(list->md, sizeof(grpc_mdelem) * new_size));
-}
-
-void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list,
- grpc_mdelem md) {
- mdelem_list_ensure_capacity(list, 1);
- list->md[list->size++] = GRPC_MDELEM_REF(md);
-}
-
-void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array* dst,
- grpc_credentials_mdelem_array* src) {
- mdelem_list_ensure_capacity(dst, src->size);
- for (size_t i = 0; i < src->size; ++i) {
- dst->md[dst->size++] = GRPC_MDELEM_REF(src->md[i]);
- }
-}
-
-void grpc_credentials_mdelem_array_destroy(
- grpc_credentials_mdelem_array* list) {
- for (size_t i = 0; i < list->size; ++i) {
- GRPC_MDELEM_UNREF(list->md[i]);
- }
- gpr_free(list->md);
-}
+/*
+ *
+ * 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/security/credentials/credentials.h"
+
+#include <grpc/support/alloc.h>
+
+#include <string.h>
+
+#include "src/core/lib/slice/slice_internal.h"
+
+static void mdelem_list_ensure_capacity(grpc_credentials_mdelem_array* list,
+ size_t additional_space_needed) {
+ size_t target_size = list->size + additional_space_needed;
+ // Find the next power of two greater than the target size (i.e.,
+ // whenever we add more space, we double what we already have).
+ size_t new_size = 2;
+ while (new_size < target_size) {
+ new_size *= 2;
+ }
+ list->md = static_cast<grpc_mdelem*>(
+ gpr_realloc(list->md, sizeof(grpc_mdelem) * new_size));
+}
+
+void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list,
+ grpc_mdelem md) {
+ mdelem_list_ensure_capacity(list, 1);
+ list->md[list->size++] = GRPC_MDELEM_REF(md);
+}
+
+void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array* dst,
+ grpc_credentials_mdelem_array* src) {
+ mdelem_list_ensure_capacity(dst, src->size);
+ for (size_t i = 0; i < src->size; ++i) {
+ dst->md[dst->size++] = GRPC_MDELEM_REF(src->md[i]);
+ }
+}
+
+void grpc_credentials_mdelem_array_destroy(
+ grpc_credentials_mdelem_array* list) {
+ for (size_t i = 0; i < list->size; ++i) {
+ GRPC_MDELEM_UNREF(list->md[i]);
+ }
+ gpr_free(list->md);
+}
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 8fd0493ee44..05af6dad448 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
@@ -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/security/credentials/fake/fake_credentials.h"
-
-#include <string.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/gpr/string.h"
-#include "src/core/lib/iomgr/executor.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/security/credentials/fake/fake_credentials.h"
+
+#include <string.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/gpr/string.h"
+#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/security/security_connector/fake/fake_security_connector.h"
-
-/* -- Fake transport security credentials. -- */
-
+
+/* -- Fake transport security credentials. -- */
+
namespace {
class grpc_fake_channel_credentials final : public grpc_channel_credentials {
public:
@@ -40,7 +40,7 @@ class grpc_fake_channel_credentials final : public grpc_channel_credentials {
: grpc_channel_credentials(
GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY) {}
~grpc_fake_channel_credentials() override = default;
-
+
grpc_core::RefCountedPtr<grpc_channel_security_connector>
create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
@@ -50,44 +50,44 @@ class grpc_fake_channel_credentials final : public grpc_channel_credentials {
this->Ref(), std::move(call_creds), target, args);
}
};
-
+
class grpc_fake_server_credentials final : public grpc_server_credentials {
public:
grpc_fake_server_credentials()
: grpc_server_credentials(
GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY) {}
~grpc_fake_server_credentials() override = default;
-
+
grpc_core::RefCountedPtr<grpc_server_security_connector>
create_security_connector() override {
return grpc_fake_server_security_connector_create(this->Ref());
}
};
} // namespace
-
+
grpc_channel_credentials* grpc_fake_transport_security_credentials_create() {
return new grpc_fake_channel_credentials();
-}
-
+}
+
grpc_server_credentials*
grpc_fake_transport_security_server_credentials_create() {
return new grpc_fake_server_credentials();
-}
-
-grpc_arg grpc_fake_transport_expected_targets_arg(char* expected_targets) {
- return grpc_channel_arg_string_create(
- (char*)GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
-}
-
-const char* grpc_fake_transport_get_expected_targets(
- const grpc_channel_args* args) {
- const grpc_arg* expected_target_arg =
- grpc_channel_args_find(args, GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS);
- return grpc_channel_arg_get_string(expected_target_arg);
-}
-
-/* -- Metadata-only test credentials. -- */
-
+}
+
+grpc_arg grpc_fake_transport_expected_targets_arg(char* expected_targets) {
+ return grpc_channel_arg_string_create(
+ (char*)GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets);
+}
+
+const char* grpc_fake_transport_get_expected_targets(
+ const grpc_channel_args* args) {
+ const grpc_arg* expected_target_arg =
+ grpc_channel_args_find(args, GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS);
+ return grpc_channel_arg_get_string(expected_target_arg);
+}
+
+/* -- Metadata-only test credentials. -- */
+
bool grpc_md_only_test_credentials::get_request_metadata(
grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/,
grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata,
@@ -96,17 +96,17 @@ bool grpc_md_only_test_credentials::get_request_metadata(
if (is_async_) {
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_request_metadata,
GRPC_ERROR_NONE);
- return false;
- }
- return true;
-}
-
+ return false;
+ }
+ return true;
+}
+
void grpc_md_only_test_credentials::cancel_get_request_metadata(
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) {
+ 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);
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h
index 27f3a284515..a4e11825e81 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h
@@ -1,60 +1,60 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_FAKE_FAKE_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_FAKE_FAKE_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <string.h>
#include "src/core/lib/security/credentials/credentials.h"
-#define GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS \
- "grpc.fake_security.expected_targets"
-
+#define GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS \
+ "grpc.fake_security.expected_targets"
+
/* -- Fake transport security credentials. -- */
/* Creates a fake transport security credentials object for testing. */
-grpc_channel_credentials* grpc_fake_transport_security_credentials_create(void);
+grpc_channel_credentials* grpc_fake_transport_security_credentials_create(void);
/* Creates a fake server transport security credentials object for testing. */
-grpc_server_credentials* grpc_fake_transport_security_server_credentials_create(
+grpc_server_credentials* grpc_fake_transport_security_server_credentials_create(
void);
-/* Used to verify the target names given to the fake transport security
- * connector.
- *
- * The syntax of \a expected_targets by example:
- * For LB channels:
- * "backend_target_1,backend_target_2,...;lb_target_1,lb_target_2,..."
- * For regular channels:
- * "backend_taget_1,backend_target_2,..."
- *
- * That is to say, LB channels have a heading list of LB targets separated from
- * the list of backend targets by a semicolon. For non-LB channels, only the
- * latter is present. */
-grpc_arg grpc_fake_transport_expected_targets_arg(char* expected_targets);
-
-/* Return the value associated with the expected targets channel arg or NULL */
-const char* grpc_fake_transport_get_expected_targets(
- const grpc_channel_args* args);
-
+/* Used to verify the target names given to the fake transport security
+ * connector.
+ *
+ * The syntax of \a expected_targets by example:
+ * For LB channels:
+ * "backend_target_1,backend_target_2,...;lb_target_1,lb_target_2,..."
+ * For regular channels:
+ * "backend_taget_1,backend_target_2,..."
+ *
+ * That is to say, LB channels have a heading list of LB targets separated from
+ * the list of backend targets by a semicolon. For non-LB channels, only the
+ * latter is present. */
+grpc_arg grpc_fake_transport_expected_targets_arg(char* expected_targets);
+
+/* Return the value associated with the expected targets channel arg or NULL */
+const char* grpc_fake_transport_get_expected_targets(
+ const grpc_channel_args* args);
+
/* -- Metadata-only Test credentials. -- */
class grpc_md_only_test_credentials : public grpc_call_credentials {
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/credentials_generic.cc b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/credentials_generic.cc
index e8b9bbdadc7..244ed6d67c8 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/credentials_generic.cc
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/credentials_generic.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/credentials/google_default/google_default_credentials.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/security/credentials/google_default/google_default_credentials.h"
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/env.h"
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/env.h"
+
TString grpc_get_well_known_google_credentials_file_path_impl(void) {
- char* base = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR);
- if (base == nullptr) {
- gpr_log(GPR_ERROR, "Could not get " GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR
- " environment variable.");
+ char* base = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR);
+ if (base == nullptr) {
+ gpr_log(GPR_ERROR, "Could not get " GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR
+ " environment variable.");
return "";
- }
+ }
TString result =
y_absl::StrCat(base, "/", GRPC_GOOGLE_CREDENTIALS_PATH_SUFFIX);
- gpr_free(base);
- return result;
-}
+ gpr_free(base);
+ return result;
+}
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 8f3ca009a59..760e677eb1c 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
@@ -1,79 +1,79 @@
-/*
- *
- * 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/security/credentials/credentials.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.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/security/credentials/credentials.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
#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/gpr/env.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/http/httpcli.h"
-#include "src/core/lib/http/parser.h"
-#include "src/core/lib/iomgr/load_file.h"
-#include "src/core/lib/iomgr/polling_entity.h"
+#include "src/core/lib/http/httpcli.h"
+#include "src/core/lib/http/parser.h"
+#include "src/core/lib/iomgr/load_file.h"
+#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/security/credentials/alts/alts_credentials.h"
#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
-#include "src/core/lib/security/credentials/google_default/google_default_credentials.h"
-#include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
-#include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/api_trace.h"
-
+#include "src/core/lib/security/credentials/google_default/google_default_credentials.h"
+#include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
+#include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/surface/api_trace.h"
+
using grpc_core::Json;
-/* -- Constants. -- */
-
+/* -- Constants. -- */
+
#define GRPC_COMPUTE_ENGINE_DETECTION_HOST "metadata.google.internal."
#define GRPC_GOOGLE_CREDENTIAL_CREATION_ERROR \
"Failed to create Google credentials"
-
-/* -- Default credentials. -- */
-
+
+/* -- Default credentials. -- */
+
/* A sticky bit that will be set only if the result of metadata server detection
* is positive. We do not set the bit if the result is negative. Because it
* means the detection is done via network test that is unreliable and the
* unreliable result should not be referred by successive calls. */
static int g_metadata_server_available = 0;
-static gpr_mu g_state_mu;
+static gpr_mu g_state_mu;
/* Protect a metadata_server_detector instance that can be modified by more than
* one gRPC threads */
-static gpr_mu* g_polling_mu;
-static gpr_once g_once = GPR_ONCE_INIT;
+static gpr_mu* g_polling_mu;
+static gpr_once g_once = GPR_ONCE_INIT;
static grpc_core::internal::grpc_gce_tenancy_checker g_gce_tenancy_checker =
grpc_alts_is_running_on_gcp;
-
-static void init_default_credentials(void) { gpr_mu_init(&g_state_mu); }
-
+
+static void init_default_credentials(void) { gpr_mu_init(&g_state_mu); }
+
struct metadata_server_detector {
- grpc_polling_entity pollent;
- int is_done;
- int success;
- grpc_http_response response;
+ grpc_polling_entity pollent;
+ int is_done;
+ int success;
+ grpc_http_response response;
};
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_google_default_channel_credentials::create_security_connector(
@@ -133,151 +133,151 @@ static void on_metadata_server_detection_http_response(void* user_data,
grpc_error* error) {
metadata_server_detector* detector =
static_cast<metadata_server_detector*>(user_data);
- if (error == GRPC_ERROR_NONE && detector->response.status == 200 &&
- detector->response.hdr_count > 0) {
- /* Internet providers can return a generic response to all requests, so
- it is necessary to check that metadata header is present also. */
- size_t i;
- for (i = 0; i < detector->response.hdr_count; i++) {
- grpc_http_header* header = &detector->response.hdrs[i];
- if (strcmp(header->key, "Metadata-Flavor") == 0 &&
- strcmp(header->value, "Google") == 0) {
- detector->success = 1;
- break;
- }
- }
- }
- gpr_mu_lock(g_polling_mu);
- detector->is_done = 1;
- GRPC_LOG_IF_ERROR(
- "Pollset kick",
- grpc_pollset_kick(grpc_polling_entity_pollset(&detector->pollent),
- nullptr));
- gpr_mu_unlock(g_polling_mu);
-}
-
+ if (error == GRPC_ERROR_NONE && detector->response.status == 200 &&
+ detector->response.hdr_count > 0) {
+ /* Internet providers can return a generic response to all requests, so
+ it is necessary to check that metadata header is present also. */
+ size_t i;
+ for (i = 0; i < detector->response.hdr_count; i++) {
+ grpc_http_header* header = &detector->response.hdrs[i];
+ if (strcmp(header->key, "Metadata-Flavor") == 0 &&
+ strcmp(header->value, "Google") == 0) {
+ detector->success = 1;
+ break;
+ }
+ }
+ }
+ gpr_mu_lock(g_polling_mu);
+ detector->is_done = 1;
+ GRPC_LOG_IF_ERROR(
+ "Pollset kick",
+ grpc_pollset_kick(grpc_polling_entity_pollset(&detector->pollent),
+ nullptr));
+ gpr_mu_unlock(g_polling_mu);
+}
+
static void destroy_pollset(void* p, grpc_error* /*e*/) {
- grpc_pollset_destroy(static_cast<grpc_pollset*>(p));
-}
-
+ grpc_pollset_destroy(static_cast<grpc_pollset*>(p));
+}
+
static int is_metadata_server_reachable() {
metadata_server_detector detector;
- grpc_httpcli_request request;
- grpc_httpcli_context context;
- grpc_closure destroy_closure;
- /* The http call is local. If it takes more than one sec, it is for sure not
- on compute engine. */
- grpc_millis max_detection_delay = GPR_MS_PER_SEC;
- grpc_pollset* pollset =
- static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
- grpc_pollset_init(pollset, &g_polling_mu);
- detector.pollent = grpc_polling_entity_create_from_pollset(pollset);
- detector.is_done = 0;
- detector.success = 0;
- memset(&request, 0, sizeof(grpc_httpcli_request));
- request.host = (char*)GRPC_COMPUTE_ENGINE_DETECTION_HOST;
- request.http.path = (char*)"/";
- grpc_httpcli_context_init(&context);
- grpc_resource_quota* resource_quota =
- grpc_resource_quota_create("google_default_credentials");
- grpc_httpcli_get(
- &context, &detector.pollent, resource_quota, &request,
- grpc_core::ExecCtx::Get()->Now() + max_detection_delay,
+ grpc_httpcli_request request;
+ grpc_httpcli_context context;
+ grpc_closure destroy_closure;
+ /* The http call is local. If it takes more than one sec, it is for sure not
+ on compute engine. */
+ grpc_millis max_detection_delay = GPR_MS_PER_SEC;
+ grpc_pollset* pollset =
+ static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
+ grpc_pollset_init(pollset, &g_polling_mu);
+ detector.pollent = grpc_polling_entity_create_from_pollset(pollset);
+ detector.is_done = 0;
+ detector.success = 0;
+ memset(&request, 0, sizeof(grpc_httpcli_request));
+ request.host = (char*)GRPC_COMPUTE_ENGINE_DETECTION_HOST;
+ request.http.path = (char*)"/";
+ grpc_httpcli_context_init(&context);
+ grpc_resource_quota* resource_quota =
+ grpc_resource_quota_create("google_default_credentials");
+ grpc_httpcli_get(
+ &context, &detector.pollent, resource_quota, &request,
+ grpc_core::ExecCtx::Get()->Now() + max_detection_delay,
GRPC_CLOSURE_CREATE(on_metadata_server_detection_http_response, &detector,
- grpc_schedule_on_exec_ctx),
- &detector.response);
- grpc_resource_quota_unref_internal(resource_quota);
- grpc_core::ExecCtx::Get()->Flush();
- /* Block until we get the response. This is not ideal but this should only be
+ grpc_schedule_on_exec_ctx),
+ &detector.response);
+ grpc_resource_quota_unref_internal(resource_quota);
+ grpc_core::ExecCtx::Get()->Flush();
+ /* Block until we get the response. This is not ideal but this should only be
called once for the lifetime of the process by the default credentials. */
- gpr_mu_lock(g_polling_mu);
- while (!detector.is_done) {
- grpc_pollset_worker* worker = nullptr;
- if (!GRPC_LOG_IF_ERROR(
- "pollset_work",
- grpc_pollset_work(grpc_polling_entity_pollset(&detector.pollent),
- &worker, GRPC_MILLIS_INF_FUTURE))) {
- detector.is_done = 1;
- detector.success = 0;
- }
- }
- gpr_mu_unlock(g_polling_mu);
- grpc_httpcli_context_destroy(&context);
- GRPC_CLOSURE_INIT(&destroy_closure, destroy_pollset,
- grpc_polling_entity_pollset(&detector.pollent),
- grpc_schedule_on_exec_ctx);
- grpc_pollset_shutdown(grpc_polling_entity_pollset(&detector.pollent),
- &destroy_closure);
- g_polling_mu = nullptr;
- grpc_core::ExecCtx::Get()->Flush();
- gpr_free(grpc_polling_entity_pollset(&detector.pollent));
- grpc_http_response_destroy(&detector.response);
- return detector.success;
-}
-
-/* Takes ownership of creds_path if not NULL. */
-static grpc_error* create_default_creds_from_path(
+ gpr_mu_lock(g_polling_mu);
+ while (!detector.is_done) {
+ grpc_pollset_worker* worker = nullptr;
+ if (!GRPC_LOG_IF_ERROR(
+ "pollset_work",
+ grpc_pollset_work(grpc_polling_entity_pollset(&detector.pollent),
+ &worker, GRPC_MILLIS_INF_FUTURE))) {
+ detector.is_done = 1;
+ detector.success = 0;
+ }
+ }
+ gpr_mu_unlock(g_polling_mu);
+ grpc_httpcli_context_destroy(&context);
+ GRPC_CLOSURE_INIT(&destroy_closure, destroy_pollset,
+ grpc_polling_entity_pollset(&detector.pollent),
+ grpc_schedule_on_exec_ctx);
+ grpc_pollset_shutdown(grpc_polling_entity_pollset(&detector.pollent),
+ &destroy_closure);
+ g_polling_mu = nullptr;
+ grpc_core::ExecCtx::Get()->Flush();
+ gpr_free(grpc_polling_entity_pollset(&detector.pollent));
+ grpc_http_response_destroy(&detector.response);
+ return detector.success;
+}
+
+/* Takes ownership of creds_path if not NULL. */
+static grpc_error* create_default_creds_from_path(
const TString& creds_path,
grpc_core::RefCountedPtr<grpc_call_credentials>* creds) {
- grpc_auth_json_key key;
- grpc_auth_refresh_token token;
+ grpc_auth_json_key key;
+ grpc_auth_refresh_token token;
grpc_core::RefCountedPtr<grpc_call_credentials> result;
- grpc_slice creds_data = grpc_empty_slice();
- grpc_error* error = GRPC_ERROR_NONE;
+ grpc_slice creds_data = grpc_empty_slice();
+ grpc_error* error = GRPC_ERROR_NONE;
Json json;
if (creds_path.empty()) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("creds_path unset");
- goto end;
- }
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("creds_path unset");
+ goto end;
+ }
error = grpc_load_file(creds_path.c_str(), 0, &creds_data);
if (error != GRPC_ERROR_NONE) goto end;
json = Json::Parse(grpc_core::StringViewFromSlice(creds_data), &error);
if (error != GRPC_ERROR_NONE) goto end;
if (json.type() != Json::Type::OBJECT) {
- error = grpc_error_set_str(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to parse JSON"),
- GRPC_ERROR_STR_RAW_BYTES, grpc_slice_ref_internal(creds_data));
- goto end;
- }
-
- /* First, try an auth json key. */
- key = grpc_auth_json_key_create_from_json(json);
- if (grpc_auth_json_key_is_valid(&key)) {
- result =
- grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
- key, grpc_max_auth_token_lifetime());
- if (result == nullptr) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "grpc_service_account_jwt_access_credentials_create_from_auth_json_"
- "key failed");
- }
- goto end;
- }
-
- /* Then try a refresh token if the auth json key was invalid. */
- token = grpc_auth_refresh_token_create_from_json(json);
- if (grpc_auth_refresh_token_is_valid(&token)) {
- result =
- grpc_refresh_token_credentials_create_from_auth_refresh_token(token);
- if (result == nullptr) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "grpc_refresh_token_credentials_create_from_auth_refresh_token "
- "failed");
- }
- goto end;
- }
-
-end:
- GPR_ASSERT((result == nullptr) + (error == GRPC_ERROR_NONE) == 1);
- grpc_slice_unref_internal(creds_data);
- *creds = result;
- return error;
-}
-
+ error = grpc_error_set_str(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to parse JSON"),
+ GRPC_ERROR_STR_RAW_BYTES, grpc_slice_ref_internal(creds_data));
+ goto end;
+ }
+
+ /* First, try an auth json key. */
+ key = grpc_auth_json_key_create_from_json(json);
+ if (grpc_auth_json_key_is_valid(&key)) {
+ result =
+ grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
+ key, grpc_max_auth_token_lifetime());
+ if (result == nullptr) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "grpc_service_account_jwt_access_credentials_create_from_auth_json_"
+ "key failed");
+ }
+ goto end;
+ }
+
+ /* Then try a refresh token if the auth json key was invalid. */
+ token = grpc_auth_refresh_token_create_from_json(json);
+ if (grpc_auth_refresh_token_is_valid(&token)) {
+ result =
+ grpc_refresh_token_credentials_create_from_auth_refresh_token(token);
+ if (result == nullptr) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "grpc_refresh_token_credentials_create_from_auth_refresh_token "
+ "failed");
+ }
+ goto end;
+ }
+
+end:
+ GPR_ASSERT((result == nullptr) + (error == GRPC_ERROR_NONE) == 1);
+ grpc_slice_unref_internal(creds_data);
+ *creds = result;
+ return error;
+}
+
static void update_tenancy() {
- gpr_once_init(&g_once, init_default_credentials);
+ gpr_once_init(&g_once, init_default_credentials);
grpc_core::MutexLock lock(&g_state_mu);
-
+
/* Try a platform-provided hint for GCE. */
if (!g_metadata_server_available) {
g_metadata_server_available = g_gce_tenancy_checker();
@@ -326,9 +326,9 @@ static grpc_core::RefCountedPtr<grpc_call_credentials> make_default_call_creds(
*error = grpc_error_add_child(
*error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Failed to get credentials from network"));
- }
- }
-
+ }
+ }
+
return call_creds;
}
@@ -363,14 +363,14 @@ grpc_channel_credentials* grpc_google_default_credentials_create(
result = grpc_composite_channel_credentials_create(
creds.get(), call_creds.get(), nullptr);
GPR_ASSERT(result != nullptr);
- } else {
+ } else {
gpr_log(GPR_ERROR, "Could not create google default credentials: %s",
grpc_error_string(error));
- }
+ }
GRPC_ERROR_UNREF(error);
- return result;
-}
-
+ return result;
+}
+
namespace grpc_core {
namespace internal {
@@ -378,27 +378,27 @@ void set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker) {
g_gce_tenancy_checker = checker;
}
-void grpc_flush_cached_google_default_credentials(void) {
- grpc_core::ExecCtx exec_ctx;
- gpr_once_init(&g_once, init_default_credentials);
- gpr_mu_lock(&g_state_mu);
+void grpc_flush_cached_google_default_credentials(void) {
+ grpc_core::ExecCtx exec_ctx;
+ gpr_once_init(&g_once, init_default_credentials);
+ gpr_mu_lock(&g_state_mu);
g_metadata_server_available = 0;
- gpr_mu_unlock(&g_state_mu);
-}
-
+ gpr_mu_unlock(&g_state_mu);
+}
+
} // namespace internal
} // namespace grpc_core
-/* -- Well known credentials path. -- */
-
-static grpc_well_known_credentials_path_getter creds_path_getter = nullptr;
-
+/* -- Well known credentials path. -- */
+
+static grpc_well_known_credentials_path_getter creds_path_getter = nullptr;
+
TString grpc_get_well_known_google_credentials_file_path(void) {
- if (creds_path_getter != nullptr) return creds_path_getter();
- return grpc_get_well_known_google_credentials_file_path_impl();
-}
-
-void grpc_override_well_known_credentials_path_getter(
- grpc_well_known_credentials_path_getter getter) {
- creds_path_getter = getter;
-}
+ if (creds_path_getter != nullptr) return creds_path_getter();
+ return grpc_get_well_known_google_credentials_file_path_impl();
+}
+
+void grpc_override_well_known_credentials_path_getter(
+ grpc_well_known_credentials_path_getter getter) {
+ creds_path_getter = getter;
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h
index 8a945da31e2..0ba20064a2f 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -84,4 +84,4 @@ void grpc_flush_cached_google_default_credentials(void);
} // namespace grpc_core
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_GOOGLE_DEFAULT_GOOGLE_DEFAULT_CREDENTIALS_H \
- */
+ */
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 a03e4970b8e..9e571266d5b 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
@@ -1,51 +1,51 @@
-/*
- *
- * 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/security/credentials/iam/iam_credentials.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.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/security/credentials/iam/iam_credentials.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+
#include "y_absl/strings/str_format.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/surface/api_trace.h"
grpc_google_iam_credentials::~grpc_google_iam_credentials() {
grpc_credentials_mdelem_array_destroy(&md_array_);
-}
-
+}
+
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_credentials_mdelem_array_append(md_array, &md_array_);
- return true;
-}
-
+ return true;
+}
+
void grpc_google_iam_credentials::cancel_get_request_metadata(
grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
- GRPC_ERROR_UNREF(error);
-}
-
+ GRPC_ERROR_UNREF(error);
+}
+
grpc_google_iam_credentials::grpc_google_iam_credentials(
const char* token, const char* authority_selector)
: grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_IAM),
@@ -63,18 +63,18 @@ grpc_google_iam_credentials::grpc_google_iam_credentials(
grpc_credentials_mdelem_array_add(&md_array_, md);
GRPC_MDELEM_UNREF(md);
}
-
-grpc_call_credentials* grpc_google_iam_credentials_create(
- const char* token, const char* authority_selector, void* reserved) {
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE(
- "grpc_iam_credentials_create(token=%s, authority_selector=%s, "
- "reserved=%p)",
- 3, (token, authority_selector, reserved));
- GPR_ASSERT(reserved == nullptr);
- GPR_ASSERT(token != nullptr);
- GPR_ASSERT(authority_selector != nullptr);
+
+grpc_call_credentials* grpc_google_iam_credentials_create(
+ const char* token, const char* authority_selector, void* reserved) {
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE(
+ "grpc_iam_credentials_create(token=%s, authority_selector=%s, "
+ "reserved=%p)",
+ 3, (token, authority_selector, reserved));
+ GPR_ASSERT(reserved == nullptr);
+ GPR_ASSERT(token != nullptr);
+ GPR_ASSERT(authority_selector != nullptr);
return grpc_core::MakeRefCounted<grpc_google_iam_credentials>(
token, authority_selector)
.release();
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h
index 76b6acfa281..cd84de4e72c 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_IAM_IAM_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_IAM_IAM_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include "src/core/lib/security/credentials/credentials.h"
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 c0c5b52782b..b5b3f0f6285 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
@@ -1,159 +1,159 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/iomgr/error.h"
-#include "src/core/lib/security/credentials/jwt/json_token.h"
-
-#include <string.h>
-
-#include <grpc/grpc_security.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/lib/gpr/string.h"
-#include "src/core/lib/security/util/json_util.h"
-#include "src/core/lib/slice/b64.h"
-
-extern "C" {
-#include <openssl/bio.h>
-#include <openssl/evp.h>
-#include <openssl/pem.h>
-}
-
+#include "src/core/lib/security/credentials/jwt/json_token.h"
+
+#include <string.h>
+
+#include <grpc/grpc_security.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/lib/gpr/string.h"
+#include "src/core/lib/security/util/json_util.h"
+#include "src/core/lib/slice/b64.h"
+
+extern "C" {
+#include <openssl/bio.h>
+#include <openssl/evp.h>
+#include <openssl/pem.h>
+}
+
using grpc_core::Json;
-/* --- Constants. --- */
-
-/* 1 hour max. */
-gpr_timespec grpc_max_auth_token_lifetime() {
- gpr_timespec out;
- out.tv_sec = 3600;
- out.tv_nsec = 0;
- out.clock_type = GPR_TIMESPAN;
- return out;
-}
-
-#define GRPC_JWT_RSA_SHA256_ALGORITHM "RS256"
-#define GRPC_JWT_TYPE "JWT"
-
-/* --- Override for testing. --- */
-
-static grpc_jwt_encode_and_sign_override g_jwt_encode_and_sign_override =
- nullptr;
-
-/* --- grpc_auth_json_key. --- */
-
-int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key) {
- return (json_key != nullptr) &&
- strcmp(json_key->type, GRPC_AUTH_JSON_TYPE_INVALID);
-}
-
+/* --- Constants. --- */
+
+/* 1 hour max. */
+gpr_timespec grpc_max_auth_token_lifetime() {
+ gpr_timespec out;
+ out.tv_sec = 3600;
+ out.tv_nsec = 0;
+ out.clock_type = GPR_TIMESPAN;
+ return out;
+}
+
+#define GRPC_JWT_RSA_SHA256_ALGORITHM "RS256"
+#define GRPC_JWT_TYPE "JWT"
+
+/* --- Override for testing. --- */
+
+static grpc_jwt_encode_and_sign_override g_jwt_encode_and_sign_override =
+ nullptr;
+
+/* --- grpc_auth_json_key. --- */
+
+int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key) {
+ return (json_key != nullptr) &&
+ strcmp(json_key->type, GRPC_AUTH_JSON_TYPE_INVALID);
+}
+
grpc_auth_json_key grpc_auth_json_key_create_from_json(const Json& json) {
- grpc_auth_json_key result;
- BIO* bio = nullptr;
- const char* prop_value;
- int success = 0;
+ grpc_auth_json_key result;
+ BIO* bio = nullptr;
+ const char* prop_value;
+ int success = 0;
grpc_error* error = GRPC_ERROR_NONE;
-
- memset(&result, 0, sizeof(grpc_auth_json_key));
- result.type = GRPC_AUTH_JSON_TYPE_INVALID;
+
+ memset(&result, 0, sizeof(grpc_auth_json_key));
+ result.type = GRPC_AUTH_JSON_TYPE_INVALID;
if (json.type() == Json::Type::JSON_NULL) {
- gpr_log(GPR_ERROR, "Invalid json.");
- goto end;
- }
-
+ gpr_log(GPR_ERROR, "Invalid json.");
+ goto end;
+ }
+
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;
- }
- result.type = GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT;
-
- if (!grpc_copy_json_string_property(json, "private_key_id",
- &result.private_key_id) ||
- !grpc_copy_json_string_property(json, "client_id", &result.client_id) ||
- !grpc_copy_json_string_property(json, "client_email",
- &result.client_email)) {
- goto end;
- }
-
+ if (prop_value == nullptr ||
+ strcmp(prop_value, GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT)) {
+ goto end;
+ }
+ result.type = GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT;
+
+ if (!grpc_copy_json_string_property(json, "private_key_id",
+ &result.private_key_id) ||
+ !grpc_copy_json_string_property(json, "client_id", &result.client_id) ||
+ !grpc_copy_json_string_property(json, "client_email",
+ &result.client_email)) {
+ goto end;
+ }
+
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;
- }
- bio = BIO_new(BIO_s_mem());
- success = BIO_puts(bio, prop_value);
- if ((success < 0) || (static_cast<size_t>(success) != strlen(prop_value))) {
- gpr_log(GPR_ERROR, "Could not write into openssl BIO.");
- goto end;
- }
- result.private_key =
- PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, (void*)"");
- if (result.private_key == nullptr) {
- gpr_log(GPR_ERROR, "Could not deserialize private key.");
- goto end;
- }
- success = 1;
-
-end:
- if (bio != nullptr) BIO_free(bio);
- if (!success) grpc_auth_json_key_destruct(&result);
- return result;
-}
-
-grpc_auth_json_key grpc_auth_json_key_create_from_string(
- const char* json_string) {
+ if (prop_value == nullptr) {
+ goto end;
+ }
+ bio = BIO_new(BIO_s_mem());
+ success = BIO_puts(bio, prop_value);
+ if ((success < 0) || (static_cast<size_t>(success) != strlen(prop_value))) {
+ gpr_log(GPR_ERROR, "Could not write into openssl BIO.");
+ goto end;
+ }
+ result.private_key =
+ PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, (void*)"");
+ if (result.private_key == nullptr) {
+ gpr_log(GPR_ERROR, "Could not deserialize private key.");
+ goto end;
+ }
+ success = 1;
+
+end:
+ if (bio != nullptr) BIO_free(bio);
+ if (!success) grpc_auth_json_key_destruct(&result);
+ return result;
+}
+
+grpc_auth_json_key grpc_auth_json_key_create_from_string(
+ const char* json_string) {
grpc_error* error = GRPC_ERROR_NONE;
Json json = Json::Parse(json_string, &error);
GRPC_LOG_IF_ERROR("JSON key parsing", error);
return grpc_auth_json_key_create_from_json(json);
-}
-
-void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key) {
- if (json_key == nullptr) return;
- json_key->type = GRPC_AUTH_JSON_TYPE_INVALID;
- if (json_key->client_id != nullptr) {
- gpr_free(json_key->client_id);
- json_key->client_id = nullptr;
- }
- if (json_key->private_key_id != nullptr) {
- gpr_free(json_key->private_key_id);
- json_key->private_key_id = nullptr;
- }
- if (json_key->client_email != nullptr) {
- gpr_free(json_key->client_email);
- json_key->client_email = nullptr;
- }
- if (json_key->private_key != nullptr) {
- RSA_free(json_key->private_key);
- json_key->private_key = nullptr;
- }
-}
-
-/* --- jwt encoding and signature. --- */
-
-static char* encoded_jwt_header(const char* key_id, const char* algorithm) {
+}
+
+void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key) {
+ if (json_key == nullptr) return;
+ json_key->type = GRPC_AUTH_JSON_TYPE_INVALID;
+ if (json_key->client_id != nullptr) {
+ gpr_free(json_key->client_id);
+ json_key->client_id = nullptr;
+ }
+ if (json_key->private_key_id != nullptr) {
+ gpr_free(json_key->private_key_id);
+ json_key->private_key_id = nullptr;
+ }
+ if (json_key->client_email != nullptr) {
+ gpr_free(json_key->client_email);
+ json_key->client_email = nullptr;
+ }
+ if (json_key->private_key != nullptr) {
+ RSA_free(json_key->private_key);
+ json_key->private_key = nullptr;
+ }
+}
+
+/* --- jwt encoding and signature. --- */
+
+static char* encoded_jwt_header(const char* key_id, const char* algorithm) {
Json json = Json::Object{
{"alg", algorithm},
{"typ", GRPC_JWT_TYPE},
@@ -161,128 +161,128 @@ static char* encoded_jwt_header(const char* key_id, const char* algorithm) {
};
TString json_str = json.Dump();
return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0);
-}
-
-static char* encoded_jwt_claim(const grpc_auth_json_key* json_key,
- const char* audience,
- gpr_timespec token_lifetime, const char* scope) {
- gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
- gpr_timespec expiration = gpr_time_add(now, token_lifetime);
- if (gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()) > 0) {
- gpr_log(GPR_INFO, "Cropping token lifetime to maximum allowed value.");
- expiration = gpr_time_add(now, grpc_max_auth_token_lifetime());
- }
-
+}
+
+static char* encoded_jwt_claim(const grpc_auth_json_key* json_key,
+ const char* audience,
+ gpr_timespec token_lifetime, const char* scope) {
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ gpr_timespec expiration = gpr_time_add(now, token_lifetime);
+ if (gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()) > 0) {
+ gpr_log(GPR_INFO, "Cropping token lifetime to maximum allowed value.");
+ expiration = gpr_time_add(now, grpc_max_auth_token_lifetime());
+ }
+
Json::Object object = {
{"iss", json_key->client_email},
{"aud", audience},
{"iat", now.tv_sec},
{"exp", expiration.tv_sec},
};
- if (scope != nullptr) {
+ if (scope != nullptr) {
object["scope"] = scope;
- } else {
- /* Unscoped JWTs need a sub field. */
+ } else {
+ /* Unscoped JWTs need a sub field. */
object["sub"] = json_key->client_email;
- }
-
+ }
+
Json json(object);
TString json_str = json.Dump();
return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0);
-}
-
-static char* dot_concat_and_free_strings(char* str1, char* str2) {
- size_t str1_len = strlen(str1);
- size_t str2_len = strlen(str2);
- size_t result_len = str1_len + 1 /* dot */ + str2_len;
- char* result =
- static_cast<char*>(gpr_malloc(result_len + 1 /* NULL terminated */));
- char* current = result;
- memcpy(current, str1, str1_len);
- current += str1_len;
- *(current++) = '.';
- memcpy(current, str2, str2_len);
- current += str2_len;
- GPR_ASSERT(current >= result);
- GPR_ASSERT((uintptr_t)(current - result) == result_len);
- *current = '\0';
- gpr_free(str1);
- gpr_free(str2);
- return result;
-}
-
-const EVP_MD* openssl_digest_from_algorithm(const char* algorithm) {
- if (strcmp(algorithm, GRPC_JWT_RSA_SHA256_ALGORITHM) == 0) {
- return EVP_sha256();
- } else {
- gpr_log(GPR_ERROR, "Unknown algorithm %s.", algorithm);
- return nullptr;
- }
-}
-
-char* compute_and_encode_signature(const grpc_auth_json_key* json_key,
- const char* signature_algorithm,
- const char* to_sign) {
- const EVP_MD* md = openssl_digest_from_algorithm(signature_algorithm);
- EVP_MD_CTX* md_ctx = nullptr;
- EVP_PKEY* key = EVP_PKEY_new();
- size_t sig_len = 0;
- unsigned char* sig = nullptr;
- char* result = nullptr;
- if (md == nullptr) return nullptr;
- md_ctx = EVP_MD_CTX_create();
- if (md_ctx == nullptr) {
- gpr_log(GPR_ERROR, "Could not create MD_CTX");
- goto end;
- }
- EVP_PKEY_set1_RSA(key, json_key->private_key);
- if (EVP_DigestSignInit(md_ctx, nullptr, md, nullptr, key) != 1) {
- gpr_log(GPR_ERROR, "DigestInit failed.");
- goto end;
- }
- if (EVP_DigestSignUpdate(md_ctx, to_sign, strlen(to_sign)) != 1) {
- gpr_log(GPR_ERROR, "DigestUpdate failed.");
- goto end;
- }
- if (EVP_DigestSignFinal(md_ctx, nullptr, &sig_len) != 1) {
- gpr_log(GPR_ERROR, "DigestFinal (get signature length) failed.");
- goto end;
- }
- sig = static_cast<unsigned char*>(gpr_malloc(sig_len));
- if (EVP_DigestSignFinal(md_ctx, sig, &sig_len) != 1) {
- gpr_log(GPR_ERROR, "DigestFinal (signature compute) failed.");
- goto end;
- }
- result = grpc_base64_encode(sig, sig_len, 1, 0);
-
-end:
- if (key != nullptr) EVP_PKEY_free(key);
- if (md_ctx != nullptr) EVP_MD_CTX_destroy(md_ctx);
- if (sig != nullptr) gpr_free(sig);
- return result;
-}
-
-char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key,
- const char* audience,
- gpr_timespec token_lifetime, const char* scope) {
- if (g_jwt_encode_and_sign_override != nullptr) {
- return g_jwt_encode_and_sign_override(json_key, audience, token_lifetime,
- scope);
- } else {
- const char* sig_algo = GRPC_JWT_RSA_SHA256_ALGORITHM;
- char* to_sign = dot_concat_and_free_strings(
- encoded_jwt_header(json_key->private_key_id, sig_algo),
- encoded_jwt_claim(json_key, audience, token_lifetime, scope));
- char* sig = compute_and_encode_signature(json_key, sig_algo, to_sign);
- if (sig == nullptr) {
- gpr_free(to_sign);
- return nullptr;
- }
- return dot_concat_and_free_strings(to_sign, sig);
- }
-}
-
-void grpc_jwt_encode_and_sign_set_override(
- grpc_jwt_encode_and_sign_override func) {
- g_jwt_encode_and_sign_override = func;
-}
+}
+
+static char* dot_concat_and_free_strings(char* str1, char* str2) {
+ size_t str1_len = strlen(str1);
+ size_t str2_len = strlen(str2);
+ size_t result_len = str1_len + 1 /* dot */ + str2_len;
+ char* result =
+ static_cast<char*>(gpr_malloc(result_len + 1 /* NULL terminated */));
+ char* current = result;
+ memcpy(current, str1, str1_len);
+ current += str1_len;
+ *(current++) = '.';
+ memcpy(current, str2, str2_len);
+ current += str2_len;
+ GPR_ASSERT(current >= result);
+ GPR_ASSERT((uintptr_t)(current - result) == result_len);
+ *current = '\0';
+ gpr_free(str1);
+ gpr_free(str2);
+ return result;
+}
+
+const EVP_MD* openssl_digest_from_algorithm(const char* algorithm) {
+ if (strcmp(algorithm, GRPC_JWT_RSA_SHA256_ALGORITHM) == 0) {
+ return EVP_sha256();
+ } else {
+ gpr_log(GPR_ERROR, "Unknown algorithm %s.", algorithm);
+ return nullptr;
+ }
+}
+
+char* compute_and_encode_signature(const grpc_auth_json_key* json_key,
+ const char* signature_algorithm,
+ const char* to_sign) {
+ const EVP_MD* md = openssl_digest_from_algorithm(signature_algorithm);
+ EVP_MD_CTX* md_ctx = nullptr;
+ EVP_PKEY* key = EVP_PKEY_new();
+ size_t sig_len = 0;
+ unsigned char* sig = nullptr;
+ char* result = nullptr;
+ if (md == nullptr) return nullptr;
+ md_ctx = EVP_MD_CTX_create();
+ if (md_ctx == nullptr) {
+ gpr_log(GPR_ERROR, "Could not create MD_CTX");
+ goto end;
+ }
+ EVP_PKEY_set1_RSA(key, json_key->private_key);
+ if (EVP_DigestSignInit(md_ctx, nullptr, md, nullptr, key) != 1) {
+ gpr_log(GPR_ERROR, "DigestInit failed.");
+ goto end;
+ }
+ if (EVP_DigestSignUpdate(md_ctx, to_sign, strlen(to_sign)) != 1) {
+ gpr_log(GPR_ERROR, "DigestUpdate failed.");
+ goto end;
+ }
+ if (EVP_DigestSignFinal(md_ctx, nullptr, &sig_len) != 1) {
+ gpr_log(GPR_ERROR, "DigestFinal (get signature length) failed.");
+ goto end;
+ }
+ sig = static_cast<unsigned char*>(gpr_malloc(sig_len));
+ if (EVP_DigestSignFinal(md_ctx, sig, &sig_len) != 1) {
+ gpr_log(GPR_ERROR, "DigestFinal (signature compute) failed.");
+ goto end;
+ }
+ result = grpc_base64_encode(sig, sig_len, 1, 0);
+
+end:
+ if (key != nullptr) EVP_PKEY_free(key);
+ if (md_ctx != nullptr) EVP_MD_CTX_destroy(md_ctx);
+ if (sig != nullptr) gpr_free(sig);
+ return result;
+}
+
+char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key,
+ const char* audience,
+ gpr_timespec token_lifetime, const char* scope) {
+ if (g_jwt_encode_and_sign_override != nullptr) {
+ return g_jwt_encode_and_sign_override(json_key, audience, token_lifetime,
+ scope);
+ } else {
+ const char* sig_algo = GRPC_JWT_RSA_SHA256_ALGORITHM;
+ char* to_sign = dot_concat_and_free_strings(
+ encoded_jwt_header(json_key->private_key_id, sig_algo),
+ encoded_jwt_claim(json_key, audience, token_lifetime, scope));
+ char* sig = compute_and_encode_signature(json_key, sig_algo, to_sign);
+ if (sig == nullptr) {
+ gpr_free(to_sign);
+ return nullptr;
+ }
+ return dot_concat_and_free_strings(to_sign, sig);
+ }
+}
+
+void grpc_jwt_encode_and_sign_set_override(
+ grpc_jwt_encode_and_sign_override func) {
+ g_jwt_encode_and_sign_override = func;
+}
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 b9a41c6b2b6..db588e6fdb7 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_JWT_JSON_TOKEN_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JSON_TOKEN_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include <openssl/rsa.h>
@@ -33,19 +33,19 @@
/* --- auth_json_key parsing. --- */
struct grpc_auth_json_key {
- const char* type;
- char* private_key_id;
- char* client_id;
- char* client_email;
- RSA* private_key;
+ const char* type;
+ char* private_key_id;
+ char* client_id;
+ char* client_email;
+ RSA* private_key;
};
/* Returns 1 if the object is valid, 0 otherwise. */
-int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key);
+int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key);
/* Creates a json_key object from string. Returns an invalid object if a parsing
error has been encountered. */
grpc_auth_json_key grpc_auth_json_key_create_from_string(
- const char* json_string);
+ const char* json_string);
/* Creates a json_key object from parsed json. Returns an invalid object if a
parsing error has been encountered. */
@@ -53,20 +53,20 @@ grpc_auth_json_key grpc_auth_json_key_create_from_json(
const grpc_core::Json& json);
/* Destructs the object. */
-void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key);
+void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key);
/* --- json token encoding and signing. --- */
/* Caller is responsible for calling gpr_free on the returned value. May return
NULL on invalid input. The scope parameter may be NULL. */
-char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key,
- const char* audience,
- gpr_timespec token_lifetime, const char* scope);
+char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key,
+ const char* audience,
+ gpr_timespec token_lifetime, const char* scope);
/* Override encode_and_sign function for testing. */
-typedef char* (*grpc_jwt_encode_and_sign_override)(
- const grpc_auth_json_key* json_key, const char* audience,
- gpr_timespec token_lifetime, const char* scope);
+typedef char* (*grpc_jwt_encode_and_sign_override)(
+ const grpc_auth_json_key* json_key, const char* audience,
+ gpr_timespec token_lifetime, const char* scope);
/* Set a custom encode_and_sign override for testing. */
void grpc_jwt_encode_and_sign_set_override(
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 d5555c3aa16..c54ce7058f8 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
@@ -1,28 +1,28 @@
-/*
- *
- * 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/security/credentials/jwt/jwt_credentials.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/security/credentials/jwt/jwt_credentials.h"
+
+#include <inttypes.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
@@ -30,13 +30,13 @@
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.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/lib/surface/api_trace.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+
using grpc_core::Json;
void grpc_service_account_jwt_access_credentials::reset_cache() {
@@ -45,27 +45,27 @@ void grpc_service_account_jwt_access_credentials::reset_cache() {
if (cached_.service_url != nullptr) {
gpr_free(cached_.service_url);
cached_.service_url = nullptr;
- }
+ }
cached_.jwt_expiration = gpr_inf_past(GPR_CLOCK_REALTIME);
-}
-
+}
+
grpc_service_account_jwt_access_credentials::
~grpc_service_account_jwt_access_credentials() {
grpc_auth_json_key_destruct(&key_);
reset_cache();
gpr_mu_destroy(&cache_mu_);
-}
-
+}
+
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) {
- gpr_timespec refresh_threshold = gpr_time_from_seconds(
- GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS, GPR_TIMESPAN);
-
- /* See if we can return a cached jwt. */
- grpc_mdelem jwt_md = GRPC_MDNULL;
- {
+ gpr_timespec refresh_threshold = gpr_time_from_seconds(
+ GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS, GPR_TIMESPAN);
+
+ /* See if we can return a cached jwt. */
+ grpc_mdelem jwt_md = GRPC_MDNULL;
+ {
gpr_mu_lock(&cache_mu_);
if (cached_.service_url != nullptr &&
strcmp(cached_.service_url, context.service_url) == 0 &&
@@ -74,61 +74,61 @@ bool grpc_service_account_jwt_access_credentials::get_request_metadata(
gpr_time_sub(cached_.jwt_expiration, gpr_now(GPR_CLOCK_REALTIME)),
refresh_threshold) > 0)) {
jwt_md = GRPC_MDELEM_REF(cached_.jwt_md);
- }
+ }
gpr_mu_unlock(&cache_mu_);
- }
-
- if (GRPC_MDISNULL(jwt_md)) {
- char* jwt = nullptr;
- /* Generate a new jwt. */
+ }
+
+ if (GRPC_MDISNULL(jwt_md)) {
+ char* jwt = nullptr;
+ /* Generate a new jwt. */
gpr_mu_lock(&cache_mu_);
reset_cache();
jwt = grpc_jwt_encode_and_sign(&key_, context.service_url, jwt_lifetime_,
nullptr);
- if (jwt != nullptr) {
+ if (jwt != nullptr) {
TString md_value = y_absl::StrCat("Bearer ", jwt);
- gpr_free(jwt);
+ gpr_free(jwt);
cached_.jwt_expiration =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), jwt_lifetime_);
cached_.service_url = gpr_strdup(context.service_url);
cached_.jwt_md = grpc_mdelem_from_slices(
- grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY),
+ grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_cpp_string(std::move(md_value)));
jwt_md = GRPC_MDELEM_REF(cached_.jwt_md);
- }
+ }
gpr_mu_unlock(&cache_mu_);
- }
-
- if (!GRPC_MDISNULL(jwt_md)) {
- grpc_credentials_mdelem_array_add(md_array, jwt_md);
- GRPC_MDELEM_UNREF(jwt_md);
- } else {
- *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Could not generate JWT.");
- }
- return true;
-}
-
+ }
+
+ if (!GRPC_MDISNULL(jwt_md)) {
+ grpc_credentials_mdelem_array_add(md_array, jwt_md);
+ GRPC_MDELEM_UNREF(jwt_md);
+ } else {
+ *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Could not generate JWT.");
+ }
+ return true;
+}
+
void grpc_service_account_jwt_access_credentials::cancel_get_request_metadata(
grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
- GRPC_ERROR_UNREF(error);
-}
-
+ GRPC_ERROR_UNREF(error);
+}
+
grpc_service_account_jwt_access_credentials::
grpc_service_account_jwt_access_credentials(grpc_auth_json_key key,
gpr_timespec token_lifetime)
: grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_JWT), key_(key) {
- gpr_timespec max_token_lifetime = grpc_max_auth_token_lifetime();
- if (gpr_time_cmp(token_lifetime, max_token_lifetime) > 0) {
- gpr_log(GPR_INFO,
- "Cropping token lifetime to maximum allowed value (%d secs).",
- static_cast<int>(max_token_lifetime.tv_sec));
- token_lifetime = grpc_max_auth_token_lifetime();
- }
+ gpr_timespec max_token_lifetime = grpc_max_auth_token_lifetime();
+ if (gpr_time_cmp(token_lifetime, max_token_lifetime) > 0) {
+ gpr_log(GPR_INFO,
+ "Cropping token lifetime to maximum allowed value (%d secs).",
+ static_cast<int>(max_token_lifetime.tv_sec));
+ token_lifetime = grpc_max_auth_token_lifetime();
+ }
jwt_lifetime_ = token_lifetime;
gpr_mu_init(&cache_mu_);
reset_cache();
-}
-
+}
+
grpc_core::RefCountedPtr<grpc_call_credentials>
grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
grpc_auth_json_key key, gpr_timespec token_lifetime) {
@@ -140,36 +140,36 @@ grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
key, token_lifetime);
}
-static char* redact_private_key(const char* json_key) {
+static char* redact_private_key(const char* json_key) {
grpc_error* error = GRPC_ERROR_NONE;
Json json = Json::Parse(json_key, &error);
if (error != GRPC_ERROR_NONE || json.type() != Json::Type::OBJECT) {
GRPC_ERROR_UNREF(error);
- return gpr_strdup("<Json failed to parse.>");
- }
+ return gpr_strdup("<Json failed to parse.>");
+ }
(*json.mutable_object())["private_key"] = "<redacted>";
return gpr_strdup(json.Dump(/*indent=*/2).c_str());
-}
-
-grpc_call_credentials* grpc_service_account_jwt_access_credentials_create(
- const char* json_key, gpr_timespec token_lifetime, void* reserved) {
+}
+
+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)) {
- char* clean_json = redact_private_key(json_key);
- gpr_log(GPR_INFO,
- "grpc_service_account_jwt_access_credentials_create("
- "json_key=%s, "
- "token_lifetime="
- "gpr_timespec { tv_sec: %" PRId64
- ", tv_nsec: %d, clock_type: %d }, "
- "reserved=%p)",
- clean_json, token_lifetime.tv_sec, token_lifetime.tv_nsec,
- static_cast<int>(token_lifetime.clock_type), reserved);
- gpr_free(clean_json);
- }
- GPR_ASSERT(reserved == nullptr);
+ char* clean_json = redact_private_key(json_key);
+ gpr_log(GPR_INFO,
+ "grpc_service_account_jwt_access_credentials_create("
+ "json_key=%s, "
+ "token_lifetime="
+ "gpr_timespec { tv_sec: %" PRId64
+ ", tv_nsec: %d, clock_type: %d }, "
+ "reserved=%p)",
+ clean_json, token_lifetime.tv_sec, token_lifetime.tv_nsec,
+ static_cast<int>(token_lifetime.clock_type), reserved);
+ gpr_free(clean_json);
+ }
+ GPR_ASSERT(reserved == nullptr);
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
return grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
grpc_auth_json_key_create_from_string(json_key), token_lifetime)
.release();
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h
index 9b60deacb5b..f5ede7b1a5a 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_JWT_JWT_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include <grpc/support/time.h>
@@ -75,6 +75,6 @@ class grpc_service_account_jwt_access_credentials
// Takes ownership of the key.
grpc_core::RefCountedPtr<grpc_call_credentials>
grpc_service_account_jwt_access_credentials_create_from_auth_json_key(
- grpc_auth_json_key key, gpr_timespec token_lifetime);
+ grpc_auth_json_key key, gpr_timespec token_lifetime);
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_CREDENTIALS_H */
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 0c9e118826f..881f4ec6078 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
@@ -1,91 +1,91 @@
-/*
- *
- * 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/security/credentials/jwt/jwt_verifier.h"
-
-#include <limits.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-
-extern "C" {
+/*
+ *
+ * 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/security/credentials/jwt/jwt_verifier.h"
+
+#include <limits.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/sync.h>
+
+extern "C" {
#include <openssl/bn.h>
-#include <openssl/pem.h>
+#include <openssl/pem.h>
#include <openssl/rsa.h>
-}
-
-#include "src/core/lib/gpr/string.h"
+}
+
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/manual_constructor.h"
-#include "src/core/lib/http/httpcli.h"
-#include "src/core/lib/iomgr/polling_entity.h"
-#include "src/core/lib/slice/b64.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/tsi/ssl_types.h"
-
+#include "src/core/lib/http/httpcli.h"
+#include "src/core/lib/iomgr/polling_entity.h"
+#include "src/core/lib/slice/b64.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/tsi/ssl_types.h"
+
using grpc_core::Json;
-/* --- Utils. --- */
-
-const char* grpc_jwt_verifier_status_to_string(
- grpc_jwt_verifier_status status) {
- switch (status) {
- case GRPC_JWT_VERIFIER_OK:
- return "OK";
- case GRPC_JWT_VERIFIER_BAD_SIGNATURE:
- return "BAD_SIGNATURE";
- case GRPC_JWT_VERIFIER_BAD_FORMAT:
- return "BAD_FORMAT";
- case GRPC_JWT_VERIFIER_BAD_AUDIENCE:
- return "BAD_AUDIENCE";
- case GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR:
- return "KEY_RETRIEVAL_ERROR";
- case GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE:
- return "TIME_CONSTRAINT_FAILURE";
- case GRPC_JWT_VERIFIER_GENERIC_ERROR:
- return "GENERIC_ERROR";
- default:
- return "UNKNOWN";
- }
-}
-
-static const EVP_MD* evp_md_from_alg(const char* alg) {
- if (strcmp(alg, "RS256") == 0) {
- return EVP_sha256();
- } else if (strcmp(alg, "RS384") == 0) {
- return EVP_sha384();
- } else if (strcmp(alg, "RS512") == 0) {
- return EVP_sha512();
- } else {
- return nullptr;
- }
-}
-
+/* --- Utils. --- */
+
+const char* grpc_jwt_verifier_status_to_string(
+ grpc_jwt_verifier_status status) {
+ switch (status) {
+ case GRPC_JWT_VERIFIER_OK:
+ return "OK";
+ case GRPC_JWT_VERIFIER_BAD_SIGNATURE:
+ return "BAD_SIGNATURE";
+ case GRPC_JWT_VERIFIER_BAD_FORMAT:
+ return "BAD_FORMAT";
+ case GRPC_JWT_VERIFIER_BAD_AUDIENCE:
+ return "BAD_AUDIENCE";
+ case GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR:
+ return "KEY_RETRIEVAL_ERROR";
+ case GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE:
+ return "TIME_CONSTRAINT_FAILURE";
+ case GRPC_JWT_VERIFIER_GENERIC_ERROR:
+ return "GENERIC_ERROR";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+static const EVP_MD* evp_md_from_alg(const char* alg) {
+ if (strcmp(alg, "RS256") == 0) {
+ return EVP_sha256();
+ } else if (strcmp(alg, "RS384") == 0) {
+ return EVP_sha384();
+ } else if (strcmp(alg, "RS512") == 0) {
+ return EVP_sha512();
+ } else {
+ return nullptr;
+ }
+}
+
static Json parse_json_part_from_jwt(const char* str, size_t len) {
grpc_slice slice = grpc_base64_decode_with_len(str, len, 1);
if (GRPC_SLICE_IS_EMPTY(slice)) {
- gpr_log(GPR_ERROR, "Invalid base64.");
+ gpr_log(GPR_ERROR, "Invalid base64.");
return Json(); // JSON null
- }
+ }
y_absl::string_view string = grpc_core::StringViewFromSlice(slice);
grpc_error* error = GRPC_ERROR_NONE;
Json json = Json::Parse(string, &error);
@@ -93,57 +93,57 @@ static Json parse_json_part_from_jwt(const char* str, size_t len) {
gpr_log(GPR_ERROR, "JSON parse error: %s", grpc_error_string(error));
GRPC_ERROR_UNREF(error);
json = Json(); // JSON null
- }
+ }
grpc_slice_unref_internal(slice);
- return json;
-}
-
+ return json;
+}
+
static const char* validate_string_field(const Json& json, const char* key) {
if (json.type() != Json::Type::STRING) {
gpr_log(GPR_ERROR, "Invalid %s field", key);
- return nullptr;
- }
+ return nullptr;
+ }
return json.string_value().c_str();
-}
-
+}
+
static gpr_timespec validate_time_field(const Json& json, const char* key) {
- gpr_timespec result = gpr_time_0(GPR_CLOCK_REALTIME);
+ gpr_timespec result = gpr_time_0(GPR_CLOCK_REALTIME);
if (json.type() != Json::Type::NUMBER) {
gpr_log(GPR_ERROR, "Invalid %s field", key);
- return result;
- }
+ return result;
+ }
result.tv_sec = strtol(json.string_value().c_str(), nullptr, 10);
- return result;
-}
-
-/* --- JOSE header. see http://tools.ietf.org/html/rfc7515#section-4 --- */
-
+ return result;
+}
+
+/* --- JOSE header. see http://tools.ietf.org/html/rfc7515#section-4 --- */
+
struct jose_header {
- const char* alg;
- const char* kid;
- const char* typ;
- /* TODO(jboeuf): Add others as needed (jku, jwk, x5u, x5c and so on...). */
+ const char* alg;
+ const char* kid;
+ const char* typ;
+ /* TODO(jboeuf): Add others as needed (jku, jwk, x5u, x5c and so on...). */
grpc_core::ManualConstructor<Json> json;
};
-static void jose_header_destroy(jose_header* h) {
+static void jose_header_destroy(jose_header* h) {
h->json.Destroy();
- gpr_free(h);
-}
-
+ gpr_free(h);
+}
+
static jose_header* jose_header_from_json(Json json) {
const char* alg_value;
Json::Object::const_iterator it;
- jose_header* h = static_cast<jose_header*>(gpr_zalloc(sizeof(jose_header)));
+ jose_header* h = static_cast<jose_header*>(gpr_zalloc(sizeof(jose_header)));
if (json.type() != Json::Type::OBJECT) {
gpr_log(GPR_ERROR, "JSON value is not an object");
goto error;
- }
+ }
// Check alg field.
it = json.object_value().find("alg");
if (it == json.object_value().end()) {
- gpr_log(GPR_ERROR, "Missing alg field.");
- goto error;
- }
+ gpr_log(GPR_ERROR, "Missing alg field.");
+ goto error;
+ }
/* We only support RSA-1.5 signatures for now.
Beware of this if we add HMAC support:
https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
@@ -168,758 +168,758 @@ static jose_header* jose_header_from_json(Json json) {
if (h->kid == nullptr) goto error;
}
h->json.Init(std::move(json));
- return h;
-
-error:
- jose_header_destroy(h);
- return nullptr;
-}
-
-/* --- JWT claims. see http://tools.ietf.org/html/rfc7519#section-4.1 */
-
-struct grpc_jwt_claims {
- /* Well known properties already parsed. */
- const char* sub;
- const char* iss;
- const char* aud;
- const char* jti;
- gpr_timespec iat;
- gpr_timespec exp;
- gpr_timespec nbf;
-
+ return h;
+
+error:
+ jose_header_destroy(h);
+ return nullptr;
+}
+
+/* --- JWT claims. see http://tools.ietf.org/html/rfc7519#section-4.1 */
+
+struct grpc_jwt_claims {
+ /* Well known properties already parsed. */
+ const char* sub;
+ const char* iss;
+ const char* aud;
+ const char* jti;
+ gpr_timespec iat;
+ gpr_timespec exp;
+ gpr_timespec nbf;
+
grpc_core::ManualConstructor<Json> json;
-};
-
-void grpc_jwt_claims_destroy(grpc_jwt_claims* claims) {
+};
+
+void grpc_jwt_claims_destroy(grpc_jwt_claims* claims) {
claims->json.Destroy();
- gpr_free(claims);
-}
-
+ gpr_free(claims);
+}
+
const Json* grpc_jwt_claims_json(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return nullptr;
+ if (claims == nullptr) return nullptr;
return claims->json.get();
-}
-
-const char* grpc_jwt_claims_subject(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return nullptr;
- return claims->sub;
-}
-
-const char* grpc_jwt_claims_issuer(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return nullptr;
- return claims->iss;
-}
-
-const char* grpc_jwt_claims_id(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return nullptr;
- return claims->jti;
-}
-
-const char* grpc_jwt_claims_audience(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return nullptr;
- return claims->aud;
-}
-
-gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME);
- return claims->iat;
-}
-
-gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return gpr_inf_future(GPR_CLOCK_REALTIME);
- return claims->exp;
-}
-
-gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims* claims) {
- if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME);
- return claims->nbf;
-}
-
+}
+
+const char* grpc_jwt_claims_subject(const grpc_jwt_claims* claims) {
+ if (claims == nullptr) return nullptr;
+ return claims->sub;
+}
+
+const char* grpc_jwt_claims_issuer(const grpc_jwt_claims* claims) {
+ if (claims == nullptr) return nullptr;
+ return claims->iss;
+}
+
+const char* grpc_jwt_claims_id(const grpc_jwt_claims* claims) {
+ if (claims == nullptr) return nullptr;
+ return claims->jti;
+}
+
+const char* grpc_jwt_claims_audience(const grpc_jwt_claims* claims) {
+ if (claims == nullptr) return nullptr;
+ return claims->aud;
+}
+
+gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims* claims) {
+ if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME);
+ return claims->iat;
+}
+
+gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims* claims) {
+ if (claims == nullptr) return gpr_inf_future(GPR_CLOCK_REALTIME);
+ return claims->exp;
+}
+
+gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims* claims) {
+ if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME);
+ return claims->nbf;
+}
+
grpc_jwt_claims* grpc_jwt_claims_from_json(Json json) {
- grpc_jwt_claims* claims =
+ grpc_jwt_claims* claims =
static_cast<grpc_jwt_claims*>(gpr_zalloc(sizeof(grpc_jwt_claims)));
claims->json.Init(std::move(json));
- claims->iat = gpr_inf_past(GPR_CLOCK_REALTIME);
- claims->nbf = gpr_inf_past(GPR_CLOCK_REALTIME);
- claims->exp = gpr_inf_future(GPR_CLOCK_REALTIME);
-
- /* Per the spec, all fields are optional. */
+ claims->iat = gpr_inf_past(GPR_CLOCK_REALTIME);
+ claims->nbf = gpr_inf_past(GPR_CLOCK_REALTIME);
+ claims->exp = gpr_inf_future(GPR_CLOCK_REALTIME);
+
+ /* Per the spec, all fields are optional. */
for (const auto& p : claims->json->object_value()) {
if (p.first == "sub") {
claims->sub = validate_string_field(p.second, "sub");
- if (claims->sub == nullptr) goto error;
+ if (claims->sub == nullptr) goto error;
} else if (p.first == "iss") {
claims->iss = validate_string_field(p.second, "iss");
- if (claims->iss == nullptr) goto error;
+ if (claims->iss == nullptr) goto error;
} else if (p.first == "aud") {
claims->aud = validate_string_field(p.second, "aud");
- if (claims->aud == nullptr) goto error;
+ if (claims->aud == nullptr) goto error;
} else if (p.first == "jti") {
claims->jti = validate_string_field(p.second, "jti");
- if (claims->jti == nullptr) goto error;
+ if (claims->jti == nullptr) goto error;
} else if (p.first == "iat") {
claims->iat = validate_time_field(p.second, "iat");
if (gpr_time_cmp(claims->iat, gpr_time_0(GPR_CLOCK_REALTIME)) == 0) {
- goto error;
+ goto error;
}
} else if (p.first == "exp") {
claims->exp = validate_time_field(p.second, "exp");
if (gpr_time_cmp(claims->exp, gpr_time_0(GPR_CLOCK_REALTIME)) == 0) {
- goto error;
+ goto error;
}
} else if (p.first == "nbf") {
claims->nbf = validate_time_field(p.second, "nbf");
if (gpr_time_cmp(claims->nbf, gpr_time_0(GPR_CLOCK_REALTIME)) == 0) {
- goto error;
+ goto error;
}
- }
- }
- return claims;
-
-error:
- grpc_jwt_claims_destroy(claims);
- return nullptr;
-}
-
-grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims* claims,
- const char* audience) {
- gpr_timespec skewed_now;
- int audience_ok;
-
- GPR_ASSERT(claims != nullptr);
-
- skewed_now =
- gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_clock_skew);
- if (gpr_time_cmp(skewed_now, claims->nbf) < 0) {
- gpr_log(GPR_ERROR, "JWT is not valid yet.");
- return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE;
- }
- skewed_now =
- gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_clock_skew);
- if (gpr_time_cmp(skewed_now, claims->exp) > 0) {
- gpr_log(GPR_ERROR, "JWT is expired.");
- return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE;
- }
-
- /* This should be probably up to the upper layer to decide but let's harcode
- the 99% use case here for email issuers, where the JWT must be self
- issued. */
- if (grpc_jwt_issuer_email_domain(claims->iss) != nullptr &&
- claims->sub != nullptr && strcmp(claims->iss, claims->sub) != 0) {
- gpr_log(GPR_ERROR,
- "Email issuer (%s) cannot assert another subject (%s) than itself.",
- claims->iss, claims->sub);
- return GRPC_JWT_VERIFIER_BAD_SUBJECT;
- }
-
- if (audience == nullptr) {
- audience_ok = claims->aud == nullptr;
- } else {
- audience_ok = claims->aud != nullptr && strcmp(audience, claims->aud) == 0;
- }
- if (!audience_ok) {
- gpr_log(GPR_ERROR, "Audience mismatch: expected %s and found %s.",
- audience == nullptr ? "NULL" : audience,
- claims->aud == nullptr ? "NULL" : claims->aud);
- return GRPC_JWT_VERIFIER_BAD_AUDIENCE;
- }
- return GRPC_JWT_VERIFIER_OK;
-}
-
-/* --- verifier_cb_ctx object. --- */
-
-typedef enum {
- HTTP_RESPONSE_OPENID = 0,
- HTTP_RESPONSE_KEYS,
- HTTP_RESPONSE_COUNT /* must be last */
-} http_response_index;
-
+ }
+ }
+ return claims;
+
+error:
+ grpc_jwt_claims_destroy(claims);
+ return nullptr;
+}
+
+grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims* claims,
+ const char* audience) {
+ gpr_timespec skewed_now;
+ int audience_ok;
+
+ GPR_ASSERT(claims != nullptr);
+
+ skewed_now =
+ gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_clock_skew);
+ if (gpr_time_cmp(skewed_now, claims->nbf) < 0) {
+ gpr_log(GPR_ERROR, "JWT is not valid yet.");
+ return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE;
+ }
+ skewed_now =
+ gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_clock_skew);
+ if (gpr_time_cmp(skewed_now, claims->exp) > 0) {
+ gpr_log(GPR_ERROR, "JWT is expired.");
+ return GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE;
+ }
+
+ /* This should be probably up to the upper layer to decide but let's harcode
+ the 99% use case here for email issuers, where the JWT must be self
+ issued. */
+ if (grpc_jwt_issuer_email_domain(claims->iss) != nullptr &&
+ claims->sub != nullptr && strcmp(claims->iss, claims->sub) != 0) {
+ gpr_log(GPR_ERROR,
+ "Email issuer (%s) cannot assert another subject (%s) than itself.",
+ claims->iss, claims->sub);
+ return GRPC_JWT_VERIFIER_BAD_SUBJECT;
+ }
+
+ if (audience == nullptr) {
+ audience_ok = claims->aud == nullptr;
+ } else {
+ audience_ok = claims->aud != nullptr && strcmp(audience, claims->aud) == 0;
+ }
+ if (!audience_ok) {
+ gpr_log(GPR_ERROR, "Audience mismatch: expected %s and found %s.",
+ audience == nullptr ? "NULL" : audience,
+ claims->aud == nullptr ? "NULL" : claims->aud);
+ return GRPC_JWT_VERIFIER_BAD_AUDIENCE;
+ }
+ return GRPC_JWT_VERIFIER_OK;
+}
+
+/* --- verifier_cb_ctx object. --- */
+
+typedef enum {
+ HTTP_RESPONSE_OPENID = 0,
+ HTTP_RESPONSE_KEYS,
+ HTTP_RESPONSE_COUNT /* must be last */
+} http_response_index;
+
struct verifier_cb_ctx {
- grpc_jwt_verifier* verifier;
- grpc_polling_entity pollent;
- jose_header* header;
- grpc_jwt_claims* claims;
- char* audience;
- grpc_slice signature;
- grpc_slice signed_data;
- void* user_data;
- grpc_jwt_verification_done_cb user_cb;
- grpc_http_response responses[HTTP_RESPONSE_COUNT];
+ grpc_jwt_verifier* verifier;
+ grpc_polling_entity pollent;
+ jose_header* header;
+ grpc_jwt_claims* claims;
+ char* audience;
+ grpc_slice signature;
+ grpc_slice signed_data;
+ void* user_data;
+ grpc_jwt_verification_done_cb user_cb;
+ grpc_http_response responses[HTTP_RESPONSE_COUNT];
};
-/* 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,
+/* 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,
- const char* signed_jwt, size_t signed_jwt_len, void* user_data,
- grpc_jwt_verification_done_cb cb) {
+ const char* signed_jwt, size_t signed_jwt_len, void* user_data,
+ grpc_jwt_verification_done_cb cb) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- verifier_cb_ctx* ctx =
- static_cast<verifier_cb_ctx*>(gpr_zalloc(sizeof(verifier_cb_ctx)));
- ctx->verifier = verifier;
- ctx->pollent = grpc_polling_entity_create_from_pollset(pollset);
- ctx->header = header;
- ctx->audience = gpr_strdup(audience);
- ctx->claims = claims;
- ctx->signature = signature;
- ctx->signed_data = grpc_slice_from_copied_buffer(signed_jwt, signed_jwt_len);
- ctx->user_data = user_data;
- ctx->user_cb = cb;
-
- return ctx;
-}
-
-void verifier_cb_ctx_destroy(verifier_cb_ctx* ctx) {
- if (ctx->audience != nullptr) gpr_free(ctx->audience);
- if (ctx->claims != nullptr) grpc_jwt_claims_destroy(ctx->claims);
- grpc_slice_unref_internal(ctx->signature);
- grpc_slice_unref_internal(ctx->signed_data);
- jose_header_destroy(ctx->header);
- for (size_t i = 0; i < HTTP_RESPONSE_COUNT; i++) {
- grpc_http_response_destroy(&ctx->responses[i]);
- }
- /* TODO: see what to do with claims... */
- gpr_free(ctx);
-}
-
-/* --- grpc_jwt_verifier object. --- */
-
-/* Clock skew defaults to one minute. */
-gpr_timespec grpc_jwt_verifier_clock_skew = {60, 0, GPR_TIMESPAN};
-
-/* Max delay defaults to one minute. */
-grpc_millis grpc_jwt_verifier_max_delay = 60 * GPR_MS_PER_SEC;
-
+ grpc_core::ExecCtx exec_ctx;
+ verifier_cb_ctx* ctx =
+ static_cast<verifier_cb_ctx*>(gpr_zalloc(sizeof(verifier_cb_ctx)));
+ ctx->verifier = verifier;
+ ctx->pollent = grpc_polling_entity_create_from_pollset(pollset);
+ ctx->header = header;
+ ctx->audience = gpr_strdup(audience);
+ ctx->claims = claims;
+ ctx->signature = signature;
+ ctx->signed_data = grpc_slice_from_copied_buffer(signed_jwt, signed_jwt_len);
+ ctx->user_data = user_data;
+ ctx->user_cb = cb;
+
+ return ctx;
+}
+
+void verifier_cb_ctx_destroy(verifier_cb_ctx* ctx) {
+ if (ctx->audience != nullptr) gpr_free(ctx->audience);
+ if (ctx->claims != nullptr) grpc_jwt_claims_destroy(ctx->claims);
+ grpc_slice_unref_internal(ctx->signature);
+ grpc_slice_unref_internal(ctx->signed_data);
+ jose_header_destroy(ctx->header);
+ for (size_t i = 0; i < HTTP_RESPONSE_COUNT; i++) {
+ grpc_http_response_destroy(&ctx->responses[i]);
+ }
+ /* TODO: see what to do with claims... */
+ gpr_free(ctx);
+}
+
+/* --- grpc_jwt_verifier object. --- */
+
+/* Clock skew defaults to one minute. */
+gpr_timespec grpc_jwt_verifier_clock_skew = {60, 0, GPR_TIMESPAN};
+
+/* Max delay defaults to one minute. */
+grpc_millis grpc_jwt_verifier_max_delay = 60 * GPR_MS_PER_SEC;
+
struct email_key_mapping {
- char* email_domain;
- char* key_url_prefix;
-};
-struct grpc_jwt_verifier {
- email_key_mapping* mappings;
- size_t num_mappings; /* Should be very few, linear search ok. */
- size_t allocated_mappings;
- grpc_httpcli_context http_ctx;
+ char* email_domain;
+ char* key_url_prefix;
};
-
+struct grpc_jwt_verifier {
+ email_key_mapping* mappings;
+ size_t num_mappings; /* Should be very few, linear search ok. */
+ size_t allocated_mappings;
+ grpc_httpcli_context http_ctx;
+};
+
static Json json_from_http(const grpc_httpcli_response* response) {
- if (response == nullptr) {
- gpr_log(GPR_ERROR, "HTTP response is NULL.");
+ if (response == nullptr) {
+ gpr_log(GPR_ERROR, "HTTP response is NULL.");
return Json(); // JSON null
- }
- if (response->status != 200) {
- gpr_log(GPR_ERROR, "Call to http server failed with error %d.",
- response->status);
+ }
+ if (response->status != 200) {
+ gpr_log(GPR_ERROR, "Call to http server failed with error %d.",
+ response->status);
return Json(); // JSON null
- }
+ }
grpc_error* error = GRPC_ERROR_NONE;
Json json = Json::Parse(
y_absl::string_view(response->body, response->body_length), &error);
if (error != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "Invalid JSON found in response.");
+ gpr_log(GPR_ERROR, "Invalid JSON found in response.");
return Json(); // JSON null
- }
- return json;
-}
-
+ }
+ return json;
+}
+
static const Json* find_property_by_name(const Json& json, const char* name) {
auto it = json.object_value().find(name);
if (it == json.object_value().end()) {
return nullptr;
- }
+ }
return &it->second;
-}
-
-static EVP_PKEY* extract_pkey_from_x509(const char* x509_str) {
- X509* x509 = nullptr;
- EVP_PKEY* result = nullptr;
- BIO* bio = BIO_new(BIO_s_mem());
- size_t len = strlen(x509_str);
- GPR_ASSERT(len < INT_MAX);
- BIO_write(bio, x509_str, static_cast<int>(len));
- x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
- if (x509 == nullptr) {
- gpr_log(GPR_ERROR, "Unable to parse x509 cert.");
- goto end;
- }
- result = X509_get_pubkey(x509);
- if (result == nullptr) {
- gpr_log(GPR_ERROR, "Cannot find public key in X509 cert.");
- }
-
-end:
- BIO_free(bio);
- X509_free(x509);
- return result;
-}
-
-static BIGNUM* bignum_from_base64(const char* b64) {
- BIGNUM* result = nullptr;
- grpc_slice bin;
-
- if (b64 == nullptr) return nullptr;
- bin = grpc_base64_decode(b64, 1);
- if (GRPC_SLICE_IS_EMPTY(bin)) {
- gpr_log(GPR_ERROR, "Invalid base64 for big num.");
- return nullptr;
- }
- result = BN_bin2bn(GRPC_SLICE_START_PTR(bin),
- TSI_SIZE_AS_SIZE(GRPC_SLICE_LENGTH(bin)), nullptr);
- grpc_slice_unref_internal(bin);
- return result;
-}
-
-#if OPENSSL_VERSION_NUMBER < 0x10100000L
-
-// Provide compatibility across OpenSSL 1.02 and 1.1.
-static int RSA_set0_key(RSA* r, BIGNUM* n, BIGNUM* e, BIGNUM* d) {
- /* If the fields n and e in r are NULL, the corresponding input
- * parameters MUST be non-NULL for n and e. d may be
- * left NULL (in case only the public key is used).
- */
- if ((r->n == nullptr && n == nullptr) || (r->e == nullptr && e == nullptr)) {
- return 0;
- }
-
- if (n != nullptr) {
- BN_free(r->n);
- r->n = n;
- }
- if (e != nullptr) {
- BN_free(r->e);
- r->e = e;
- }
- if (d != nullptr) {
- BN_free(r->d);
- r->d = d;
- }
-
- return 1;
-}
-#endif // OPENSSL_VERSION_NUMBER < 0x10100000L
-
+}
+
+static EVP_PKEY* extract_pkey_from_x509(const char* x509_str) {
+ X509* x509 = nullptr;
+ EVP_PKEY* result = nullptr;
+ BIO* bio = BIO_new(BIO_s_mem());
+ size_t len = strlen(x509_str);
+ GPR_ASSERT(len < INT_MAX);
+ BIO_write(bio, x509_str, static_cast<int>(len));
+ x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
+ if (x509 == nullptr) {
+ gpr_log(GPR_ERROR, "Unable to parse x509 cert.");
+ goto end;
+ }
+ result = X509_get_pubkey(x509);
+ if (result == nullptr) {
+ gpr_log(GPR_ERROR, "Cannot find public key in X509 cert.");
+ }
+
+end:
+ BIO_free(bio);
+ X509_free(x509);
+ return result;
+}
+
+static BIGNUM* bignum_from_base64(const char* b64) {
+ BIGNUM* result = nullptr;
+ grpc_slice bin;
+
+ if (b64 == nullptr) return nullptr;
+ bin = grpc_base64_decode(b64, 1);
+ if (GRPC_SLICE_IS_EMPTY(bin)) {
+ gpr_log(GPR_ERROR, "Invalid base64 for big num.");
+ return nullptr;
+ }
+ result = BN_bin2bn(GRPC_SLICE_START_PTR(bin),
+ TSI_SIZE_AS_SIZE(GRPC_SLICE_LENGTH(bin)), nullptr);
+ grpc_slice_unref_internal(bin);
+ return result;
+}
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+
+// Provide compatibility across OpenSSL 1.02 and 1.1.
+static int RSA_set0_key(RSA* r, BIGNUM* n, BIGNUM* e, BIGNUM* d) {
+ /* If the fields n and e in r are NULL, the corresponding input
+ * parameters MUST be non-NULL for n and e. d may be
+ * left NULL (in case only the public key is used).
+ */
+ if ((r->n == nullptr && n == nullptr) || (r->e == nullptr && e == nullptr)) {
+ return 0;
+ }
+
+ if (n != nullptr) {
+ BN_free(r->n);
+ r->n = n;
+ }
+ if (e != nullptr) {
+ BN_free(r->e);
+ r->e = e;
+ }
+ if (d != nullptr) {
+ BN_free(r->d);
+ r->d = d;
+ }
+
+ return 1;
+}
+#endif // OPENSSL_VERSION_NUMBER < 0x10100000L
+
static EVP_PKEY* pkey_from_jwk(const Json& json, const char* kty) {
- RSA* rsa = nullptr;
- EVP_PKEY* result = nullptr;
- BIGNUM* tmp_n = nullptr;
- BIGNUM* tmp_e = nullptr;
+ RSA* rsa = nullptr;
+ EVP_PKEY* result = nullptr;
+ BIGNUM* tmp_n = nullptr;
+ BIGNUM* tmp_e = nullptr;
Json::Object::const_iterator it;
-
+
GPR_ASSERT(json.type() == Json::Type::OBJECT);
GPR_ASSERT(kty != nullptr);
- if (strcmp(kty, "RSA") != 0) {
- gpr_log(GPR_ERROR, "Unsupported key type %s.", kty);
- goto end;
- }
- rsa = RSA_new();
- if (rsa == nullptr) {
- gpr_log(GPR_ERROR, "Could not create rsa key.");
- goto end;
- }
+ if (strcmp(kty, "RSA") != 0) {
+ gpr_log(GPR_ERROR, "Unsupported key type %s.", kty);
+ goto end;
+ }
+ rsa = RSA_new();
+ if (rsa == nullptr) {
+ gpr_log(GPR_ERROR, "Could not create rsa key.");
+ goto end;
+ }
it = json.object_value().find("n");
if (it == json.object_value().end()) {
gpr_log(GPR_ERROR, "Missing RSA public key field.");
goto end;
- }
+ }
tmp_n = bignum_from_base64(validate_string_field(it->second, "n"));
if (tmp_n == nullptr) goto end;
it = json.object_value().find("e");
if (it == json.object_value().end()) {
- gpr_log(GPR_ERROR, "Missing RSA public key field.");
- goto end;
- }
+ gpr_log(GPR_ERROR, "Missing RSA public key field.");
+ goto end;
+ }
tmp_e = bignum_from_base64(validate_string_field(it->second, "e"));
if (tmp_e == nullptr) goto end;
- if (!RSA_set0_key(rsa, tmp_n, tmp_e, nullptr)) {
- gpr_log(GPR_ERROR, "Cannot set RSA key from inputs.");
- goto end;
- }
- /* RSA_set0_key takes ownership on success. */
- tmp_n = nullptr;
- tmp_e = nullptr;
- result = EVP_PKEY_new();
- EVP_PKEY_set1_RSA(result, rsa); /* uprefs rsa. */
-
-end:
- RSA_free(rsa);
- BN_free(tmp_n);
- BN_free(tmp_e);
- return result;
-}
-
+ if (!RSA_set0_key(rsa, tmp_n, tmp_e, nullptr)) {
+ gpr_log(GPR_ERROR, "Cannot set RSA key from inputs.");
+ goto end;
+ }
+ /* RSA_set0_key takes ownership on success. */
+ tmp_n = nullptr;
+ tmp_e = nullptr;
+ result = EVP_PKEY_new();
+ EVP_PKEY_set1_RSA(result, rsa); /* uprefs rsa. */
+
+end:
+ RSA_free(rsa);
+ BN_free(tmp_n);
+ BN_free(tmp_e);
+ return result;
+}
+
static EVP_PKEY* find_verification_key(const Json& json, const char* header_alg,
- const char* header_kid) {
- /* Try to parse the json as a JWK set:
- https://tools.ietf.org/html/rfc7517#section-5. */
+ const char* header_kid) {
+ /* Try to parse the json as a JWK set:
+ https://tools.ietf.org/html/rfc7517#section-5. */
const Json* jwt_keys = find_property_by_name(json, "keys");
if (jwt_keys == nullptr) {
- /* Use the google proprietary format which is:
- { <kid1>: <x5091>, <kid2>: <x5092>, ... } */
+ /* Use the google proprietary format which is:
+ { <kid1>: <x5091>, <kid2>: <x5092>, ... } */
const Json* cur = find_property_by_name(json, header_kid);
- if (cur == nullptr) return nullptr;
+ if (cur == nullptr) return nullptr;
return extract_pkey_from_x509(cur->string_value().c_str());
- }
+ }
if (jwt_keys->type() != Json::Type::ARRAY) {
- gpr_log(GPR_ERROR,
- "Unexpected value type of keys property in jwks key set.");
- return nullptr;
- }
- /* Key format is specified in:
- https://tools.ietf.org/html/rfc7518#section-6. */
+ gpr_log(GPR_ERROR,
+ "Unexpected value type of keys property in jwks key set.");
+ return nullptr;
+ }
+ /* Key format is specified in:
+ https://tools.ietf.org/html/rfc7518#section-6. */
for (const Json& jkey : jwt_keys->array_value()) {
if (jkey.type() != Json::Type::OBJECT) continue;
- const char* alg = nullptr;
+ const char* alg = nullptr;
auto it = jkey.object_value().find("alg");
if (it != jkey.object_value().end()) {
alg = validate_string_field(it->second, "alg");
}
- const char* kid = nullptr;
+ const char* kid = nullptr;
it = jkey.object_value().find("kid");
if (it != jkey.object_value().end()) {
kid = validate_string_field(it->second, "kid");
}
- const char* kty = nullptr;
+ const char* kty = nullptr;
it = jkey.object_value().find("kty");
if (it != jkey.object_value().end()) {
kty = validate_string_field(it->second, "kty");
- }
- if (alg != nullptr && kid != nullptr && kty != nullptr &&
- strcmp(kid, header_kid) == 0 && strcmp(alg, header_alg) == 0) {
- return pkey_from_jwk(jkey, kty);
- }
- }
- gpr_log(GPR_ERROR,
- "Could not find matching key in key set for kid=%s and alg=%s",
- header_kid, header_alg);
- return nullptr;
-}
-
-static int verify_jwt_signature(EVP_PKEY* key, const char* alg,
+ }
+ if (alg != nullptr && kid != nullptr && kty != nullptr &&
+ strcmp(kid, header_kid) == 0 && strcmp(alg, header_alg) == 0) {
+ return pkey_from_jwk(jkey, kty);
+ }
+ }
+ gpr_log(GPR_ERROR,
+ "Could not find matching key in key set for kid=%s and alg=%s",
+ header_kid, header_alg);
+ return nullptr;
+}
+
+static int verify_jwt_signature(EVP_PKEY* key, const char* alg,
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;
-
- GPR_ASSERT(md != nullptr); /* Checked before. */
- if (md_ctx == nullptr) {
- gpr_log(GPR_ERROR, "Could not create EVP_MD_CTX.");
- goto end;
- }
- if (EVP_DigestVerifyInit(md_ctx, nullptr, md, nullptr, key) != 1) {
- gpr_log(GPR_ERROR, "EVP_DigestVerifyInit failed.");
- goto end;
- }
- if (EVP_DigestVerifyUpdate(md_ctx, GRPC_SLICE_START_PTR(signed_data),
- GRPC_SLICE_LENGTH(signed_data)) != 1) {
- gpr_log(GPR_ERROR, "EVP_DigestVerifyUpdate failed.");
- goto end;
- }
- if (EVP_DigestVerifyFinal(md_ctx, GRPC_SLICE_START_PTR(signature),
- GRPC_SLICE_LENGTH(signature)) != 1) {
- gpr_log(GPR_ERROR, "JWT signature verification failed.");
- goto end;
- }
- result = 1;
-
-end:
- EVP_MD_CTX_destroy(md_ctx);
- return result;
-}
-
+ EVP_MD_CTX* md_ctx = EVP_MD_CTX_create();
+ const EVP_MD* md = evp_md_from_alg(alg);
+ int result = 0;
+
+ GPR_ASSERT(md != nullptr); /* Checked before. */
+ if (md_ctx == nullptr) {
+ gpr_log(GPR_ERROR, "Could not create EVP_MD_CTX.");
+ goto end;
+ }
+ if (EVP_DigestVerifyInit(md_ctx, nullptr, md, nullptr, key) != 1) {
+ gpr_log(GPR_ERROR, "EVP_DigestVerifyInit failed.");
+ goto end;
+ }
+ if (EVP_DigestVerifyUpdate(md_ctx, GRPC_SLICE_START_PTR(signed_data),
+ GRPC_SLICE_LENGTH(signed_data)) != 1) {
+ gpr_log(GPR_ERROR, "EVP_DigestVerifyUpdate failed.");
+ goto end;
+ }
+ if (EVP_DigestVerifyFinal(md_ctx, GRPC_SLICE_START_PTR(signature),
+ GRPC_SLICE_LENGTH(signature)) != 1) {
+ gpr_log(GPR_ERROR, "JWT signature verification failed.");
+ goto end;
+ }
+ result = 1;
+
+end:
+ EVP_MD_CTX_destroy(md_ctx);
+ return result;
+}
+
static void on_keys_retrieved(void* user_data, grpc_error* /*error*/) {
- verifier_cb_ctx* ctx = static_cast<verifier_cb_ctx*>(user_data);
+ 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;
- grpc_jwt_verifier_status status = GRPC_JWT_VERIFIER_GENERIC_ERROR;
- grpc_jwt_claims* claims = nullptr;
-
+ EVP_PKEY* verification_key = nullptr;
+ grpc_jwt_verifier_status status = GRPC_JWT_VERIFIER_GENERIC_ERROR;
+ grpc_jwt_claims* claims = nullptr;
+
if (json.type() == Json::Type::JSON_NULL) {
- status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR;
- goto end;
- }
- verification_key =
- find_verification_key(json, ctx->header->alg, ctx->header->kid);
- if (verification_key == nullptr) {
- gpr_log(GPR_ERROR, "Could not find verification key with kid %s.",
- ctx->header->kid);
- status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR;
- goto end;
- }
-
- if (!verify_jwt_signature(verification_key, ctx->header->alg, ctx->signature,
- ctx->signed_data)) {
- status = GRPC_JWT_VERIFIER_BAD_SIGNATURE;
- goto end;
- }
-
- status = grpc_jwt_claims_check(ctx->claims, ctx->audience);
- if (status == GRPC_JWT_VERIFIER_OK) {
- /* Pass ownership. */
- claims = ctx->claims;
- ctx->claims = nullptr;
- }
-
-end:
- EVP_PKEY_free(verification_key);
- ctx->user_cb(ctx->user_data, status, claims);
- verifier_cb_ctx_destroy(ctx);
-}
-
+ status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR;
+ goto end;
+ }
+ verification_key =
+ find_verification_key(json, ctx->header->alg, ctx->header->kid);
+ if (verification_key == nullptr) {
+ gpr_log(GPR_ERROR, "Could not find verification key with kid %s.",
+ ctx->header->kid);
+ status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR;
+ goto end;
+ }
+
+ if (!verify_jwt_signature(verification_key, ctx->header->alg, ctx->signature,
+ ctx->signed_data)) {
+ status = GRPC_JWT_VERIFIER_BAD_SIGNATURE;
+ goto end;
+ }
+
+ status = grpc_jwt_claims_check(ctx->claims, ctx->audience);
+ if (status == GRPC_JWT_VERIFIER_OK) {
+ /* Pass ownership. */
+ claims = ctx->claims;
+ ctx->claims = nullptr;
+ }
+
+end:
+ EVP_PKEY_free(verification_key);
+ ctx->user_cb(ctx->user_data, status, claims);
+ verifier_cb_ctx_destroy(ctx);
+}
+
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];
+ 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);
- grpc_httpcli_request req;
- const char* jwks_uri;
- grpc_resource_quota* resource_quota = nullptr;
+ grpc_httpcli_request req;
+ const char* jwks_uri;
+ grpc_resource_quota* resource_quota = nullptr;
const Json* cur;
-
- /* TODO(jboeuf): Cache the jwks_uri in order to avoid this hop next time. */
+
+ /* TODO(jboeuf): Cache the jwks_uri in order to avoid this hop next time. */
if (json.type() == Json::Type::JSON_NULL) goto error;
- cur = find_property_by_name(json, "jwks_uri");
- if (cur == nullptr) {
- gpr_log(GPR_ERROR, "Could not find jwks_uri in openid config.");
- goto error;
- }
+ cur = find_property_by_name(json, "jwks_uri");
+ if (cur == nullptr) {
+ gpr_log(GPR_ERROR, "Could not find jwks_uri in openid config.");
+ goto error;
+ }
jwks_uri = validate_string_field(*cur, "jwks_uri");
- if (jwks_uri == nullptr) goto error;
- if (strstr(jwks_uri, "https://") != jwks_uri) {
- gpr_log(GPR_ERROR, "Invalid non https jwks_uri: %s.", jwks_uri);
- goto error;
- }
- jwks_uri += 8;
- req.handshaker = &grpc_httpcli_ssl;
- req.host = gpr_strdup(jwks_uri);
- req.http.path = const_cast<char*>(strchr(jwks_uri, '/'));
- if (req.http.path == nullptr) {
- req.http.path = (char*)"";
- } else {
- *(req.host + (req.http.path - jwks_uri)) = '\0';
- }
-
- /* 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. */
- resource_quota = grpc_resource_quota_create("jwt_verifier");
- grpc_httpcli_get(
- &ctx->verifier->http_ctx, &ctx->pollent, resource_quota, &req,
- grpc_core::ExecCtx::Get()->Now() + grpc_jwt_verifier_max_delay,
- GRPC_CLOSURE_CREATE(on_keys_retrieved, ctx, grpc_schedule_on_exec_ctx),
- &ctx->responses[HTTP_RESPONSE_KEYS]);
- grpc_resource_quota_unref_internal(resource_quota);
- gpr_free(req.host);
- return;
-
-error:
- ctx->user_cb(ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, nullptr);
- verifier_cb_ctx_destroy(ctx);
-}
-
-static email_key_mapping* verifier_get_mapping(grpc_jwt_verifier* v,
- const char* email_domain) {
- size_t i;
- if (v->mappings == nullptr) return nullptr;
- for (i = 0; i < v->num_mappings; i++) {
- if (strcmp(email_domain, v->mappings[i].email_domain) == 0) {
- return &v->mappings[i];
- }
- }
- return nullptr;
-}
-
-static void verifier_put_mapping(grpc_jwt_verifier* v, const char* email_domain,
- const char* key_url_prefix) {
- email_key_mapping* mapping = verifier_get_mapping(v, email_domain);
- GPR_ASSERT(v->num_mappings < v->allocated_mappings);
- if (mapping != nullptr) {
- gpr_free(mapping->key_url_prefix);
- mapping->key_url_prefix = gpr_strdup(key_url_prefix);
- return;
- }
- v->mappings[v->num_mappings].email_domain = gpr_strdup(email_domain);
- v->mappings[v->num_mappings].key_url_prefix = gpr_strdup(key_url_prefix);
- v->num_mappings++;
- GPR_ASSERT(v->num_mappings <= v->allocated_mappings);
-}
-
-/* Very non-sophisticated way to detect an email address. Should be good
- enough for now... */
-const char* grpc_jwt_issuer_email_domain(const char* issuer) {
- const char* at_sign = strchr(issuer, '@');
- if (at_sign == nullptr) return nullptr;
- const char* email_domain = at_sign + 1;
- if (*email_domain == '\0') return nullptr;
- const char* dot = strrchr(email_domain, '.');
- if (dot == nullptr || dot == email_domain) return email_domain;
- GPR_ASSERT(dot > email_domain);
- /* There may be a subdomain, we just want the domain. */
- dot = static_cast<const char*>(gpr_memrchr(
- (void*)email_domain, '.', static_cast<size_t>(dot - email_domain)));
- if (dot == nullptr) return email_domain;
- return dot + 1;
-}
-
-/* Takes ownership of ctx. */
-static void retrieve_key_and_verify(verifier_cb_ctx* ctx) {
- const char* email_domain;
- grpc_closure* http_cb;
- char* path_prefix = nullptr;
- const char* iss;
- grpc_httpcli_request req;
- grpc_resource_quota* resource_quota = nullptr;
- memset(&req, 0, sizeof(grpc_httpcli_request));
- req.handshaker = &grpc_httpcli_ssl;
- http_response_index rsp_idx;
-
- GPR_ASSERT(ctx != nullptr && ctx->header != nullptr &&
- ctx->claims != nullptr);
- iss = ctx->claims->iss;
- if (ctx->header->kid == nullptr) {
- gpr_log(GPR_ERROR, "Missing kid in jose header.");
- goto error;
- }
- if (iss == nullptr) {
- gpr_log(GPR_ERROR, "Missing iss in claims.");
- goto error;
- }
-
- /* This code relies on:
- https://openid.net/specs/openid-connect-discovery-1_0.html
- Nobody seems to implement the account/email/webfinger part 2. of the spec
- so we will rely instead on email/url mappings if we detect such an issuer.
- Part 4, on the other hand is implemented by both google and salesforce. */
- email_domain = grpc_jwt_issuer_email_domain(iss);
- if (email_domain != nullptr) {
- email_key_mapping* mapping;
- GPR_ASSERT(ctx->verifier != nullptr);
- mapping = verifier_get_mapping(ctx->verifier, email_domain);
- if (mapping == nullptr) {
- gpr_log(GPR_ERROR, "Missing mapping for issuer email.");
- goto error;
- }
- req.host = gpr_strdup(mapping->key_url_prefix);
- path_prefix = strchr(req.host, '/');
- if (path_prefix == nullptr) {
- gpr_asprintf(&req.http.path, "/%s", iss);
- } else {
- *(path_prefix++) = '\0';
- gpr_asprintf(&req.http.path, "/%s/%s", path_prefix, iss);
- }
- http_cb =
- GRPC_CLOSURE_CREATE(on_keys_retrieved, ctx, grpc_schedule_on_exec_ctx);
- rsp_idx = HTTP_RESPONSE_KEYS;
- } else {
- req.host = gpr_strdup(strstr(iss, "https://") == iss ? iss + 8 : iss);
- path_prefix = strchr(req.host, '/');
- if (path_prefix == nullptr) {
- req.http.path = gpr_strdup(GRPC_OPENID_CONFIG_URL_SUFFIX);
- } else {
- *(path_prefix++) = 0;
- gpr_asprintf(&req.http.path, "/%s%s", path_prefix,
- GRPC_OPENID_CONFIG_URL_SUFFIX);
- }
- http_cb = GRPC_CLOSURE_CREATE(on_openid_config_retrieved, ctx,
- grpc_schedule_on_exec_ctx);
- rsp_idx = HTTP_RESPONSE_OPENID;
- }
-
- /* 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. */
- resource_quota = grpc_resource_quota_create("jwt_verifier");
- grpc_httpcli_get(
- &ctx->verifier->http_ctx, &ctx->pollent, resource_quota, &req,
- grpc_core::ExecCtx::Get()->Now() + grpc_jwt_verifier_max_delay, http_cb,
- &ctx->responses[rsp_idx]);
- grpc_resource_quota_unref_internal(resource_quota);
- gpr_free(req.host);
- gpr_free(req.http.path);
- return;
-
-error:
- ctx->user_cb(ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, nullptr);
- verifier_cb_ctx_destroy(ctx);
-}
-
-void grpc_jwt_verifier_verify(grpc_jwt_verifier* verifier,
- grpc_pollset* pollset, const char* jwt,
- const char* audience,
- grpc_jwt_verification_done_cb cb,
- void* user_data) {
- const char* dot = nullptr;
- jose_header* header = nullptr;
- grpc_jwt_claims* claims = nullptr;
- grpc_slice signature;
- size_t signed_jwt_len;
- const char* cur = jwt;
+ if (jwks_uri == nullptr) goto error;
+ if (strstr(jwks_uri, "https://") != jwks_uri) {
+ gpr_log(GPR_ERROR, "Invalid non https jwks_uri: %s.", jwks_uri);
+ goto error;
+ }
+ jwks_uri += 8;
+ req.handshaker = &grpc_httpcli_ssl;
+ req.host = gpr_strdup(jwks_uri);
+ req.http.path = const_cast<char*>(strchr(jwks_uri, '/'));
+ if (req.http.path == nullptr) {
+ req.http.path = (char*)"";
+ } else {
+ *(req.host + (req.http.path - jwks_uri)) = '\0';
+ }
+
+ /* 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. */
+ resource_quota = grpc_resource_quota_create("jwt_verifier");
+ grpc_httpcli_get(
+ &ctx->verifier->http_ctx, &ctx->pollent, resource_quota, &req,
+ grpc_core::ExecCtx::Get()->Now() + grpc_jwt_verifier_max_delay,
+ GRPC_CLOSURE_CREATE(on_keys_retrieved, ctx, grpc_schedule_on_exec_ctx),
+ &ctx->responses[HTTP_RESPONSE_KEYS]);
+ grpc_resource_quota_unref_internal(resource_quota);
+ gpr_free(req.host);
+ return;
+
+error:
+ ctx->user_cb(ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, nullptr);
+ verifier_cb_ctx_destroy(ctx);
+}
+
+static email_key_mapping* verifier_get_mapping(grpc_jwt_verifier* v,
+ const char* email_domain) {
+ size_t i;
+ if (v->mappings == nullptr) return nullptr;
+ for (i = 0; i < v->num_mappings; i++) {
+ if (strcmp(email_domain, v->mappings[i].email_domain) == 0) {
+ return &v->mappings[i];
+ }
+ }
+ return nullptr;
+}
+
+static void verifier_put_mapping(grpc_jwt_verifier* v, const char* email_domain,
+ const char* key_url_prefix) {
+ email_key_mapping* mapping = verifier_get_mapping(v, email_domain);
+ GPR_ASSERT(v->num_mappings < v->allocated_mappings);
+ if (mapping != nullptr) {
+ gpr_free(mapping->key_url_prefix);
+ mapping->key_url_prefix = gpr_strdup(key_url_prefix);
+ return;
+ }
+ v->mappings[v->num_mappings].email_domain = gpr_strdup(email_domain);
+ v->mappings[v->num_mappings].key_url_prefix = gpr_strdup(key_url_prefix);
+ v->num_mappings++;
+ GPR_ASSERT(v->num_mappings <= v->allocated_mappings);
+}
+
+/* Very non-sophisticated way to detect an email address. Should be good
+ enough for now... */
+const char* grpc_jwt_issuer_email_domain(const char* issuer) {
+ const char* at_sign = strchr(issuer, '@');
+ if (at_sign == nullptr) return nullptr;
+ const char* email_domain = at_sign + 1;
+ if (*email_domain == '\0') return nullptr;
+ const char* dot = strrchr(email_domain, '.');
+ if (dot == nullptr || dot == email_domain) return email_domain;
+ GPR_ASSERT(dot > email_domain);
+ /* There may be a subdomain, we just want the domain. */
+ dot = static_cast<const char*>(gpr_memrchr(
+ (void*)email_domain, '.', static_cast<size_t>(dot - email_domain)));
+ if (dot == nullptr) return email_domain;
+ return dot + 1;
+}
+
+/* Takes ownership of ctx. */
+static void retrieve_key_and_verify(verifier_cb_ctx* ctx) {
+ const char* email_domain;
+ grpc_closure* http_cb;
+ char* path_prefix = nullptr;
+ const char* iss;
+ grpc_httpcli_request req;
+ grpc_resource_quota* resource_quota = nullptr;
+ memset(&req, 0, sizeof(grpc_httpcli_request));
+ req.handshaker = &grpc_httpcli_ssl;
+ http_response_index rsp_idx;
+
+ GPR_ASSERT(ctx != nullptr && ctx->header != nullptr &&
+ ctx->claims != nullptr);
+ iss = ctx->claims->iss;
+ if (ctx->header->kid == nullptr) {
+ gpr_log(GPR_ERROR, "Missing kid in jose header.");
+ goto error;
+ }
+ if (iss == nullptr) {
+ gpr_log(GPR_ERROR, "Missing iss in claims.");
+ goto error;
+ }
+
+ /* This code relies on:
+ https://openid.net/specs/openid-connect-discovery-1_0.html
+ Nobody seems to implement the account/email/webfinger part 2. of the spec
+ so we will rely instead on email/url mappings if we detect such an issuer.
+ Part 4, on the other hand is implemented by both google and salesforce. */
+ email_domain = grpc_jwt_issuer_email_domain(iss);
+ if (email_domain != nullptr) {
+ email_key_mapping* mapping;
+ GPR_ASSERT(ctx->verifier != nullptr);
+ mapping = verifier_get_mapping(ctx->verifier, email_domain);
+ if (mapping == nullptr) {
+ gpr_log(GPR_ERROR, "Missing mapping for issuer email.");
+ goto error;
+ }
+ req.host = gpr_strdup(mapping->key_url_prefix);
+ path_prefix = strchr(req.host, '/');
+ if (path_prefix == nullptr) {
+ gpr_asprintf(&req.http.path, "/%s", iss);
+ } else {
+ *(path_prefix++) = '\0';
+ gpr_asprintf(&req.http.path, "/%s/%s", path_prefix, iss);
+ }
+ http_cb =
+ GRPC_CLOSURE_CREATE(on_keys_retrieved, ctx, grpc_schedule_on_exec_ctx);
+ rsp_idx = HTTP_RESPONSE_KEYS;
+ } else {
+ req.host = gpr_strdup(strstr(iss, "https://") == iss ? iss + 8 : iss);
+ path_prefix = strchr(req.host, '/');
+ if (path_prefix == nullptr) {
+ req.http.path = gpr_strdup(GRPC_OPENID_CONFIG_URL_SUFFIX);
+ } else {
+ *(path_prefix++) = 0;
+ gpr_asprintf(&req.http.path, "/%s%s", path_prefix,
+ GRPC_OPENID_CONFIG_URL_SUFFIX);
+ }
+ http_cb = GRPC_CLOSURE_CREATE(on_openid_config_retrieved, ctx,
+ grpc_schedule_on_exec_ctx);
+ rsp_idx = HTTP_RESPONSE_OPENID;
+ }
+
+ /* 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. */
+ resource_quota = grpc_resource_quota_create("jwt_verifier");
+ grpc_httpcli_get(
+ &ctx->verifier->http_ctx, &ctx->pollent, resource_quota, &req,
+ grpc_core::ExecCtx::Get()->Now() + grpc_jwt_verifier_max_delay, http_cb,
+ &ctx->responses[rsp_idx]);
+ grpc_resource_quota_unref_internal(resource_quota);
+ gpr_free(req.host);
+ gpr_free(req.http.path);
+ return;
+
+error:
+ ctx->user_cb(ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, nullptr);
+ verifier_cb_ctx_destroy(ctx);
+}
+
+void grpc_jwt_verifier_verify(grpc_jwt_verifier* verifier,
+ grpc_pollset* pollset, const char* jwt,
+ const char* audience,
+ grpc_jwt_verification_done_cb cb,
+ void* user_data) {
+ const char* dot = nullptr;
+ jose_header* header = nullptr;
+ grpc_jwt_claims* claims = nullptr;
+ grpc_slice signature;
+ size_t signed_jwt_len;
+ const char* cur = jwt;
Json json;
-
- GPR_ASSERT(verifier != nullptr && jwt != nullptr && audience != nullptr &&
- cb != nullptr);
- dot = strchr(cur, '.');
- if (dot == nullptr) goto error;
+
+ GPR_ASSERT(verifier != nullptr && jwt != nullptr && audience != nullptr &&
+ cb != nullptr);
+ dot = strchr(cur, '.');
+ if (dot == nullptr) goto error;
json = parse_json_part_from_jwt(cur, static_cast<size_t>(dot - cur));
if (json.type() == Json::Type::JSON_NULL) goto error;
header = jose_header_from_json(std::move(json));
- if (header == nullptr) goto error;
-
- cur = dot + 1;
- dot = strchr(cur, '.');
- if (dot == nullptr) goto error;
+ if (header == nullptr) goto error;
+
+ cur = dot + 1;
+ dot = strchr(cur, '.');
+ if (dot == nullptr) goto error;
json = parse_json_part_from_jwt(cur, static_cast<size_t>(dot - cur));
if (json.type() == Json::Type::JSON_NULL) goto error;
claims = grpc_jwt_claims_from_json(std::move(json));
- if (claims == nullptr) goto error;
-
- signed_jwt_len = static_cast<size_t>(dot - jwt);
- cur = dot + 1;
- signature = grpc_base64_decode(cur, 1);
- if (GRPC_SLICE_IS_EMPTY(signature)) goto error;
- retrieve_key_and_verify(
- verifier_cb_ctx_create(verifier, pollset, header, claims, audience,
- signature, jwt, signed_jwt_len, user_data, cb));
- return;
-
-error:
- if (header != nullptr) jose_header_destroy(header);
- if (claims != nullptr) grpc_jwt_claims_destroy(claims);
- cb(user_data, GRPC_JWT_VERIFIER_BAD_FORMAT, nullptr);
-}
-
-grpc_jwt_verifier* grpc_jwt_verifier_create(
- const grpc_jwt_verifier_email_domain_key_url_mapping* mappings,
- size_t num_mappings) {
- grpc_jwt_verifier* v =
- static_cast<grpc_jwt_verifier*>(gpr_zalloc(sizeof(grpc_jwt_verifier)));
- grpc_httpcli_context_init(&v->http_ctx);
-
- /* We know at least of one mapping. */
- v->allocated_mappings = 1 + num_mappings;
- v->mappings = static_cast<email_key_mapping*>(
- gpr_malloc(v->allocated_mappings * sizeof(email_key_mapping)));
- verifier_put_mapping(v, GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN,
- GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX);
- /* User-Provided mappings. */
- if (mappings != nullptr) {
- size_t i;
- for (i = 0; i < num_mappings; i++) {
- verifier_put_mapping(v, mappings[i].email_domain,
- mappings[i].key_url_prefix);
- }
- }
- return v;
-}
-
-void grpc_jwt_verifier_destroy(grpc_jwt_verifier* v) {
- size_t i;
- if (v == nullptr) return;
- grpc_httpcli_context_destroy(&v->http_ctx);
- if (v->mappings != nullptr) {
- for (i = 0; i < v->num_mappings; i++) {
- gpr_free(v->mappings[i].email_domain);
- gpr_free(v->mappings[i].key_url_prefix);
- }
- gpr_free(v->mappings);
- }
- gpr_free(v);
-}
+ if (claims == nullptr) goto error;
+
+ signed_jwt_len = static_cast<size_t>(dot - jwt);
+ cur = dot + 1;
+ signature = grpc_base64_decode(cur, 1);
+ if (GRPC_SLICE_IS_EMPTY(signature)) goto error;
+ retrieve_key_and_verify(
+ verifier_cb_ctx_create(verifier, pollset, header, claims, audience,
+ signature, jwt, signed_jwt_len, user_data, cb));
+ return;
+
+error:
+ if (header != nullptr) jose_header_destroy(header);
+ if (claims != nullptr) grpc_jwt_claims_destroy(claims);
+ cb(user_data, GRPC_JWT_VERIFIER_BAD_FORMAT, nullptr);
+}
+
+grpc_jwt_verifier* grpc_jwt_verifier_create(
+ const grpc_jwt_verifier_email_domain_key_url_mapping* mappings,
+ size_t num_mappings) {
+ grpc_jwt_verifier* v =
+ static_cast<grpc_jwt_verifier*>(gpr_zalloc(sizeof(grpc_jwt_verifier)));
+ grpc_httpcli_context_init(&v->http_ctx);
+
+ /* We know at least of one mapping. */
+ v->allocated_mappings = 1 + num_mappings;
+ v->mappings = static_cast<email_key_mapping*>(
+ gpr_malloc(v->allocated_mappings * sizeof(email_key_mapping)));
+ verifier_put_mapping(v, GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN,
+ GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX);
+ /* User-Provided mappings. */
+ if (mappings != nullptr) {
+ size_t i;
+ for (i = 0; i < num_mappings; i++) {
+ verifier_put_mapping(v, mappings[i].email_domain,
+ mappings[i].key_url_prefix);
+ }
+ }
+ return v;
+}
+
+void grpc_jwt_verifier_destroy(grpc_jwt_verifier* v) {
+ size_t i;
+ if (v == nullptr) return;
+ grpc_httpcli_context_destroy(&v->http_ctx);
+ if (v->mappings != nullptr) {
+ for (i = 0; i < v->num_mappings; i++) {
+ gpr_free(v->mappings[i].email_domain);
+ gpr_free(v->mappings[i].key_url_prefix);
+ }
+ gpr_free(v->mappings);
+ }
+ gpr_free(v);
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.h b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.h
index 66ddbf2206b..e81c85bfcb3 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_JWT_JWT_VERIFIER_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_VERIFIER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/json/json.h"
@@ -47,25 +47,25 @@ typedef enum {
GRPC_JWT_VERIFIER_GENERIC_ERROR
} grpc_jwt_verifier_status;
-const char* grpc_jwt_verifier_status_to_string(grpc_jwt_verifier_status status);
+const char* grpc_jwt_verifier_status_to_string(grpc_jwt_verifier_status status);
/* --- grpc_jwt_claims. --- */
typedef struct grpc_jwt_claims grpc_jwt_claims;
-void grpc_jwt_claims_destroy(grpc_jwt_claims* claims);
+void grpc_jwt_claims_destroy(grpc_jwt_claims* claims);
/* Returns the whole JSON tree of the claims. */
const grpc_core::Json* grpc_jwt_claims_json(const grpc_jwt_claims* claims);
/* Access to registered claims in https://tools.ietf.org/html/rfc7519#page-9 */
-const char* grpc_jwt_claims_subject(const grpc_jwt_claims* claims);
-const char* grpc_jwt_claims_issuer(const grpc_jwt_claims* claims);
-const char* grpc_jwt_claims_id(const grpc_jwt_claims* claims);
-const char* grpc_jwt_claims_audience(const grpc_jwt_claims* claims);
-gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims* claims);
-gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims* claims);
-gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims* claims);
+const char* grpc_jwt_claims_subject(const grpc_jwt_claims* claims);
+const char* grpc_jwt_claims_issuer(const grpc_jwt_claims* claims);
+const char* grpc_jwt_claims_id(const grpc_jwt_claims* claims);
+const char* grpc_jwt_claims_audience(const grpc_jwt_claims* claims);
+gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims* claims);
+gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims* claims);
+gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims* claims);
/* --- grpc_jwt_verifier. --- */
@@ -73,16 +73,16 @@ typedef struct grpc_jwt_verifier grpc_jwt_verifier;
struct grpc_jwt_verifier_email_domain_key_url_mapping {
/* The email domain is the part after the @ sign. */
- const char* email_domain;
+ const char* email_domain;
/* The key url prefix will be used to get the public key from the issuer:
https://<key_url_prefix>/<issuer_email>
Therefore the key_url_prefix must NOT contain https://. */
- const char* key_url_prefix;
+ const char* key_url_prefix;
};
/* Globals to control the verifier. Not thread-safe. */
extern gpr_timespec grpc_jwt_verifier_clock_skew;
-extern grpc_millis grpc_jwt_verifier_max_delay;
+extern grpc_millis grpc_jwt_verifier_max_delay;
/* The verifier can be created with some custom mappings to help with key
discovery in the case where the issuer is an email address.
@@ -90,33 +90,33 @@ extern grpc_millis grpc_jwt_verifier_max_delay;
A verifier object has one built-in mapping (unless overridden):
GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN ->
GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX.*/
-grpc_jwt_verifier* grpc_jwt_verifier_create(
- const grpc_jwt_verifier_email_domain_key_url_mapping* mappings,
+grpc_jwt_verifier* grpc_jwt_verifier_create(
+ const grpc_jwt_verifier_email_domain_key_url_mapping* mappings,
size_t num_mappings);
/*The verifier must not be destroyed if there are still outstanding callbacks.*/
-void grpc_jwt_verifier_destroy(grpc_jwt_verifier* verifier);
+void grpc_jwt_verifier_destroy(grpc_jwt_verifier* verifier);
/* User provided callback that will be called when the verification of the JWT
is done (maybe in another thread).
It is the responsibility of the callee to call grpc_jwt_claims_destroy on
the claims. */
-typedef void (*grpc_jwt_verification_done_cb)(void* user_data,
+typedef void (*grpc_jwt_verification_done_cb)(void* user_data,
grpc_jwt_verifier_status status,
- grpc_jwt_claims* claims);
+ grpc_jwt_claims* claims);
/* Verifies for the JWT for the given expected audience. */
-void grpc_jwt_verifier_verify(grpc_jwt_verifier* verifier,
- grpc_pollset* pollset, const char* jwt,
- const char* audience,
+void grpc_jwt_verifier_verify(grpc_jwt_verifier* verifier,
+ grpc_pollset* pollset, const char* jwt,
+ const char* audience,
grpc_jwt_verification_done_cb cb,
- void* user_data);
+ void* user_data);
/* --- TESTING ONLY exposed functions. --- */
grpc_jwt_claims* grpc_jwt_claims_from_json(grpc_core::Json json);
-grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims* claims,
- const char* audience);
-const char* grpc_jwt_issuer_email_domain(const char* issuer);
+grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims* claims,
+ const char* audience);
+const char* grpc_jwt_issuer_email_domain(const char* issuer);
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_VERIFIER_H */
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 552ee37cfcf..39c4cd6e1e0 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
@@ -1,28 +1,28 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/json/json.h"
-#include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
-
-#include <string.h>
-
+#include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h"
+
+#include <string.h>
+
#include "y_absl/container/inlined_vector.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
@@ -39,61 +39,61 @@
#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/security/util/json_util.h"
+#include "src/core/lib/security/util/json_util.h"
#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/uri/uri_parser.h"
-
+
using grpc_core::Json;
-//
-// Auth Refresh Token.
-//
-
-int grpc_auth_refresh_token_is_valid(
- const grpc_auth_refresh_token* refresh_token) {
- return (refresh_token != nullptr) &&
- strcmp(refresh_token->type, GRPC_AUTH_JSON_TYPE_INVALID);
-}
-
-grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json(
+//
+// Auth Refresh Token.
+//
+
+int grpc_auth_refresh_token_is_valid(
+ const grpc_auth_refresh_token* refresh_token) {
+ return (refresh_token != nullptr) &&
+ strcmp(refresh_token->type, GRPC_AUTH_JSON_TYPE_INVALID);
+}
+
+grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json(
const Json& json) {
- grpc_auth_refresh_token result;
- const char* prop_value;
- int success = 0;
+ grpc_auth_refresh_token result;
+ const char* prop_value;
+ int success = 0;
grpc_error* error = GRPC_ERROR_NONE;
-
- memset(&result, 0, sizeof(grpc_auth_refresh_token));
- result.type = GRPC_AUTH_JSON_TYPE_INVALID;
+
+ memset(&result, 0, sizeof(grpc_auth_refresh_token));
+ result.type = GRPC_AUTH_JSON_TYPE_INVALID;
if (json.type() != Json::Type::OBJECT) {
- gpr_log(GPR_ERROR, "Invalid json.");
- goto end;
- }
-
+ gpr_log(GPR_ERROR, "Invalid json.");
+ goto end;
+ }
+
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;
- }
- result.type = GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER;
-
- if (!grpc_copy_json_string_property(json, "client_secret",
- &result.client_secret) ||
- !grpc_copy_json_string_property(json, "client_id", &result.client_id) ||
- !grpc_copy_json_string_property(json, "refresh_token",
- &result.refresh_token)) {
- goto end;
- }
- success = 1;
-
-end:
- if (!success) grpc_auth_refresh_token_destruct(&result);
- return result;
-}
-
-grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string(
- const char* json_string) {
+ if (prop_value == nullptr ||
+ strcmp(prop_value, GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER)) {
+ goto end;
+ }
+ result.type = GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER;
+
+ if (!grpc_copy_json_string_property(json, "client_secret",
+ &result.client_secret) ||
+ !grpc_copy_json_string_property(json, "client_id", &result.client_id) ||
+ !grpc_copy_json_string_property(json, "refresh_token",
+ &result.refresh_token)) {
+ goto end;
+ }
+ success = 1;
+
+end:
+ if (!success) grpc_auth_refresh_token_destruct(&result);
+ return result;
+}
+
+grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string(
+ const char* json_string) {
grpc_error* error = GRPC_ERROR_NONE;
Json json = Json::Parse(json_string, &error);
if (error != GRPC_ERROR_NONE) {
@@ -101,65 +101,65 @@ grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string(
GRPC_ERROR_UNREF(error);
}
return grpc_auth_refresh_token_create_from_json(json);
-}
-
-void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token) {
- if (refresh_token == nullptr) return;
- refresh_token->type = GRPC_AUTH_JSON_TYPE_INVALID;
- if (refresh_token->client_id != nullptr) {
- gpr_free(refresh_token->client_id);
- refresh_token->client_id = nullptr;
- }
- if (refresh_token->client_secret != nullptr) {
- gpr_free(refresh_token->client_secret);
- refresh_token->client_secret = nullptr;
- }
- if (refresh_token->refresh_token != nullptr) {
- gpr_free(refresh_token->refresh_token);
- refresh_token->refresh_token = nullptr;
- }
-}
-
-//
-// Oauth2 Token Fetcher credentials.
-//
-
+}
+
+void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token) {
+ if (refresh_token == nullptr) return;
+ refresh_token->type = GRPC_AUTH_JSON_TYPE_INVALID;
+ if (refresh_token->client_id != nullptr) {
+ gpr_free(refresh_token->client_id);
+ refresh_token->client_id = nullptr;
+ }
+ if (refresh_token->client_secret != nullptr) {
+ gpr_free(refresh_token->client_secret);
+ refresh_token->client_secret = nullptr;
+ }
+ if (refresh_token->refresh_token != nullptr) {
+ gpr_free(refresh_token->refresh_token);
+ refresh_token->refresh_token = nullptr;
+ }
+}
+
+//
+// Oauth2 Token Fetcher credentials.
+//
+
grpc_oauth2_token_fetcher_credentials::
~grpc_oauth2_token_fetcher_credentials() {
GRPC_MDELEM_UNREF(access_token_md_);
gpr_mu_destroy(&mu_);
grpc_pollset_set_destroy(grpc_polling_entity_pollset_set(&pollent_));
grpc_httpcli_context_destroy(&httpcli_context_);
-}
-
-grpc_credentials_status
-grpc_oauth2_token_fetcher_credentials_parse_server_response(
- const grpc_http_response* response, grpc_mdelem* token_md,
- grpc_millis* token_lifetime) {
- char* null_terminated_body = nullptr;
- grpc_credentials_status status = GRPC_CREDENTIALS_OK;
+}
+
+grpc_credentials_status
+grpc_oauth2_token_fetcher_credentials_parse_server_response(
+ const grpc_http_response* response, grpc_mdelem* token_md,
+ grpc_millis* token_lifetime) {
+ char* null_terminated_body = nullptr;
+ grpc_credentials_status status = GRPC_CREDENTIALS_OK;
Json json;
-
- if (response == nullptr) {
- gpr_log(GPR_ERROR, "Received NULL response.");
- status = GRPC_CREDENTIALS_ERROR;
- goto end;
- }
-
- if (response->body_length > 0) {
- null_terminated_body =
- static_cast<char*>(gpr_malloc(response->body_length + 1));
- null_terminated_body[response->body_length] = '\0';
- memcpy(null_terminated_body, response->body, response->body_length);
- }
-
- if (response->status != 200) {
- gpr_log(GPR_ERROR, "Call to http server ended with error %d [%s].",
- response->status,
- null_terminated_body != nullptr ? null_terminated_body : "");
- status = GRPC_CREDENTIALS_ERROR;
- goto end;
- } else {
+
+ if (response == nullptr) {
+ gpr_log(GPR_ERROR, "Received NULL response.");
+ status = GRPC_CREDENTIALS_ERROR;
+ goto end;
+ }
+
+ if (response->body_length > 0) {
+ null_terminated_body =
+ static_cast<char*>(gpr_malloc(response->body_length + 1));
+ null_terminated_body[response->body_length] = '\0';
+ memcpy(null_terminated_body, response->body, response->body_length);
+ }
+
+ if (response->status != 200) {
+ gpr_log(GPR_ERROR, "Call to http server ended with error %d [%s].",
+ response->status,
+ null_terminated_body != nullptr ? null_terminated_body : "");
+ status = GRPC_CREDENTIALS_ERROR;
+ goto end;
+ } else {
const char* access_token = nullptr;
const char* token_type = nullptr;
const char* expires_in = nullptr;
@@ -170,76 +170,76 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response(
gpr_log(GPR_ERROR, "Could not parse JSON from %s: %s",
null_terminated_body, grpc_error_string(error));
GRPC_ERROR_UNREF(error);
- status = GRPC_CREDENTIALS_ERROR;
- goto end;
- }
+ status = GRPC_CREDENTIALS_ERROR;
+ goto end;
+ }
if (json.type() != Json::Type::OBJECT) {
- gpr_log(GPR_ERROR, "Response should be a JSON object");
- status = GRPC_CREDENTIALS_ERROR;
- goto end;
- }
+ gpr_log(GPR_ERROR, "Response should be a JSON object");
+ status = GRPC_CREDENTIALS_ERROR;
+ goto end;
+ }
it = json.object_value().find("access_token");
if (it == json.object_value().end() ||
it->second.type() != Json::Type::STRING) {
- gpr_log(GPR_ERROR, "Missing or invalid access_token in JSON.");
- status = GRPC_CREDENTIALS_ERROR;
- goto end;
- }
+ gpr_log(GPR_ERROR, "Missing or invalid access_token in JSON.");
+ status = GRPC_CREDENTIALS_ERROR;
+ goto end;
+ }
access_token = it->second.string_value().c_str();
it = json.object_value().find("token_type");
if (it == json.object_value().end() ||
it->second.type() != Json::Type::STRING) {
- gpr_log(GPR_ERROR, "Missing or invalid token_type in JSON.");
- status = GRPC_CREDENTIALS_ERROR;
- goto end;
- }
+ gpr_log(GPR_ERROR, "Missing or invalid token_type in JSON.");
+ status = GRPC_CREDENTIALS_ERROR;
+ goto end;
+ }
token_type = it->second.string_value().c_str();
it = json.object_value().find("expires_in");
if (it == json.object_value().end() ||
it->second.type() != Json::Type::NUMBER) {
- gpr_log(GPR_ERROR, "Missing or invalid expires_in in JSON.");
- status = GRPC_CREDENTIALS_ERROR;
- goto end;
- }
+ gpr_log(GPR_ERROR, "Missing or invalid expires_in in JSON.");
+ status = GRPC_CREDENTIALS_ERROR;
+ goto end;
+ }
expires_in = it->second.string_value().c_str();
*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(
+ if (!GRPC_MDISNULL(*token_md)) GRPC_MDELEM_UNREF(*token_md);
+ *token_md = grpc_mdelem_from_slices(
grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_cpp_string(
y_absl::StrCat(token_type, " ", access_token)));
- status = GRPC_CREDENTIALS_OK;
- }
-
-end:
- if (status != GRPC_CREDENTIALS_OK && !GRPC_MDISNULL(*token_md)) {
- GRPC_MDELEM_UNREF(*token_md);
- *token_md = GRPC_MDNULL;
- }
+ status = GRPC_CREDENTIALS_OK;
+ }
+
+end:
+ if (status != GRPC_CREDENTIALS_OK && !GRPC_MDISNULL(*token_md)) {
+ GRPC_MDELEM_UNREF(*token_md);
+ *token_md = GRPC_MDNULL;
+ }
gpr_free(null_terminated_body);
- return status;
-}
-
-static void on_oauth2_token_fetcher_http_response(void* user_data,
- grpc_error* error) {
- GRPC_LOG_IF_ERROR("oauth_fetch", GRPC_ERROR_REF(error));
- grpc_credentials_metadata_request* r =
- static_cast<grpc_credentials_metadata_request*>(user_data);
- grpc_oauth2_token_fetcher_credentials* c =
+ return status;
+}
+
+static void on_oauth2_token_fetcher_http_response(void* user_data,
+ grpc_error* error) {
+ GRPC_LOG_IF_ERROR("oauth_fetch", GRPC_ERROR_REF(error));
+ grpc_credentials_metadata_request* r =
+ static_cast<grpc_credentials_metadata_request*>(user_data);
+ grpc_oauth2_token_fetcher_credentials* c =
reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(r->creds.get());
c->on_http_response(r, error);
}
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_mdelem access_token_md = GRPC_MDNULL;
grpc_millis token_lifetime = 0;
- grpc_credentials_status status =
+ 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;
- // Update cache and grab list of pending requests.
+ // Update cache and grab list of pending requests.
gpr_mu_lock(&mu_);
token_fetch_pending_ = false;
access_token_md_ = GRPC_MDELEM_REF(access_token_md);
@@ -251,37 +251,37 @@ void grpc_oauth2_token_fetcher_credentials::on_http_response(
grpc_oauth2_pending_get_request_metadata* pending_request = pending_requests_;
pending_requests_ = nullptr;
gpr_mu_unlock(&mu_);
- // Invoke callbacks for all pending requests.
- while (pending_request != nullptr) {
+ // Invoke callbacks for all pending requests.
+ while (pending_request != nullptr) {
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 {
+ 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(
"Error occurred when fetching oauth2 token.", &error, 1);
- }
+ }
grpc_core::ExecCtx::Run(DEBUG_LOCATION,
pending_request->on_request_metadata, new_error);
- grpc_polling_entity_del_from_pollset_set(
+ 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;
- pending_request = pending_request->next;
- gpr_free(prev);
- }
- GRPC_MDELEM_UNREF(access_token_md);
+ grpc_oauth2_pending_get_request_metadata* prev = pending_request;
+ pending_request = pending_request->next;
+ gpr_free(prev);
+ }
+ GRPC_MDELEM_UNREF(access_token_md);
Unref();
- grpc_credentials_metadata_request_destroy(r);
-}
-
+ grpc_credentials_metadata_request_destroy(r);
+}
+
bool grpc_oauth2_token_fetcher_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*/) {
- // Check if we can use the cached token.
- grpc_millis refresh_threshold =
- GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS * GPR_MS_PER_SEC;
- grpc_mdelem cached_access_token_md = GRPC_MDNULL;
+ // Check if we can use the cached token.
+ grpc_millis refresh_threshold =
+ GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS * GPR_MS_PER_SEC;
+ grpc_mdelem cached_access_token_md = GRPC_MDNULL;
gpr_mu_lock(&mu_);
if (!GRPC_MDISNULL(access_token_md_) &&
gpr_time_cmp(
@@ -289,68 +289,68 @@ bool grpc_oauth2_token_fetcher_credentials::get_request_metadata(
gpr_time_from_seconds(GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS,
GPR_TIMESPAN)) > 0) {
cached_access_token_md = GRPC_MDELEM_REF(access_token_md_);
- }
- if (!GRPC_MDISNULL(cached_access_token_md)) {
+ }
+ if (!GRPC_MDISNULL(cached_access_token_md)) {
gpr_mu_unlock(&mu_);
- grpc_credentials_mdelem_array_add(md_array, cached_access_token_md);
- GRPC_MDELEM_UNREF(cached_access_token_md);
- return true;
- }
- // Couldn't get the token from the cache.
+ grpc_credentials_mdelem_array_add(md_array, cached_access_token_md);
+ GRPC_MDELEM_UNREF(cached_access_token_md);
+ return true;
+ }
+ // Couldn't get the token from the cache.
// Add request to pending_requests_ and start a new fetch if needed.
- grpc_oauth2_pending_get_request_metadata* pending_request =
- static_cast<grpc_oauth2_pending_get_request_metadata*>(
- gpr_malloc(sizeof(*pending_request)));
- pending_request->md_array = md_array;
- pending_request->on_request_metadata = on_request_metadata;
- pending_request->pollent = pollent;
- grpc_polling_entity_add_to_pollset_set(
+ grpc_oauth2_pending_get_request_metadata* pending_request =
+ static_cast<grpc_oauth2_pending_get_request_metadata*>(
+ gpr_malloc(sizeof(*pending_request)));
+ pending_request->md_array = md_array;
+ pending_request->on_request_metadata = on_request_metadata;
+ pending_request->pollent = pollent;
+ grpc_polling_entity_add_to_pollset_set(
pollent, grpc_polling_entity_pollset_set(&pollent_));
pending_request->next = pending_requests_;
pending_requests_ = pending_request;
- bool start_fetch = false;
+ bool start_fetch = false;
if (!token_fetch_pending_) {
token_fetch_pending_ = true;
- start_fetch = true;
- }
+ start_fetch = true;
+ }
gpr_mu_unlock(&mu_);
- if (start_fetch) {
+ if (start_fetch) {
Ref().release();
fetch_oauth2(grpc_credentials_metadata_request_create(this->Ref()),
&httpcli_context_, &pollent_,
on_oauth2_token_fetcher_http_response,
grpc_core::ExecCtx::Get()->Now() + refresh_threshold);
- }
- return false;
-}
-
+ }
+ return false;
+}
+
void grpc_oauth2_token_fetcher_credentials::cancel_get_request_metadata(
grpc_credentials_mdelem_array* md_array, grpc_error* error) {
gpr_mu_lock(&mu_);
- grpc_oauth2_pending_get_request_metadata* prev = nullptr;
+ grpc_oauth2_pending_get_request_metadata* prev = nullptr;
grpc_oauth2_pending_get_request_metadata* pending_request = pending_requests_;
- while (pending_request != nullptr) {
- if (pending_request->md_array == md_array) {
- // Remove matching pending request from the list.
- if (prev != nullptr) {
- prev->next = pending_request->next;
- } else {
+ while (pending_request != nullptr) {
+ if (pending_request->md_array == md_array) {
+ // Remove matching pending request from the list.
+ if (prev != nullptr) {
+ prev->next = pending_request->next;
+ } else {
pending_requests_ = pending_request->next;
- }
- // Invoke the callback immediately with an error.
+ }
+ // Invoke the callback immediately with an error.
grpc_core::ExecCtx::Run(DEBUG_LOCATION,
pending_request->on_request_metadata,
GRPC_ERROR_REF(error));
- gpr_free(pending_request);
- break;
- }
- prev = pending_request;
- pending_request = pending_request->next;
- }
+ gpr_free(pending_request);
+ break;
+ }
+ prev = pending_request;
+ pending_request = pending_request->next;
+ }
gpr_mu_unlock(&mu_);
- GRPC_ERROR_UNREF(error);
-}
-
+ GRPC_ERROR_UNREF(error);
+}
+
grpc_oauth2_token_fetcher_credentials::grpc_oauth2_token_fetcher_credentials()
: grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2),
token_expiration_(gpr_inf_past(GPR_CLOCK_MONOTONIC)),
@@ -358,24 +358,24 @@ grpc_oauth2_token_fetcher_credentials::grpc_oauth2_token_fetcher_credentials()
grpc_pollset_set_create())) {
gpr_mu_init(&mu_);
grpc_httpcli_context_init(&httpcli_context_);
-}
-
+}
+
TString grpc_oauth2_token_fetcher_credentials::debug_string() {
return "OAuth2TokenFetcherCredentials";
}
-//
-// Google Compute Engine credentials.
-//
-
+//
+// Google Compute Engine credentials.
+//
+
namespace {
-
+
class grpc_compute_engine_token_fetcher_credentials
: public grpc_oauth2_token_fetcher_credentials {
public:
grpc_compute_engine_token_fetcher_credentials() = default;
~grpc_compute_engine_token_fetcher_credentials() override = default;
-
+
protected:
void fetch_oauth2(grpc_credentials_metadata_request* metadata_req,
grpc_httpcli_context* http_context,
@@ -414,70 +414,70 @@ class grpc_compute_engine_token_fetcher_credentials
} // namespace
-grpc_call_credentials* grpc_google_compute_engine_credentials_create(
- void* reserved) {
- GRPC_API_TRACE("grpc_compute_engine_credentials_create(reserved=%p)", 1,
- (reserved));
- GPR_ASSERT(reserved == nullptr);
+grpc_call_credentials* grpc_google_compute_engine_credentials_create(
+ void* reserved) {
+ GRPC_API_TRACE("grpc_compute_engine_credentials_create(reserved=%p)", 1,
+ (reserved));
+ GPR_ASSERT(reserved == nullptr);
return grpc_core::MakeRefCounted<
grpc_compute_engine_token_fetcher_credentials>()
.release();
-}
-
-//
-// Google Refresh Token credentials.
-//
-
+}
+
+//
+// Google Refresh Token credentials.
+//
+
grpc_google_refresh_token_credentials::
~grpc_google_refresh_token_credentials() {
grpc_auth_refresh_token_destruct(&refresh_token_);
-}
-
+}
+
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_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_httpcli_request request;
+ grpc_httpcli_request request;
TString body = y_absl::StrFormat(
GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING, refresh_token_.client_id,
refresh_token_.client_secret, refresh_token_.refresh_token);
- memset(&request, 0, sizeof(grpc_httpcli_request));
- request.host = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_HOST;
- request.http.path = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH;
- request.http.hdr_count = 1;
- request.http.hdrs = &header;
- request.handshaker = &grpc_httpcli_ssl;
- /* 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");
+ memset(&request, 0, sizeof(grpc_httpcli_request));
+ request.host = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_HOST;
+ request.http.path = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH;
+ request.http.hdr_count = 1;
+ request.http.hdrs = &header;
+ request.handshaker = &grpc_httpcli_ssl;
+ /* 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(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_resource_quota_unref_internal(resource_quota);
-}
-
+ grpc_resource_quota_unref_internal(resource_quota);
+}
+
grpc_google_refresh_token_credentials::grpc_google_refresh_token_credentials(
grpc_auth_refresh_token refresh_token)
: refresh_token_(refresh_token) {}
grpc_core::RefCountedPtr<grpc_call_credentials>
-grpc_refresh_token_credentials_create_from_auth_refresh_token(
- grpc_auth_refresh_token refresh_token) {
- if (!grpc_auth_refresh_token_is_valid(&refresh_token)) {
- gpr_log(GPR_ERROR, "Invalid input for refresh token credentials creation");
- return nullptr;
- }
+grpc_refresh_token_credentials_create_from_auth_refresh_token(
+ grpc_auth_refresh_token refresh_token) {
+ if (!grpc_auth_refresh_token_is_valid(&refresh_token)) {
+ gpr_log(GPR_ERROR, "Invalid input for refresh token credentials creation");
+ return nullptr;
+ }
return grpc_core::MakeRefCounted<grpc_google_refresh_token_credentials>(
refresh_token);
-}
-
+}
+
TString grpc_google_refresh_token_credentials::debug_string() {
return y_absl::StrFormat("GoogleRefreshToken{ClientID:%s,%s}",
refresh_token_.client_id,
@@ -486,31 +486,31 @@ TString grpc_google_refresh_token_credentials::debug_string() {
static TString create_loggable_refresh_token(
grpc_auth_refresh_token* token) {
- if (strcmp(token->type, GRPC_AUTH_JSON_TYPE_INVALID) == 0) {
+ if (strcmp(token->type, GRPC_AUTH_JSON_TYPE_INVALID) == 0) {
return "<Invalid json token>";
- }
+ }
return y_absl::StrFormat(
"{\n type: %s\n client_id: %s\n client_secret: "
"<redacted>\n refresh_token: <redacted>\n}",
token->type, token->client_id);
-}
-
-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);
+}
+
+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)) {
- gpr_log(GPR_INFO,
- "grpc_refresh_token_credentials_create(json_refresh_token=%s, "
- "reserved=%p)",
+ gpr_log(GPR_INFO,
+ "grpc_refresh_token_credentials_create(json_refresh_token=%s, "
+ "reserved=%p)",
create_loggable_refresh_token(&token).c_str(), reserved);
- }
- GPR_ASSERT(reserved == nullptr);
+ }
+ GPR_ASSERT(reserved == nullptr);
return grpc_refresh_token_credentials_create_from_auth_refresh_token(token)
.release();
-}
-
-//
+}
+
+//
// STS credentials.
//
@@ -715,26 +715,26 @@ grpc_call_credentials* grpc_sts_credentials_create(
}
//
-// Oauth2 Access Token credentials.
-//
-
+// Oauth2 Access Token credentials.
+//
+
grpc_access_token_credentials::~grpc_access_token_credentials() {
GRPC_MDELEM_UNREF(access_token_md_);
-}
-
+}
+
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_credentials_mdelem_array_add(md_array, access_token_md_);
- return true;
-}
-
+ return true;
+}
+
void grpc_access_token_credentials::cancel_get_request_metadata(
grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) {
- GRPC_ERROR_UNREF(error);
-}
-
+ GRPC_ERROR_UNREF(error);
+}
+
grpc_access_token_credentials::grpc_access_token_credentials(
const char* access_token)
: grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) {
@@ -743,20 +743,20 @@ grpc_access_token_credentials::grpc_access_token_credentials(
grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_cpp_string(y_absl::StrCat("Bearer ", access_token)));
}
-
+
TString grpc_access_token_credentials::debug_string() {
bool access_token_present = !GRPC_MDISNULL(access_token_md_);
return y_absl::StrFormat("AccessTokenCredentials{Token:%s}",
access_token_present ? "present" : "absent");
}
-grpc_call_credentials* grpc_access_token_credentials_create(
- const char* access_token, void* reserved) {
- GRPC_API_TRACE(
- "grpc_access_token_credentials_create(access_token=<redacted>, "
- "reserved=%p)",
- 1, (reserved));
- GPR_ASSERT(reserved == nullptr);
+grpc_call_credentials* grpc_access_token_credentials_create(
+ const char* access_token, void* reserved) {
+ GRPC_API_TRACE(
+ "grpc_access_token_credentials_create(access_token=<redacted>, "
+ "reserved=%p)",
+ 1, (reserved));
+ GPR_ASSERT(reserved == nullptr);
return grpc_core::MakeRefCounted<grpc_access_token_credentials>(access_token)
.release();
-}
+}
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 fd886405cff..c60b0e63da4 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_OAUTH2_OAUTH2_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_OAUTH2_OAUTH2_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include <grpc/grpc_security.h>
@@ -35,19 +35,19 @@
// auth_refresh_token parsing.
struct grpc_auth_refresh_token {
- const char* type;
- char* client_id;
- char* client_secret;
- char* refresh_token;
+ const char* type;
+ char* client_id;
+ char* client_secret;
+ char* refresh_token;
};
/// Returns 1 if the object is valid, 0 otherwise.
int grpc_auth_refresh_token_is_valid(
- const grpc_auth_refresh_token* refresh_token);
+ const grpc_auth_refresh_token* refresh_token);
/// Creates a refresh token object from string. Returns an invalid object if a
/// parsing error has been encountered.
grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string(
- const char* json_string);
+ const char* json_string);
/// Creates a refresh token object from parsed json. Returns an invalid object
/// if a parsing error has been encountered.
@@ -55,7 +55,7 @@ grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json(
const grpc_core::Json& json);
/// Destructs the object.
-void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token);
+void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token);
// -- Oauth2 Token Fetcher credentials --
//
@@ -63,12 +63,12 @@ void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token);
// from an http service.
struct grpc_oauth2_pending_get_request_metadata {
- grpc_credentials_mdelem_array* md_array;
- grpc_closure* on_request_metadata;
- grpc_polling_entity* pollent;
- struct grpc_oauth2_pending_get_request_metadata* next;
+ grpc_credentials_mdelem_array* md_array;
+ grpc_closure* on_request_metadata;
+ grpc_polling_entity* pollent;
+ struct grpc_oauth2_pending_get_request_metadata* next;
};
-
+
class grpc_oauth2_token_fetcher_credentials : public grpc_call_credentials {
public:
grpc_oauth2_token_fetcher_credentials();
@@ -157,8 +157,8 @@ grpc_refresh_token_credentials_create_from_auth_refresh_token(
// Exposed for testing only.
grpc_credentials_status
grpc_oauth2_token_fetcher_credentials_parse_server_response(
- const struct grpc_http_response* response, grpc_mdelem* token_md,
- grpc_millis* token_lifetime);
+ 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
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 40d8fec6e4b..f226d3c86e0 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/credentials/plugin/plugin_credentials.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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/security/credentials/plugin/plugin_credentials.h"
+
+#include <string.h>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/validate_metadata.h"
-
-grpc_core::TraceFlag grpc_plugin_credentials_trace(false, "plugin_credentials");
-
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/validate_metadata.h"
+
+grpc_core::TraceFlag grpc_plugin_credentials_trace(false, "plugin_credentials");
+
grpc_plugin_credentials::~grpc_plugin_credentials() {
gpr_mu_destroy(&mu_);
if (plugin_.state != nullptr && plugin_.destroy != nullptr) {
plugin_.destroy(plugin_.state);
- }
-}
-
+ }
+}
+
TString grpc_plugin_credentials::debug_string() {
char* debug_c_str = nullptr;
if (plugin_.debug_string != nullptr) {
@@ -58,212 +58,212 @@ TString grpc_plugin_credentials::debug_string() {
void grpc_plugin_credentials::pending_request_remove_locked(
pending_request* pending_request) {
- if (pending_request->prev == nullptr) {
+ if (pending_request->prev == nullptr) {
pending_requests_ = pending_request->next;
- } else {
- pending_request->prev->next = pending_request->next;
- }
- if (pending_request->next != nullptr) {
- pending_request->next->prev = pending_request->prev;
- }
-}
-
-// Checks if the request has been cancelled.
-// If not, removes it from the pending list, so that it cannot be
-// cancelled out from under us.
-// When this returns, r->cancelled indicates whether the request was
-// cancelled before completion.
+ } else {
+ pending_request->prev->next = pending_request->next;
+ }
+ if (pending_request->next != nullptr) {
+ pending_request->next->prev = pending_request->prev;
+ }
+}
+
+// Checks if the request has been cancelled.
+// If not, removes it from the pending list, so that it cannot be
+// cancelled out from under us.
+// When this returns, r->cancelled indicates whether the request was
+// cancelled before completion.
void grpc_plugin_credentials::pending_request_complete(pending_request* r) {
GPR_DEBUG_ASSERT(r->creds == this);
gpr_mu_lock(&mu_);
if (!r->cancelled) pending_request_remove_locked(r);
gpr_mu_unlock(&mu_);
- // Ref to credentials not needed anymore.
+ // Ref to credentials not needed anymore.
Unref();
-}
-
-static grpc_error* process_plugin_result(
+}
+
+static grpc_error* process_plugin_result(
grpc_plugin_credentials::pending_request* r, const grpc_metadata* md,
- size_t num_md, grpc_status_code status, const char* error_details) {
- grpc_error* error = GRPC_ERROR_NONE;
- if (status != GRPC_STATUS_OK) {
+ size_t num_md, grpc_status_code status, const char* error_details) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (status != GRPC_STATUS_OK) {
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
y_absl::StrCat("Getting metadata from plugin failed with error: ",
error_details)
.c_str());
- } else {
- bool seen_illegal_header = false;
- for (size_t i = 0; i < num_md; ++i) {
- if (!GRPC_LOG_IF_ERROR("validate_metadata_from_plugin",
- grpc_validate_header_key_is_legal(md[i].key))) {
- seen_illegal_header = true;
- break;
+ } else {
+ bool seen_illegal_header = false;
+ for (size_t i = 0; i < num_md; ++i) {
+ if (!GRPC_LOG_IF_ERROR("validate_metadata_from_plugin",
+ grpc_validate_header_key_is_legal(md[i].key))) {
+ seen_illegal_header = true;
+ break;
} 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))) {
- gpr_log(GPR_ERROR, "Plugin added invalid metadata value.");
- seen_illegal_header = true;
- break;
- }
- }
- if (seen_illegal_header) {
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal metadata");
- } else {
- for (size_t i = 0; i < num_md; ++i) {
- grpc_mdelem mdelem =
+ !GRPC_LOG_IF_ERROR(
+ "validate_metadata_from_plugin",
+ grpc_validate_header_nonbin_value_is_legal(md[i].value))) {
+ gpr_log(GPR_ERROR, "Plugin added invalid metadata value.");
+ seen_illegal_header = true;
+ break;
+ }
+ }
+ if (seen_illegal_header) {
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Illegal metadata");
+ } else {
+ for (size_t i = 0; i < num_md; ++i) {
+ grpc_mdelem mdelem =
grpc_mdelem_create(md[i].key, md[i].value, nullptr);
- grpc_credentials_mdelem_array_add(r->md_array, mdelem);
- GRPC_MDELEM_UNREF(mdelem);
- }
- }
- }
- return error;
-}
-
-static void plugin_md_request_metadata_ready(void* request,
- const grpc_metadata* md,
- size_t num_md,
- grpc_status_code status,
- const char* error_details) {
- /* called from application code */
+ grpc_credentials_mdelem_array_add(r->md_array, mdelem);
+ GRPC_MDELEM_UNREF(mdelem);
+ }
+ }
+ }
+ return error;
+}
+
+static void plugin_md_request_metadata_ready(void* request,
+ const grpc_metadata* md,
+ size_t num_md,
+ grpc_status_code status,
+ const char* error_details) {
+ /* called from application code */
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_FINISHED |
- GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP);
+ grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_FINISHED |
+ 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)) {
- gpr_log(GPR_INFO,
- "plugin_credentials[%p]: request %p: plugin returned "
- "asynchronously",
- r->creds, r);
- }
- // Remove request from pending list if not previously cancelled.
+ gpr_log(GPR_INFO,
+ "plugin_credentials[%p]: request %p: plugin returned "
+ "asynchronously",
+ r->creds, r);
+ }
+ // Remove request from pending list if not previously cancelled.
r->creds->pending_request_complete(r);
- // If it has not been cancelled, process it.
- if (!r->cancelled) {
- grpc_error* error =
- process_plugin_result(r, md, num_md, status, error_details);
+ // If it has not been cancelled, process it.
+ 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)) {
- gpr_log(GPR_INFO,
- "plugin_credentials[%p]: request %p: plugin was previously "
- "cancelled",
- r->creds, r);
- }
- gpr_free(r);
-}
-
+ gpr_log(GPR_INFO,
+ "plugin_credentials[%p]: request %p: plugin was previously "
+ "cancelled",
+ r->creds, r);
+ }
+ gpr_free(r);
+}
+
bool grpc_plugin_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) {
- bool retval = true; // Synchronous return.
+ bool retval = true; // Synchronous return.
if (plugin_.get_metadata != nullptr) {
- // Create pending_request object.
+ // Create pending_request object.
pending_request* request =
static_cast<pending_request*>(gpr_zalloc(sizeof(*request)));
request->creds = this;
request->md_array = md_array;
request->on_request_metadata = on_request_metadata;
- // Add it to the pending list.
+ // Add it to the pending list.
gpr_mu_lock(&mu_);
if (pending_requests_ != nullptr) {
pending_requests_->prev = request;
- }
+ }
request->next = pending_requests_;
pending_requests_ = request;
gpr_mu_unlock(&mu_);
- // Invoke the plugin. The callback holds a ref to us.
+ // Invoke the plugin. The callback holds a ref to us.
if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
- gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: invoking plugin",
+ gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: invoking plugin",
this, request);
- }
+ }
Ref().release();
- grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX];
- size_t num_creds_md = 0;
- grpc_status_code status = GRPC_STATUS_OK;
- const char* error_details = nullptr;
+ grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX];
+ size_t num_creds_md = 0;
+ grpc_status_code status = GRPC_STATUS_OK;
+ const char* error_details = nullptr;
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)) {
- gpr_log(GPR_INFO,
- "plugin_credentials[%p]: request %p: plugin will return "
- "asynchronously",
+ gpr_log(GPR_INFO,
+ "plugin_credentials[%p]: request %p: plugin will return "
+ "asynchronously",
this, request);
- }
- return false; // Asynchronous return.
- }
- // Returned synchronously.
- // Remove request from pending list if not previously cancelled.
+ }
+ return false; // Asynchronous return.
+ }
+ // Returned synchronously.
+ // Remove request from pending list if not previously cancelled.
request->creds->pending_request_complete(request);
- // If the request was cancelled, the error will have been returned
- // asynchronously by plugin_cancel_get_request_metadata(), so return
- // false. Otherwise, process the result.
+ // If the request was cancelled, the error will have been returned
+ // 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)) {
- gpr_log(GPR_INFO,
- "plugin_credentials[%p]: request %p was cancelled, error "
- "will be returned asynchronously",
+ gpr_log(GPR_INFO,
+ "plugin_credentials[%p]: request %p was cancelled, error "
+ "will be returned asynchronously",
this, request);
- }
- retval = false;
- } else {
+ }
+ retval = false;
+ } else {
if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) {
- gpr_log(GPR_INFO,
- "plugin_credentials[%p]: request %p: plugin returned "
- "synchronously",
+ gpr_log(GPR_INFO,
+ "plugin_credentials[%p]: request %p: plugin returned "
+ "synchronously",
this, request);
- }
+ }
*error = process_plugin_result(request, creds_md, num_creds_md, status,
error_details);
- }
- // Clean up.
- for (size_t i = 0; i < num_creds_md; ++i) {
- grpc_slice_unref_internal(creds_md[i].key);
- grpc_slice_unref_internal(creds_md[i].value);
- }
- gpr_free((void*)error_details);
+ }
+ // Clean up.
+ for (size_t i = 0; i < num_creds_md; ++i) {
+ grpc_slice_unref_internal(creds_md[i].key);
+ grpc_slice_unref_internal(creds_md[i].value);
+ }
+ gpr_free((void*)error_details);
gpr_free(request);
- }
- return retval;
-}
-
+ }
+ return retval;
+}
+
void grpc_plugin_credentials::cancel_get_request_metadata(
grpc_credentials_mdelem_array* md_array, grpc_error* error) {
gpr_mu_lock(&mu_);
for (pending_request* pending_request = pending_requests_;
- pending_request != nullptr; pending_request = pending_request->next) {
- if (pending_request->md_array == md_array) {
+ pending_request != nullptr; pending_request = pending_request->next) {
+ if (pending_request->md_array == md_array) {
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;
+ pending_request);
+ }
+ pending_request->cancelled = true;
grpc_core::ExecCtx::Run(DEBUG_LOCATION,
pending_request->on_request_metadata,
GRPC_ERROR_REF(error));
pending_request_remove_locked(pending_request);
- break;
- }
- }
+ break;
+ }
+ }
gpr_mu_unlock(&mu_);
- GRPC_ERROR_UNREF(error);
-}
-
+ GRPC_ERROR_UNREF(error);
+}
+
grpc_plugin_credentials::grpc_plugin_credentials(
grpc_metadata_credentials_plugin plugin,
grpc_security_level min_security_level)
: grpc_call_credentials(plugin.type, min_security_level), plugin_(plugin) {
gpr_mu_init(&mu_);
}
-
-grpc_call_credentials* grpc_metadata_credentials_create_from_plugin(
+
+grpc_call_credentials* grpc_metadata_credentials_create_from_plugin(
grpc_metadata_credentials_plugin plugin,
grpc_security_level min_security_level, void* reserved) {
- GRPC_API_TRACE("grpc_metadata_credentials_create_from_plugin(reserved=%p)", 1,
- (reserved));
- GPR_ASSERT(reserved == nullptr);
+ GRPC_API_TRACE("grpc_metadata_credentials_create_from_plugin(reserved=%p)", 1,
+ (reserved));
+ GPR_ASSERT(reserved == nullptr);
return new grpc_plugin_credentials(plugin, min_security_level);
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h
index 78bca05fb90..333bed36c5f 100644
--- a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h
+++ b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h
@@ -1,30 +1,30 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_PLUGIN_PLUGIN_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_PLUGIN_PLUGIN_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/security/credentials/credentials.h"
-extern grpc_core::TraceFlag grpc_plugin_credentials_trace;
-
+extern grpc_core::TraceFlag grpc_plugin_credentials_trace;
+
// This type is forward declared as a C struct and we cannot define it as a
// class. Otherwise, compiler will complain about type mismatch due to
// -Wmismatched-tags.
@@ -38,11 +38,11 @@ struct grpc_plugin_credentials final : public grpc_call_credentials {
struct pending_request* prev;
struct pending_request* next;
};
-
+
explicit grpc_plugin_credentials(grpc_metadata_credentials_plugin plugin,
grpc_security_level min_security_level);
~grpc_plugin_credentials() override;
-
+
bool get_request_metadata(grpc_polling_entity* pollent,
grpc_auth_metadata_context context,
grpc_credentials_mdelem_array* md_array,
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 3bb7790f5c9..1160f89d825 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
@@ -1,56 +1,56 @@
-/*
- *
- * 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/security/credentials/ssl/ssl_credentials.h"
-
-#include <string.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/tsi/ssl_transport_security.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-//
-// SSL Channel Credentials.
-//
-
-void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp,
- size_t num_key_cert_pairs) {
- if (kp == nullptr) return;
- for (size_t i = 0; i < num_key_cert_pairs; i++) {
- gpr_free((void*)kp[i].private_key);
- gpr_free((void*)kp[i].cert_chain);
- }
- gpr_free(kp);
-}
-
+/*
+ *
+ * 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/security/credentials/ssl/ssl_credentials.h"
+
+#include <string.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/tsi/ssl_transport_security.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+//
+// SSL Channel Credentials.
+//
+
+void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp,
+ size_t num_key_cert_pairs) {
+ if (kp == nullptr) return;
+ for (size_t i = 0; i < num_key_cert_pairs; i++) {
+ gpr_free((void*)kp[i].private_key);
+ gpr_free((void*)kp[i].cert_chain);
+ }
+ gpr_free(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)
: grpc_channel_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_SSL) {
build_config(pem_root_certs, pem_key_cert_pair, verify_options);
-}
-
+}
+
grpc_ssl_credentials::~grpc_ssl_credentials() {
gpr_free(config_.pem_root_certs);
grpc_tsi_ssl_pem_key_cert_pairs_destroy(config_.pem_key_cert_pair, 1);
@@ -63,51 +63,51 @@ grpc_ssl_credentials::~grpc_ssl_credentials() {
grpc_core::RefCountedPtr<grpc_channel_security_connector>
grpc_ssl_credentials::create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
- const char* target, const grpc_channel_args* args,
+ const char* target, const grpc_channel_args* args,
grpc_channel_args** new_args) {
- const char* overridden_target_name = nullptr;
- tsi_ssl_session_cache* ssl_session_cache = nullptr;
- for (size_t i = 0; args && i < args->num_args; i++) {
- grpc_arg* arg = &args->args[i];
- if (strcmp(arg->key, GRPC_SSL_TARGET_NAME_OVERRIDE_ARG) == 0 &&
- arg->type == GRPC_ARG_STRING) {
- overridden_target_name = arg->value.string;
- }
- if (strcmp(arg->key, GRPC_SSL_SESSION_CACHE_ARG) == 0 &&
- arg->type == GRPC_ARG_POINTER) {
- ssl_session_cache =
- static_cast<tsi_ssl_session_cache*>(arg->value.pointer.p);
- }
- }
+ const char* overridden_target_name = nullptr;
+ tsi_ssl_session_cache* ssl_session_cache = nullptr;
+ for (size_t i = 0; args && i < args->num_args; i++) {
+ grpc_arg* arg = &args->args[i];
+ if (strcmp(arg->key, GRPC_SSL_TARGET_NAME_OVERRIDE_ARG) == 0 &&
+ arg->type == GRPC_ARG_STRING) {
+ overridden_target_name = arg->value.string;
+ }
+ if (strcmp(arg->key, GRPC_SSL_SESSION_CACHE_ARG) == 0 &&
+ arg->type == GRPC_ARG_POINTER) {
+ ssl_session_cache =
+ static_cast<tsi_ssl_session_cache*>(arg->value.pointer.p);
+ }
+ }
grpc_core::RefCountedPtr<grpc_channel_security_connector> sc =
grpc_ssl_channel_security_connector_create(
this->Ref(), std::move(call_creds), &config_, target,
overridden_target_name, ssl_session_cache);
if (sc == nullptr) {
return sc;
- }
- grpc_arg new_arg = grpc_channel_arg_string_create(
- (char*)GRPC_ARG_HTTP2_SCHEME, (char*)"https");
- *new_args = grpc_channel_args_copy_and_add(args, &new_arg, 1);
+ }
+ grpc_arg new_arg = grpc_channel_arg_string_create(
+ (char*)GRPC_ARG_HTTP2_SCHEME, (char*)"https");
+ *new_args = grpc_channel_args_copy_and_add(args, &new_arg, 1);
return sc;
-}
-
+}
+
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) {
config_.pem_root_certs = gpr_strdup(pem_root_certs);
- if (pem_key_cert_pair != nullptr) {
- GPR_ASSERT(pem_key_cert_pair->private_key != nullptr);
- GPR_ASSERT(pem_key_cert_pair->cert_chain != nullptr);
+ if (pem_key_cert_pair != nullptr) {
+ GPR_ASSERT(pem_key_cert_pair->private_key != nullptr);
+ GPR_ASSERT(pem_key_cert_pair->cert_chain != nullptr);
config_.pem_key_cert_pair = static_cast<tsi_ssl_pem_key_cert_pair*>(
- gpr_zalloc(sizeof(tsi_ssl_pem_key_cert_pair)));
+ gpr_zalloc(sizeof(tsi_ssl_pem_key_cert_pair)));
config_.pem_key_cert_pair->cert_chain =
- gpr_strdup(pem_key_cert_pair->cert_chain);
+ gpr_strdup(pem_key_cert_pair->cert_chain);
config_.pem_key_cert_pair->private_key =
- gpr_strdup(pem_key_cert_pair->private_key);
+ gpr_strdup(pem_key_cert_pair->private_key);
} else {
config_.pem_key_cert_pair = nullptr;
- }
+ }
if (verify_options != nullptr) {
memcpy(&config_.verify_options, verify_options,
sizeof(verify_peer_options));
@@ -115,8 +115,8 @@ void grpc_ssl_credentials::build_config(
// Otherwise set all options to default values
memset(&config_.verify_options, 0, sizeof(verify_peer_options));
}
-}
-
+}
+
void grpc_ssl_credentials::set_min_tls_version(
grpc_tls_version min_tls_version) {
config_.min_tls_version = min_tls_version;
@@ -129,22 +129,22 @@ void grpc_ssl_credentials::set_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. */
-grpc_channel_credentials* grpc_ssl_credentials_create(
- const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair,
+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) {
- GRPC_API_TRACE(
- "grpc_ssl_credentials_create(pem_root_certs=%s, "
- "pem_key_cert_pair=%p, "
+ GRPC_API_TRACE(
+ "grpc_ssl_credentials_create(pem_root_certs=%s, "
+ "pem_key_cert_pair=%p, "
"verify_options=%p, "
- "reserved=%p)",
+ "reserved=%p)",
4, (pem_root_certs, pem_key_cert_pair, verify_options, reserved));
- GPR_ASSERT(reserved == nullptr);
+ 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) {
@@ -160,16 +160,16 @@ grpc_channel_credentials* grpc_ssl_credentials_create_ex(
verify_options);
}
-//
-// SSL Server Credentials.
-//
-
-struct grpc_ssl_server_credentials_options {
- grpc_ssl_client_certificate_request_type client_certificate_request;
- grpc_ssl_server_certificate_config* certificate_config;
- grpc_ssl_server_certificate_config_fetcher* certificate_config_fetcher;
-};
-
+//
+// SSL Server Credentials.
+//
+
+struct grpc_ssl_server_credentials_options {
+ grpc_ssl_client_certificate_request_type client_certificate_request;
+ grpc_ssl_server_certificate_config* certificate_config;
+ grpc_ssl_server_certificate_config_fetcher* certificate_config_fetcher;
+};
+
grpc_ssl_server_credentials::grpc_ssl_server_credentials(
const grpc_ssl_server_credentials_options& options)
: grpc_server_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_SSL) {
@@ -182,47 +182,47 @@ grpc_ssl_server_credentials::grpc_ssl_server_credentials(
options.certificate_config->num_key_cert_pairs,
options.client_certificate_request);
}
-}
-
+}
+
grpc_ssl_server_credentials::~grpc_ssl_server_credentials() {
grpc_tsi_ssl_pem_key_cert_pairs_destroy(config_.pem_key_cert_pairs,
config_.num_key_cert_pairs);
gpr_free(config_.pem_root_certs);
-}
+}
grpc_core::RefCountedPtr<grpc_server_security_connector>
grpc_ssl_server_credentials::create_security_connector() {
return grpc_ssl_server_security_connector_create(this->Ref());
}
-
-tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs(
- const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs) {
- tsi_ssl_pem_key_cert_pair* tsi_pairs = nullptr;
- if (num_key_cert_pairs > 0) {
- GPR_ASSERT(pem_key_cert_pairs != nullptr);
- tsi_pairs = static_cast<tsi_ssl_pem_key_cert_pair*>(
- gpr_zalloc(num_key_cert_pairs * sizeof(tsi_ssl_pem_key_cert_pair)));
- }
- for (size_t i = 0; i < num_key_cert_pairs; i++) {
- GPR_ASSERT(pem_key_cert_pairs[i].private_key != nullptr);
- GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != nullptr);
- tsi_pairs[i].cert_chain = gpr_strdup(pem_key_cert_pairs[i].cert_chain);
- tsi_pairs[i].private_key = gpr_strdup(pem_key_cert_pairs[i].private_key);
- }
- return tsi_pairs;
-}
-
+
+tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs(
+ const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs) {
+ tsi_ssl_pem_key_cert_pair* tsi_pairs = nullptr;
+ if (num_key_cert_pairs > 0) {
+ GPR_ASSERT(pem_key_cert_pairs != nullptr);
+ tsi_pairs = static_cast<tsi_ssl_pem_key_cert_pair*>(
+ gpr_zalloc(num_key_cert_pairs * sizeof(tsi_ssl_pem_key_cert_pair)));
+ }
+ for (size_t i = 0; i < num_key_cert_pairs; i++) {
+ GPR_ASSERT(pem_key_cert_pairs[i].private_key != nullptr);
+ GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != nullptr);
+ tsi_pairs[i].cert_chain = gpr_strdup(pem_key_cert_pairs[i].cert_chain);
+ tsi_pairs[i].private_key = gpr_strdup(pem_key_cert_pairs[i].private_key);
+ }
+ return tsi_pairs;
+}
+
void grpc_ssl_server_credentials::build_config(
- const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs,
+ const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs,
grpc_ssl_client_certificate_request_type client_certificate_request) {
config_.client_certificate_request = client_certificate_request;
config_.pem_root_certs = gpr_strdup(pem_root_certs);
config_.pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs(
- pem_key_cert_pairs, num_key_cert_pairs);
+ pem_key_cert_pairs, num_key_cert_pairs);
config_.num_key_cert_pairs = num_key_cert_pairs;
-}
-
+}
+
void grpc_ssl_server_credentials::set_min_tls_version(
grpc_tls_version min_tls_version) {
config_.min_tls_version = min_tls_version;
@@ -233,152 +233,152 @@ void grpc_ssl_server_credentials::set_max_tls_version(
config_.max_tls_version = max_tls_version;
}
-grpc_ssl_server_certificate_config* grpc_ssl_server_certificate_config_create(
- const char* pem_root_certs,
- const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs) {
- grpc_ssl_server_certificate_config* config =
- static_cast<grpc_ssl_server_certificate_config*>(
- gpr_zalloc(sizeof(grpc_ssl_server_certificate_config)));
+grpc_ssl_server_certificate_config* grpc_ssl_server_certificate_config_create(
+ const char* pem_root_certs,
+ const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs) {
+ grpc_ssl_server_certificate_config* config =
+ static_cast<grpc_ssl_server_certificate_config*>(
+ gpr_zalloc(sizeof(grpc_ssl_server_certificate_config)));
config->pem_root_certs = gpr_strdup(pem_root_certs);
- if (num_key_cert_pairs > 0) {
- GPR_ASSERT(pem_key_cert_pairs != nullptr);
- config->pem_key_cert_pairs = static_cast<grpc_ssl_pem_key_cert_pair*>(
- gpr_zalloc(num_key_cert_pairs * sizeof(grpc_ssl_pem_key_cert_pair)));
- }
- config->num_key_cert_pairs = num_key_cert_pairs;
- for (size_t i = 0; i < num_key_cert_pairs; i++) {
- GPR_ASSERT(pem_key_cert_pairs[i].private_key != nullptr);
- GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != nullptr);
- config->pem_key_cert_pairs[i].cert_chain =
- gpr_strdup(pem_key_cert_pairs[i].cert_chain);
- config->pem_key_cert_pairs[i].private_key =
- gpr_strdup(pem_key_cert_pairs[i].private_key);
- }
- return config;
-}
-
-void grpc_ssl_server_certificate_config_destroy(
- grpc_ssl_server_certificate_config* config) {
- if (config == nullptr) return;
- for (size_t i = 0; i < config->num_key_cert_pairs; i++) {
- gpr_free((void*)config->pem_key_cert_pairs[i].private_key);
- gpr_free((void*)config->pem_key_cert_pairs[i].cert_chain);
- }
- gpr_free(config->pem_key_cert_pairs);
- gpr_free(config->pem_root_certs);
- gpr_free(config);
-}
-
-grpc_ssl_server_credentials_options*
-grpc_ssl_server_credentials_create_options_using_config(
- grpc_ssl_client_certificate_request_type client_certificate_request,
- grpc_ssl_server_certificate_config* config) {
- grpc_ssl_server_credentials_options* options = nullptr;
- if (config == nullptr) {
- gpr_log(GPR_ERROR, "Certificate config must not be NULL.");
- goto done;
- }
- options = static_cast<grpc_ssl_server_credentials_options*>(
- gpr_zalloc(sizeof(grpc_ssl_server_credentials_options)));
- options->client_certificate_request = client_certificate_request;
- options->certificate_config = config;
-done:
- return options;
-}
-
-grpc_ssl_server_credentials_options*
-grpc_ssl_server_credentials_create_options_using_config_fetcher(
- grpc_ssl_client_certificate_request_type client_certificate_request,
- grpc_ssl_server_certificate_config_callback cb, void* user_data) {
- if (cb == nullptr) {
- gpr_log(GPR_ERROR, "Invalid certificate config callback parameter.");
- return nullptr;
- }
-
- grpc_ssl_server_certificate_config_fetcher* fetcher =
- static_cast<grpc_ssl_server_certificate_config_fetcher*>(
- gpr_zalloc(sizeof(grpc_ssl_server_certificate_config_fetcher)));
- fetcher->cb = cb;
- fetcher->user_data = user_data;
-
- grpc_ssl_server_credentials_options* options =
- static_cast<grpc_ssl_server_credentials_options*>(
- gpr_zalloc(sizeof(grpc_ssl_server_credentials_options)));
- options->client_certificate_request = client_certificate_request;
- options->certificate_config_fetcher = fetcher;
-
- return options;
-}
-
-grpc_server_credentials* grpc_ssl_server_credentials_create(
- const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs, int force_client_auth, void* reserved) {
- return grpc_ssl_server_credentials_create_ex(
- pem_root_certs, pem_key_cert_pairs, num_key_cert_pairs,
- force_client_auth
- ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
- : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE,
- reserved);
-}
-
-grpc_server_credentials* grpc_ssl_server_credentials_create_ex(
- const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs,
- grpc_ssl_client_certificate_request_type client_certificate_request,
- void* reserved) {
- GRPC_API_TRACE(
- "grpc_ssl_server_credentials_create_ex("
- "pem_root_certs=%s, pem_key_cert_pairs=%p, num_key_cert_pairs=%lu, "
- "client_certificate_request=%d, reserved=%p)",
- 5,
- (pem_root_certs, pem_key_cert_pairs, (unsigned long)num_key_cert_pairs,
- client_certificate_request, reserved));
- GPR_ASSERT(reserved == nullptr);
-
- grpc_ssl_server_certificate_config* cert_config =
- grpc_ssl_server_certificate_config_create(
- pem_root_certs, pem_key_cert_pairs, num_key_cert_pairs);
- grpc_ssl_server_credentials_options* options =
- grpc_ssl_server_credentials_create_options_using_config(
- client_certificate_request, cert_config);
-
- return grpc_ssl_server_credentials_create_with_options(options);
-}
-
-grpc_server_credentials* grpc_ssl_server_credentials_create_with_options(
- grpc_ssl_server_credentials_options* options) {
- grpc_server_credentials* retval = nullptr;
-
- if (options == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid options trying to create SSL server credentials.");
- goto done;
- }
-
- if (options->certificate_config == nullptr &&
- options->certificate_config_fetcher == nullptr) {
- gpr_log(GPR_ERROR,
- "SSL server credentials options must specify either "
- "certificate config or fetcher.");
- goto done;
- } else if (options->certificate_config_fetcher != nullptr &&
- options->certificate_config_fetcher->cb == nullptr) {
- gpr_log(GPR_ERROR, "Certificate config fetcher callback must not be NULL.");
- goto done;
- }
-
+ if (num_key_cert_pairs > 0) {
+ GPR_ASSERT(pem_key_cert_pairs != nullptr);
+ config->pem_key_cert_pairs = static_cast<grpc_ssl_pem_key_cert_pair*>(
+ gpr_zalloc(num_key_cert_pairs * sizeof(grpc_ssl_pem_key_cert_pair)));
+ }
+ config->num_key_cert_pairs = num_key_cert_pairs;
+ for (size_t i = 0; i < num_key_cert_pairs; i++) {
+ GPR_ASSERT(pem_key_cert_pairs[i].private_key != nullptr);
+ GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != nullptr);
+ config->pem_key_cert_pairs[i].cert_chain =
+ gpr_strdup(pem_key_cert_pairs[i].cert_chain);
+ config->pem_key_cert_pairs[i].private_key =
+ gpr_strdup(pem_key_cert_pairs[i].private_key);
+ }
+ return config;
+}
+
+void grpc_ssl_server_certificate_config_destroy(
+ grpc_ssl_server_certificate_config* config) {
+ if (config == nullptr) return;
+ for (size_t i = 0; i < config->num_key_cert_pairs; i++) {
+ gpr_free((void*)config->pem_key_cert_pairs[i].private_key);
+ gpr_free((void*)config->pem_key_cert_pairs[i].cert_chain);
+ }
+ gpr_free(config->pem_key_cert_pairs);
+ gpr_free(config->pem_root_certs);
+ gpr_free(config);
+}
+
+grpc_ssl_server_credentials_options*
+grpc_ssl_server_credentials_create_options_using_config(
+ grpc_ssl_client_certificate_request_type client_certificate_request,
+ grpc_ssl_server_certificate_config* config) {
+ grpc_ssl_server_credentials_options* options = nullptr;
+ if (config == nullptr) {
+ gpr_log(GPR_ERROR, "Certificate config must not be NULL.");
+ goto done;
+ }
+ options = static_cast<grpc_ssl_server_credentials_options*>(
+ gpr_zalloc(sizeof(grpc_ssl_server_credentials_options)));
+ options->client_certificate_request = client_certificate_request;
+ options->certificate_config = config;
+done:
+ return options;
+}
+
+grpc_ssl_server_credentials_options*
+grpc_ssl_server_credentials_create_options_using_config_fetcher(
+ grpc_ssl_client_certificate_request_type client_certificate_request,
+ grpc_ssl_server_certificate_config_callback cb, void* user_data) {
+ if (cb == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid certificate config callback parameter.");
+ return nullptr;
+ }
+
+ grpc_ssl_server_certificate_config_fetcher* fetcher =
+ static_cast<grpc_ssl_server_certificate_config_fetcher*>(
+ gpr_zalloc(sizeof(grpc_ssl_server_certificate_config_fetcher)));
+ fetcher->cb = cb;
+ fetcher->user_data = user_data;
+
+ grpc_ssl_server_credentials_options* options =
+ static_cast<grpc_ssl_server_credentials_options*>(
+ gpr_zalloc(sizeof(grpc_ssl_server_credentials_options)));
+ options->client_certificate_request = client_certificate_request;
+ options->certificate_config_fetcher = fetcher;
+
+ return options;
+}
+
+grpc_server_credentials* grpc_ssl_server_credentials_create(
+ const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs, int force_client_auth, void* reserved) {
+ return grpc_ssl_server_credentials_create_ex(
+ pem_root_certs, pem_key_cert_pairs, num_key_cert_pairs,
+ force_client_auth
+ ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
+ : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE,
+ reserved);
+}
+
+grpc_server_credentials* grpc_ssl_server_credentials_create_ex(
+ const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs,
+ grpc_ssl_client_certificate_request_type client_certificate_request,
+ void* reserved) {
+ GRPC_API_TRACE(
+ "grpc_ssl_server_credentials_create_ex("
+ "pem_root_certs=%s, pem_key_cert_pairs=%p, num_key_cert_pairs=%lu, "
+ "client_certificate_request=%d, reserved=%p)",
+ 5,
+ (pem_root_certs, pem_key_cert_pairs, (unsigned long)num_key_cert_pairs,
+ client_certificate_request, reserved));
+ GPR_ASSERT(reserved == nullptr);
+
+ grpc_ssl_server_certificate_config* cert_config =
+ grpc_ssl_server_certificate_config_create(
+ pem_root_certs, pem_key_cert_pairs, num_key_cert_pairs);
+ grpc_ssl_server_credentials_options* options =
+ grpc_ssl_server_credentials_create_options_using_config(
+ client_certificate_request, cert_config);
+
+ return grpc_ssl_server_credentials_create_with_options(options);
+}
+
+grpc_server_credentials* grpc_ssl_server_credentials_create_with_options(
+ grpc_ssl_server_credentials_options* options) {
+ grpc_server_credentials* retval = nullptr;
+
+ if (options == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid options trying to create SSL server credentials.");
+ goto done;
+ }
+
+ if (options->certificate_config == nullptr &&
+ options->certificate_config_fetcher == nullptr) {
+ gpr_log(GPR_ERROR,
+ "SSL server credentials options must specify either "
+ "certificate config or fetcher.");
+ goto done;
+ } else if (options->certificate_config_fetcher != nullptr &&
+ options->certificate_config_fetcher->cb == nullptr) {
+ gpr_log(GPR_ERROR, "Certificate config fetcher callback must not be NULL.");
+ goto done;
+ }
+
retval = new grpc_ssl_server_credentials(*options);
-
-done:
- grpc_ssl_server_credentials_options_destroy(options);
- return retval;
-}
-
-void grpc_ssl_server_credentials_options_destroy(
- grpc_ssl_server_credentials_options* o) {
- if (o == nullptr) return;
- gpr_free(o->certificate_config_fetcher);
- grpc_ssl_server_certificate_config_destroy(o->certificate_config);
- gpr_free(o);
-}
+
+done:
+ grpc_ssl_server_credentials_options_destroy(options);
+ return retval;
+}
+
+void grpc_ssl_server_credentials_options_destroy(
+ grpc_ssl_server_credentials_options* o) {
+ if (o == nullptr) return;
+ gpr_free(o->certificate_config_fetcher);
+ grpc_ssl_server_certificate_config_destroy(o->certificate_config);
+ gpr_free(o);
+}
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 4c90813f8d2..ce3f0791aa1 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
@@ -1,25 +1,25 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_CREDENTIALS_SSL_SSL_CREDENTIALS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_SSL_SSL_CREDENTIALS_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h"
@@ -51,17 +51,17 @@ class grpc_ssl_credentials : public grpc_channel_credentials {
grpc_ssl_config config_;
};
-struct grpc_ssl_server_certificate_config {
+struct grpc_ssl_server_certificate_config {
grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs = nullptr;
size_t num_key_cert_pairs = 0;
char* pem_root_certs = nullptr;
-};
-
+};
+
struct grpc_ssl_server_certificate_config_fetcher {
grpc_ssl_server_certificate_config_callback cb = nullptr;
- void* user_data;
+ void* user_data;
};
-
+
class grpc_ssl_server_credentials final : public grpc_server_credentials {
public:
grpc_ssl_server_credentials(
@@ -99,11 +99,11 @@ class grpc_ssl_server_credentials final : public grpc_server_credentials {
grpc_ssl_server_certificate_config_fetcher certificate_config_fetcher_;
};
-tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs(
- const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs);
-
-void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp,
- size_t num_key_cert_pairs);
-
+tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs(
+ const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs);
+
+void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp,
+ size_t num_key_cert_pairs);
+
#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_SSL_SSL_CREDENTIALS_H */
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.cpp b/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.cpp
index d07d3b21b8c..849e13fe6e8 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.cpp
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.cpp
@@ -1,10 +1,10 @@
-#include "load_arcadia_root_certs.h"
-
+#include "load_arcadia_root_certs.h"
+
#include <library/cpp/resource/resource.h>
-
-namespace grpc_core {
- grpc_slice LoadArcadiaRootCerts() {
- TString cacert = NResource::Find("/builtin/cacert");
- return grpc_slice_from_copied_buffer(cacert.data(), cacert.size() + 1); // With \0.
- }
-}
+
+namespace grpc_core {
+ grpc_slice LoadArcadiaRootCerts() {
+ TString cacert = NResource::Find("/builtin/cacert");
+ return grpc_slice_from_copied_buffer(cacert.data(), cacert.size() + 1); // With \0.
+ }
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.h b/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.h
index fb57648e481..dcb61ec64fd 100644
--- a/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.h
+++ b/contrib/libs/grpc/src/core/lib/security/security_connector/load_arcadia_root_certs.h
@@ -1,7 +1,7 @@
-#pragma once
-
-#include <grpc/slice.h>
-
-namespace grpc_core {
- grpc_slice LoadArcadiaRootCerts();
-}
+#pragma once
+
+#include <grpc/slice.h>
+
+namespace grpc_core {
+ grpc_slice LoadArcadiaRootCerts();
+}
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 0400ad6fb8d..42613375010 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/security_connector/security_connector.h"
-
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/ext/transport/chttp2/alpn/alpn.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/handshaker.h"
-#include "src/core/lib/gpr/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/lib/security/security_connector/security_connector.h"
+
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/ext/transport/chttp2/alpn/alpn.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/iomgr/load_file.h"
-#include "src/core/lib/security/context/security_context.h"
-#include "src/core/lib/security/credentials/credentials.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"
#include "src/core/lib/security/security_connector/load_system_roots.h"
#include "src/core/lib/security/security_connector/security_connector.h"
-#include "src/core/lib/security/transport/security_handshaker.h"
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_security_connector_refcount(
- false, "security_connector_refcount");
-
+#include "src/core/lib/security/transport/security_handshaker.h"
+
+grpc_core::DebugOnlyTraceFlag grpc_trace_security_connector_refcount(
+ false, "security_connector_refcount");
+
grpc_server_security_connector::grpc_server_security_connector(
const char* url_scheme,
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds)
: grpc_security_connector(url_scheme),
server_creds_(std::move(server_creds)) {}
-
+
grpc_server_security_connector::~grpc_server_security_connector() = default;
grpc_channel_security_connector::grpc_channel_security_connector(
@@ -57,13 +57,13 @@ grpc_channel_security_connector::grpc_channel_security_connector(
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,
const grpc_security_connector* other) {
- if (sc == nullptr || other == nullptr) return GPR_ICMP(sc, other);
+ if (sc == nullptr || other == nullptr) return GPR_ICMP(sc, other);
return sc->cmp(other);
-}
-
+}
+
int grpc_channel_security_connector::channel_security_connector_cmp(
const grpc_channel_security_connector* other) const {
const grpc_channel_security_connector* other_sc =
@@ -71,10 +71,10 @@ int grpc_channel_security_connector::channel_security_connector_cmp(
GPR_ASSERT(channel_creds() != nullptr);
GPR_ASSERT(other_sc->channel_creds() != nullptr);
int c = GPR_ICMP(channel_creds(), other_sc->channel_creds());
- if (c != 0) return c;
+ if (c != 0) return c;
return GPR_ICMP(request_metadata_creds(), other_sc->request_metadata_creds());
-}
-
+}
+
int grpc_server_security_connector::server_security_connector_cmp(
const grpc_server_security_connector* other) const {
const grpc_server_security_connector* other_sc =
@@ -82,50 +82,50 @@ int grpc_server_security_connector::server_security_connector_cmp(
GPR_ASSERT(server_creds() != nullptr);
GPR_ASSERT(other_sc->server_creds() != nullptr);
return GPR_ICMP(server_creds(), other_sc->server_creds());
-}
-
-static void connector_arg_destroy(void* p) {
+}
+
+static void connector_arg_destroy(void* p) {
static_cast<grpc_security_connector*>(p)->Unref(DEBUG_LOCATION,
"connector_arg_destroy");
-}
-
-static void* connector_arg_copy(void* p) {
+}
+
+static void* connector_arg_copy(void* p) {
return static_cast<grpc_security_connector*>(p)
->Ref(DEBUG_LOCATION, "connector_arg_copy")
.release();
-}
-
-static int connector_cmp(void* a, void* b) {
+}
+
+static int connector_cmp(void* a, void* b) {
return static_cast<grpc_security_connector*>(a)->cmp(
static_cast<grpc_security_connector*>(b));
-}
-
-static const grpc_arg_pointer_vtable connector_arg_vtable = {
- connector_arg_copy, connector_arg_destroy, connector_cmp};
-
-grpc_arg grpc_security_connector_to_arg(grpc_security_connector* sc) {
- return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SECURITY_CONNECTOR, sc,
- &connector_arg_vtable);
-}
-
-grpc_security_connector* grpc_security_connector_from_arg(const grpc_arg* arg) {
- if (strcmp(arg->key, GRPC_ARG_SECURITY_CONNECTOR)) return nullptr;
- if (arg->type != GRPC_ARG_POINTER) {
- gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
- GRPC_ARG_SECURITY_CONNECTOR);
- return nullptr;
- }
- return static_cast<grpc_security_connector*>(arg->value.pointer.p);
-}
-
-grpc_security_connector* grpc_security_connector_find_in_args(
- const grpc_channel_args* args) {
- size_t i;
- if (args == nullptr) return nullptr;
- for (i = 0; i < args->num_args; i++) {
- grpc_security_connector* sc =
- grpc_security_connector_from_arg(&args->args[i]);
- if (sc != nullptr) return sc;
- }
- return nullptr;
-}
+}
+
+static const grpc_arg_pointer_vtable connector_arg_vtable = {
+ connector_arg_copy, connector_arg_destroy, connector_cmp};
+
+grpc_arg grpc_security_connector_to_arg(grpc_security_connector* sc) {
+ return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SECURITY_CONNECTOR, sc,
+ &connector_arg_vtable);
+}
+
+grpc_security_connector* grpc_security_connector_from_arg(const grpc_arg* arg) {
+ if (strcmp(arg->key, GRPC_ARG_SECURITY_CONNECTOR)) return nullptr;
+ if (arg->type != GRPC_ARG_POINTER) {
+ gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
+ GRPC_ARG_SECURITY_CONNECTOR);
+ return nullptr;
+ }
+ return static_cast<grpc_security_connector*>(arg->value.pointer.p);
+}
+
+grpc_security_connector* grpc_security_connector_find_in_args(
+ const grpc_channel_args* args) {
+ size_t i;
+ if (args == nullptr) return nullptr;
+ for (i = 0; i < args->num_args; i++) {
+ grpc_security_connector* sc =
+ grpc_security_connector_from_arg(&args->args[i]);
+ if (sc != nullptr) return sc;
+ }
+ return nullptr;
+}
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 74d04600b24..d8ee78cd2ec 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
@@ -1,49 +1,49 @@
-/*
- *
- * 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_SECURITY_SECURITY_CONNECTOR_SECURITY_CONNECTOR_H
-#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SECURITY_CONNECTOR_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include <grpc/grpc_security.h>
-
-#include "src/core/lib/channel/handshaker.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_SECURITY_SECURITY_CONNECTOR_SECURITY_CONNECTOR_H
+#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SECURITY_CONNECTOR_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include <grpc/grpc_security.h>
+
+#include "src/core/lib/channel/handshaker.h"
#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/lib/iomgr/endpoint.h"
+#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/pollset.h"
-#include "src/core/lib/iomgr/tcp_server.h"
-#include "src/core/tsi/ssl_transport_security.h"
-#include "src/core/tsi/transport_security_interface.h"
-
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_security_connector_refcount;
-
-typedef enum { GRPC_SECURITY_OK = 0, GRPC_SECURITY_ERROR } grpc_security_status;
-
-/* --- security_connector object. ---
-
- A security connector object represents away to configure the underlying
- transport security mechanism and check the resulting trusted peer. */
-
-#define GRPC_ARG_SECURITY_CONNECTOR "grpc.security_connector"
-
+#include "src/core/lib/iomgr/tcp_server.h"
+#include "src/core/tsi/ssl_transport_security.h"
+#include "src/core/tsi/transport_security_interface.h"
+
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_security_connector_refcount;
+
+typedef enum { GRPC_SECURITY_OK = 0, GRPC_SECURITY_ERROR } grpc_security_status;
+
+/* --- security_connector object. ---
+
+ A security connector object represents away to configure the underlying
+ transport security mechanism and check the resulting trusted peer. */
+
+#define GRPC_ARG_SECURITY_CONNECTOR "grpc.security_connector"
+
class grpc_security_connector
: public grpc_core::RefCounted<grpc_security_connector> {
public:
@@ -52,38 +52,38 @@ class grpc_security_connector
&grpc_trace_security_connector_refcount),
url_scheme_(url_scheme) {}
virtual ~grpc_security_connector() = default;
-
+
/* Check the peer. Callee takes ownership of the peer object.
When done, sets *auth_context and invokes on_peer_checked. */
virtual void check_peer(
tsi_peer peer, grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) = 0;
-
+
/* Compares two security connectors. */
virtual int cmp(const grpc_security_connector* other) const = 0;
-
+
const char* url_scheme() const { return url_scheme_; }
-
+
private:
const char* url_scheme_;
};
-/* Util to encapsulate the connector in a channel arg. */
-grpc_arg grpc_security_connector_to_arg(grpc_security_connector* sc);
-
-/* Util to get the connector from a channel arg. */
-grpc_security_connector* grpc_security_connector_from_arg(const grpc_arg* arg);
-
-/* Util to find the connector from channel args. */
-grpc_security_connector* grpc_security_connector_find_in_args(
- const grpc_channel_args* args);
-
-/* --- channel_security_connector object. ---
-
- A channel security connector object represents a way to configure the
- underlying transport security mechanism on the client side. */
-
+/* Util to encapsulate the connector in a channel arg. */
+grpc_arg grpc_security_connector_to_arg(grpc_security_connector* sc);
+
+/* Util to get the connector from a channel arg. */
+grpc_security_connector* grpc_security_connector_from_arg(const grpc_arg* arg);
+
+/* Util to find the connector from channel args. */
+grpc_security_connector* grpc_security_connector_find_in_args(
+ const grpc_channel_args* args);
+
+/* --- channel_security_connector object. ---
+
+ A channel security connector object represents a way to configure the
+ underlying transport security mechanism on the client side. */
+
class grpc_channel_security_connector : public grpc_security_connector {
public:
grpc_channel_security_connector(
@@ -93,7 +93,7 @@ class grpc_channel_security_connector : public grpc_security_connector {
/*,
grpc_channel_args* channel_args = nullptr*/);
~grpc_channel_security_connector() override;
-
+
/// Checks that the host that will be set for a call is acceptable.
/// Returns true if completed synchronously, in which case \a error will
/// be set to indicate the result. Otherwise, \a on_call_host_checked
@@ -111,7 +111,7 @@ class grpc_channel_security_connector : public grpc_security_connector {
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();
}
@@ -124,12 +124,12 @@ class grpc_channel_security_connector : public grpc_security_connector {
grpc_call_credentials* mutable_request_metadata_creds() {
return request_metadata_creds_.get();
}
-
+
protected:
// Helper methods to be used in subclasses.
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.
@@ -140,37 +140,37 @@ class grpc_channel_security_connector : public grpc_security_connector {
grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds_;
std::unique_ptr<grpc_channel_args> channel_args_;
};
-
-/* --- server_security_connector object. ---
-
- A server security connector object represents a way to configure the
- underlying transport security mechanism on the server side. */
-
+
+/* --- server_security_connector object. ---
+
+ A server security connector object represents a way to configure the
+ underlying transport security mechanism on the server side. */
+
class grpc_server_security_connector : public grpc_security_connector {
public:
grpc_server_security_connector(
const char* url_scheme,
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;
-
+
const grpc_server_credentials* server_creds() const {
return server_creds_.get();
}
grpc_server_credentials* mutable_server_creds() {
return server_creds_.get();
}
-
- protected:
+
+ protected:
// Helper methods to be used in subclasses.
int server_security_connector_cmp(
const grpc_server_security_connector* other) const;
-
- private:
+
+ private:
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds_;
-};
-
-#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SECURITY_CONNECTOR_H */
+};
+
+#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SECURITY_CONNECTOR_H */
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 6c83968f8e7..08b2177181e 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
@@ -39,8 +39,8 @@
#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"
-
+#include "load_arcadia_root_certs.h"
+
/* -- Constants. -- */
#ifndef INSTALL_PREFIX
@@ -556,10 +556,10 @@ grpc_slice DefaultSslRootStore::ComputePemRootCerts() {
}
gpr_free(pem_root_certs);
}
- // Load Arcadia certs.
- if (GRPC_SLICE_IS_EMPTY(result)) {
- result = LoadArcadiaRootCerts();
- }
+ // Load Arcadia certs.
+ if (GRPC_SLICE_IS_EMPTY(result)) {
+ result = LoadArcadiaRootCerts();
+ }
// Try loading roots from OS trust store if flag is enabled.
if (GRPC_SLICE_IS_EMPTY(result) && !not_use_system_roots) {
result = LoadSystemRootCerts();
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 ae31b1d578b..269827d7451 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
@@ -1,35 +1,35 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_AUTH_FILTERS_H
#define GRPC_CORE_LIB_SECURITY_TRANSPORT_AUTH_FILTERS_H
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc_security.h>
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc_security.h>
#include "src/core/lib/channel/channel_stack.h"
extern const grpc_channel_filter grpc_client_auth_filter;
extern const grpc_channel_filter grpc_server_auth_filter;
-void grpc_auth_metadata_context_build(
+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,
- grpc_auth_metadata_context* auth_md_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 b1a9d3f9386..d57e5a32ef2 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
@@ -1,50 +1,50 @@
-/*
- *
- * 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/security/transport/auth_filters.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/lib/security/transport/auth_filters.h"
+
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/security/context/security_context.h"
-#include "src/core/lib/security/credentials/credentials.h"
-#include "src/core/lib/security/security_connector/security_connector.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/channel/channel_stack.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/security/context/security_context.h"
+#include "src/core/lib/security/credentials/credentials.h"
+#include "src/core/lib/security/security_connector/security_connector.h"
#include "src/core/lib/security/security_connector/ssl_utils.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-#define MAX_CREDENTIALS_METADATA_COUNT 4
-
-namespace {
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/surface/call.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+#define MAX_CREDENTIALS_METADATA_COUNT 4
+
+namespace {
/* We can have a per-channel credentials. */
struct channel_data {
@@ -62,8 +62,8 @@ struct channel_data {
grpc_core::RefCountedPtr<grpc_auth_context> auth_context;
};
-/* We can have a per-call credentials. */
-struct call_data {
+/* 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);
@@ -95,25 +95,25 @@ struct call_data {
grpc_auth_metadata_context_reset(&auth_md_context);
}
- grpc_call_stack* owning_call;
+ grpc_call_stack* owning_call;
grpc_core::CallCombiner* call_combiner;
grpc_core::RefCountedPtr<grpc_call_credentials> creds;
grpc_slice host = grpc_empty_slice();
grpc_slice method = grpc_empty_slice();
- /* pollset{_set} bound to this call; if we need to make external
- network requests, they should be done under a pollset added to this
- pollset_set so that work can progress when this call wants work to progress
- */
+ /* pollset{_set} bound to this call; if we need to make external
+ network requests, they should be done under a pollset added to this
+ pollset_set so that work can progress when this call wants work to progress
+ */
grpc_polling_entity* pollent = nullptr;
- grpc_credentials_mdelem_array md_array;
+ grpc_credentials_mdelem_array md_array;
grpc_linked_mdelem md_links[MAX_CREDENTIALS_METADATA_COUNT] = {};
grpc_auth_metadata_context auth_md_context =
grpc_auth_metadata_context(); // Zero-initialize the C struct.
- grpc_closure async_result_closure;
- grpc_closure check_call_host_cancel_closure;
- grpc_closure get_request_metadata_cancel_closure;
-};
-
+ grpc_closure async_result_closure;
+ grpc_closure check_call_host_cancel_closure;
+ grpc_closure get_request_metadata_cancel_closure;
+};
+
} // namespace
void grpc_auth_metadata_context_copy(grpc_auth_metadata_context* from,
@@ -129,147 +129,147 @@ void grpc_auth_metadata_context_copy(grpc_auth_metadata_context* from,
to->method_name = gpr_strdup(from->method_name);
}
-void grpc_auth_metadata_context_reset(
- grpc_auth_metadata_context* auth_md_context) {
- if (auth_md_context->service_url != nullptr) {
- gpr_free(const_cast<char*>(auth_md_context->service_url));
- auth_md_context->service_url = nullptr;
- }
- if (auth_md_context->method_name != nullptr) {
- gpr_free(const_cast<char*>(auth_md_context->method_name));
- auth_md_context->method_name = nullptr;
- }
+void grpc_auth_metadata_context_reset(
+ grpc_auth_metadata_context* auth_md_context) {
+ if (auth_md_context->service_url != nullptr) {
+ gpr_free(const_cast<char*>(auth_md_context->service_url));
+ auth_md_context->service_url = nullptr;
+ }
+ if (auth_md_context->method_name != nullptr) {
+ gpr_free(const_cast<char*>(auth_md_context->method_name));
+ auth_md_context->method_name = nullptr;
+ }
if (auth_md_context->channel_auth_context != nullptr) {
const_cast<grpc_auth_context*>(auth_md_context->channel_auth_context)
->Unref(DEBUG_LOCATION, "grpc_auth_metadata_context");
auth_md_context->channel_auth_context = nullptr;
}
-}
-
-static void add_error(grpc_error** combined, grpc_error* error) {
- if (error == GRPC_ERROR_NONE) return;
- if (*combined == GRPC_ERROR_NONE) {
- *combined = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Client auth metadata plugin error");
- }
- *combined = grpc_error_add_child(*combined, error);
-}
-
-static void on_credentials_metadata(void* arg, grpc_error* input_error) {
- grpc_transport_stream_op_batch* batch =
- static_cast<grpc_transport_stream_op_batch*>(arg);
- grpc_call_element* elem =
- static_cast<grpc_call_element*>(batch->handler_private.extra_arg);
- call_data* calld = static_cast<call_data*>(elem->call_data);
- grpc_auth_metadata_context_reset(&calld->auth_md_context);
- grpc_error* error = GRPC_ERROR_REF(input_error);
- if (error == GRPC_ERROR_NONE) {
- GPR_ASSERT(calld->md_array.size <= MAX_CREDENTIALS_METADATA_COUNT);
- GPR_ASSERT(batch->send_initial_metadata);
- grpc_metadata_batch* mdb =
- batch->payload->send_initial_metadata.send_initial_metadata;
- for (size_t i = 0; i < calld->md_array.size; ++i) {
- add_error(&error, grpc_metadata_batch_add_tail(
- mdb, &calld->md_links[i],
- GRPC_MDELEM_REF(calld->md_array.md[i])));
- }
- }
- if (error == GRPC_ERROR_NONE) {
- grpc_call_next_op(elem, batch);
- } else {
- error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
- GRPC_STATUS_UNAVAILABLE);
- grpc_transport_stream_op_batch_finish_with_failure(batch, error,
- calld->call_combiner);
- }
- GRPC_CALL_STACK_UNREF(calld->owning_call, "get_request_metadata");
-}
-
-void grpc_auth_metadata_context_build(
+}
+
+static void add_error(grpc_error** combined, grpc_error* error) {
+ if (error == GRPC_ERROR_NONE) return;
+ if (*combined == GRPC_ERROR_NONE) {
+ *combined = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Client auth metadata plugin error");
+ }
+ *combined = grpc_error_add_child(*combined, error);
+}
+
+static void on_credentials_metadata(void* arg, grpc_error* input_error) {
+ grpc_transport_stream_op_batch* batch =
+ static_cast<grpc_transport_stream_op_batch*>(arg);
+ grpc_call_element* elem =
+ static_cast<grpc_call_element*>(batch->handler_private.extra_arg);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_auth_metadata_context_reset(&calld->auth_md_context);
+ grpc_error* error = GRPC_ERROR_REF(input_error);
+ if (error == GRPC_ERROR_NONE) {
+ GPR_ASSERT(calld->md_array.size <= MAX_CREDENTIALS_METADATA_COUNT);
+ GPR_ASSERT(batch->send_initial_metadata);
+ grpc_metadata_batch* mdb =
+ batch->payload->send_initial_metadata.send_initial_metadata;
+ for (size_t i = 0; i < calld->md_array.size; ++i) {
+ add_error(&error, grpc_metadata_batch_add_tail(
+ mdb, &calld->md_links[i],
+ GRPC_MDELEM_REF(calld->md_array.md[i])));
+ }
+ }
+ if (error == GRPC_ERROR_NONE) {
+ grpc_call_next_op(elem, batch);
+ } else {
+ error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS,
+ GRPC_STATUS_UNAVAILABLE);
+ grpc_transport_stream_op_batch_finish_with_failure(batch, error,
+ calld->call_combiner);
+ }
+ GRPC_CALL_STACK_UNREF(calld->owning_call, "get_request_metadata");
+}
+
+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,
- grpc_auth_metadata_context* auth_md_context) {
- char* service = grpc_slice_to_c_string(call_method);
- char* last_slash = strrchr(service, '/');
- char* method_name = nullptr;
- char* service_url = nullptr;
- grpc_auth_metadata_context_reset(auth_md_context);
- if (last_slash == nullptr) {
- gpr_log(GPR_ERROR, "No '/' found in fully qualified method name");
- service[0] = '\0';
- method_name = gpr_strdup("");
- } else if (last_slash == service) {
- method_name = gpr_strdup("");
- } else {
- *last_slash = '\0';
- method_name = gpr_strdup(last_slash + 1);
- }
- char* host_and_port = grpc_slice_to_c_string(call_host);
- if (url_scheme != nullptr && strcmp(url_scheme, GRPC_SSL_URL_SCHEME) == 0) {
- /* Remove the port if it is 443. */
- char* port_delimiter = strrchr(host_and_port, ':');
- if (port_delimiter != nullptr && strcmp(port_delimiter + 1, "443") == 0) {
- *port_delimiter = '\0';
- }
- }
- gpr_asprintf(&service_url, "%s://%s%s",
- url_scheme == nullptr ? "" : url_scheme, host_and_port, service);
- auth_md_context->service_url = service_url;
- auth_md_context->method_name = method_name;
- auth_md_context->channel_auth_context =
+ grpc_auth_metadata_context* auth_md_context) {
+ char* service = grpc_slice_to_c_string(call_method);
+ char* last_slash = strrchr(service, '/');
+ char* method_name = nullptr;
+ char* service_url = nullptr;
+ grpc_auth_metadata_context_reset(auth_md_context);
+ if (last_slash == nullptr) {
+ gpr_log(GPR_ERROR, "No '/' found in fully qualified method name");
+ service[0] = '\0';
+ method_name = gpr_strdup("");
+ } else if (last_slash == service) {
+ method_name = gpr_strdup("");
+ } else {
+ *last_slash = '\0';
+ method_name = gpr_strdup(last_slash + 1);
+ }
+ char* host_and_port = grpc_slice_to_c_string(call_host);
+ if (url_scheme != nullptr && strcmp(url_scheme, GRPC_SSL_URL_SCHEME) == 0) {
+ /* Remove the port if it is 443. */
+ char* port_delimiter = strrchr(host_and_port, ':');
+ if (port_delimiter != nullptr && strcmp(port_delimiter + 1, "443") == 0) {
+ *port_delimiter = '\0';
+ }
+ }
+ gpr_asprintf(&service_url, "%s://%s%s",
+ url_scheme == nullptr ? "" : url_scheme, host_and_port, service);
+ auth_md_context->service_url = service_url;
+ auth_md_context->method_name = method_name;
+ auth_md_context->channel_auth_context =
auth_context == nullptr
? nullptr
: auth_context->Ref(DEBUG_LOCATION, "grpc_auth_metadata_context")
.release();
- gpr_free(service);
- gpr_free(host_and_port);
-}
-
-static void cancel_get_request_metadata(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);
- if (error != GRPC_ERROR_NONE) {
+ gpr_free(service);
+ gpr_free(host_and_port);
+}
+
+static void cancel_get_request_metadata(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);
+ if (error != GRPC_ERROR_NONE) {
calld->creds->cancel_get_request_metadata(&calld->md_array,
GRPC_ERROR_REF(error));
- }
-}
-
-static void send_security_metadata(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);
- grpc_client_security_context* ctx =
- static_cast<grpc_client_security_context*>(
- batch->payload->context[GRPC_CONTEXT_SECURITY].value);
- grpc_call_credentials* channel_call_creds =
+ }
+}
+
+static void send_security_metadata(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);
+ grpc_client_security_context* ctx =
+ static_cast<grpc_client_security_context*>(
+ batch->payload->context[GRPC_CONTEXT_SECURITY].value);
+ grpc_call_credentials* channel_call_creds =
chand->security_connector->mutable_request_metadata_creds();
- int call_creds_has_md = (ctx != nullptr) && (ctx->creds != nullptr);
-
- if (channel_call_creds == nullptr && !call_creds_has_md) {
- /* Skip sending metadata altogether. */
- grpc_call_next_op(elem, batch);
- return;
- }
-
- if (channel_call_creds != nullptr && call_creds_has_md) {
+ int call_creds_has_md = (ctx != nullptr) && (ctx->creds != nullptr);
+
+ if (channel_call_creds == nullptr && !call_creds_has_md) {
+ /* Skip sending metadata altogether. */
+ grpc_call_next_op(elem, batch);
+ return;
+ }
+
+ if (channel_call_creds != nullptr && call_creds_has_md) {
calld->creds = grpc_core::RefCountedPtr<grpc_call_credentials>(
grpc_composite_call_credentials_create(channel_call_creds,
ctx->creds.get(), nullptr));
- if (calld->creds == nullptr) {
- grpc_transport_stream_op_batch_finish_with_failure(
- batch,
- grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Incompatible credentials set on channel and call."),
- GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAUTHENTICATED),
- calld->call_combiner);
- return;
- }
- } else {
+ if (calld->creds == nullptr) {
+ grpc_transport_stream_op_batch_finish_with_failure(
+ batch,
+ grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Incompatible credentials set on channel and call."),
+ GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAUTHENTICATED),
+ calld->call_combiner);
+ return;
+ }
+ } else {
calld->creds =
call_creds_has_md ? ctx->creds->Ref() : channel_call_creds->Ref();
- }
-
+ }
+
/* Check security level of call credential and channel, and do not send
* metadata if the check fails. */
grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name(
@@ -303,165 +303,165 @@ static void send_security_metadata(grpc_call_element* elem,
return;
}
- grpc_auth_metadata_context_build(
+ grpc_auth_metadata_context_build(
chand->security_connector->url_scheme(), calld->host, calld->method,
chand->auth_context.get(), &calld->auth_md_context);
-
- GPR_ASSERT(calld->pollent != nullptr);
- GRPC_CALL_STACK_REF(calld->owning_call, "get_request_metadata");
- GRPC_CLOSURE_INIT(&calld->async_result_closure, on_credentials_metadata,
- batch, grpc_schedule_on_exec_ctx);
- grpc_error* error = GRPC_ERROR_NONE;
+
+ GPR_ASSERT(calld->pollent != nullptr);
+ GRPC_CALL_STACK_REF(calld->owning_call, "get_request_metadata");
+ GRPC_CLOSURE_INIT(&calld->async_result_closure, on_credentials_metadata,
+ batch, grpc_schedule_on_exec_ctx);
+ grpc_error* error = GRPC_ERROR_NONE;
if (calld->creds->get_request_metadata(
calld->pollent, calld->auth_md_context, &calld->md_array,
&calld->async_result_closure, &error)) {
- // Synchronous return; invoke on_credentials_metadata() directly.
- on_credentials_metadata(batch, error);
- GRPC_ERROR_UNREF(error);
- } else {
- // Async return; register cancellation closure with call combiner.
+ // Synchronous return; invoke on_credentials_metadata() directly.
+ on_credentials_metadata(batch, error);
+ 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));
- }
-}
-
-static void on_host_checked(void* arg, grpc_error* error) {
- grpc_transport_stream_op_batch* batch =
- static_cast<grpc_transport_stream_op_batch*>(arg);
- grpc_call_element* elem =
- static_cast<grpc_call_element*>(batch->handler_private.extra_arg);
- call_data* calld = static_cast<call_data*>(elem->call_data);
- if (error == GRPC_ERROR_NONE) {
- send_security_metadata(elem, batch);
- } else {
+ }
+}
+
+static void on_host_checked(void* arg, grpc_error* error) {
+ grpc_transport_stream_op_batch* batch =
+ static_cast<grpc_transport_stream_op_batch*>(arg);
+ grpc_call_element* elem =
+ static_cast<grpc_call_element*>(batch->handler_private.extra_arg);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ if (error == GRPC_ERROR_NONE) {
+ send_security_metadata(elem, batch);
+ } else {
TString error_msg = y_absl::StrCat(
"Invalid host ", grpc_core::StringViewFromSlice(calld->host),
" set in :authority metadata.");
- grpc_transport_stream_op_batch_finish_with_failure(
- batch,
+ grpc_transport_stream_op_batch_finish_with_failure(
+ batch,
grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str()),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAUTHENTICATED),
- calld->call_combiner);
- }
- GRPC_CALL_STACK_UNREF(calld->owning_call, "check_call_host");
-}
-
-static void cancel_check_call_host(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);
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- if (error != GRPC_ERROR_NONE) {
+ calld->call_combiner);
+ }
+ GRPC_CALL_STACK_UNREF(calld->owning_call, "check_call_host");
+}
+
+static void cancel_check_call_host(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);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ if (error != GRPC_ERROR_NONE) {
chand->security_connector->cancel_check_call_host(
&calld->async_result_closure, GRPC_ERROR_REF(error));
- }
-}
-
+ }
+}
+
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);
-
- /* grab pointers to our data from the call element */
- call_data* calld = static_cast<call_data*>(elem->call_data);
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
-
- if (batch->send_initial_metadata) {
- grpc_metadata_batch* metadata =
- batch->payload->send_initial_metadata.send_initial_metadata;
- if (metadata->idx.named.path != nullptr) {
- calld->method =
- grpc_slice_ref_internal(GRPC_MDVALUE(metadata->idx.named.path->md));
- }
- if (metadata->idx.named.authority != nullptr) {
- calld->host = grpc_slice_ref_internal(
- GRPC_MDVALUE(metadata->idx.named.authority->md));
- batch->handler_private.extra_arg = elem;
- GRPC_CALL_STACK_REF(calld->owning_call, "check_call_host");
- GRPC_CLOSURE_INIT(&calld->async_result_closure, on_host_checked, batch,
- grpc_schedule_on_exec_ctx);
+ grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
+ GPR_TIMER_SCOPE("auth_start_transport_stream_op_batch", 0);
+
+ /* grab pointers to our data from the call element */
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+
+ if (batch->send_initial_metadata) {
+ grpc_metadata_batch* metadata =
+ batch->payload->send_initial_metadata.send_initial_metadata;
+ if (metadata->idx.named.path != nullptr) {
+ calld->method =
+ grpc_slice_ref_internal(GRPC_MDVALUE(metadata->idx.named.path->md));
+ }
+ if (metadata->idx.named.authority != nullptr) {
+ calld->host = grpc_slice_ref_internal(
+ GRPC_MDVALUE(metadata->idx.named.authority->md));
+ batch->handler_private.extra_arg = elem;
+ GRPC_CALL_STACK_REF(calld->owning_call, "check_call_host");
+ GRPC_CLOSURE_INIT(&calld->async_result_closure, on_host_checked, batch,
+ grpc_schedule_on_exec_ctx);
y_absl::string_view call_host(grpc_core::StringViewFromSlice(calld->host));
- grpc_error* error = GRPC_ERROR_NONE;
+ grpc_error* error = GRPC_ERROR_NONE;
if (chand->security_connector->check_call_host(
call_host, chand->auth_context.get(),
- &calld->async_result_closure, &error)) {
- // Synchronous return; invoke on_host_checked() directly.
- on_host_checked(batch, error);
- GRPC_ERROR_UNREF(error);
- } else {
- // Async return; register cancellation closure with call combiner.
+ &calld->async_result_closure, &error)) {
+ // Synchronous return; invoke on_host_checked() directly.
+ on_host_checked(batch, error);
+ 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));
- }
- return; /* early exit */
- }
- }
-
- /* pass control down the stack */
- grpc_call_next_op(elem, batch);
-}
-
-/* Constructor for call_data */
+ }
+ return; /* early exit */
+ }
+ }
+
+ /* pass control down the stack */
+ grpc_call_next_op(elem, batch);
+}
+
+/* Constructor for call_data */
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;
-}
-
+ return GRPC_ERROR_NONE;
+}
+
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 */
+ 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*/) {
- call_data* calld = static_cast<call_data*>(elem->call_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
calld->destroy();
-}
-
-/* Constructor for channel_data */
+}
+
+/* Constructor for channel_data */
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 */
GPR_ASSERT(!args->is_last);
- grpc_security_connector* sc =
- grpc_security_connector_find_in_args(args->channel_args);
- if (sc == nullptr) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Security connector missing from client auth filter args");
- }
- grpc_auth_context* auth_context =
- grpc_find_auth_context_in_args(args->channel_args);
- if (auth_context == nullptr) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Auth context missing from client auth filter args");
- }
+ grpc_security_connector* sc =
+ grpc_security_connector_find_in_args(args->channel_args);
+ if (sc == nullptr) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Security connector missing from client auth filter args");
+ }
+ grpc_auth_context* auth_context =
+ grpc_find_auth_context_in_args(args->channel_args);
+ if (auth_context == nullptr) {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Auth context missing from client auth filter args");
+ }
new (elem->channel_data) channel_data(
static_cast<grpc_channel_security_connector*>(sc), auth_context);
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel data */
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for channel data */
static void client_auth_destroy_channel_elem(grpc_channel_element* elem) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
chand->~channel_data();
-}
-
-const grpc_channel_filter grpc_client_auth_filter = {
+}
+
+const grpc_channel_filter grpc_client_auth_filter = {
client_auth_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(call_data),
+ grpc_channel_next_op,
+ sizeof(call_data),
client_auth_init_call_elem,
client_auth_set_pollset_or_pollset_set,
client_auth_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
client_auth_init_channel_elem,
client_auth_destroy_channel_elem,
- grpc_channel_next_get_info,
- "client-auth"};
+ 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 e79184fac13..24252e4e1b5 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
@@ -1,48 +1,48 @@
-/*
- *
- * 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.
- *
- */
-
-/* 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 <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.
+ *
+ */
+
+/* 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 <grpc/support/port_platform.h>
+
#include <new>
-#include "src/core/lib/iomgr/sockaddr.h"
-
-#include <grpc/slice.h>
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/iomgr/sockaddr.h"
+
+#include <grpc/slice.h>
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/security/transport/secure_endpoint.h"
-#include "src/core/lib/security/transport/tsi_error.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/tsi/transport_security_grpc.h"
-
-#define STAGING_BUFFER_SIZE 8192
-
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/security/transport/secure_endpoint.h"
+#include "src/core/lib/security/transport/tsi_error.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/tsi/transport_security_grpc.h"
+
+#define STAGING_BUFFER_SIZE 8192
+
static void on_read(void* user_data, grpc_error* error);
namespace {
@@ -80,373 +80,373 @@ struct secure_endpoint {
gpr_mu_destroy(&protector_mu);
}
- grpc_endpoint base;
- grpc_endpoint* wrapped_ep;
- struct tsi_frame_protector* protector;
- struct tsi_zero_copy_grpc_protector* zero_copy_protector;
- gpr_mu protector_mu;
- /* saved upper level callbacks and user_data. */
+ grpc_endpoint base;
+ grpc_endpoint* wrapped_ep;
+ struct tsi_frame_protector* protector;
+ struct tsi_zero_copy_grpc_protector* zero_copy_protector;
+ gpr_mu protector_mu;
+ /* saved upper level callbacks and user_data. */
grpc_closure* read_cb = nullptr;
grpc_closure* write_cb = nullptr;
- grpc_closure on_read;
+ grpc_closure on_read;
grpc_slice_buffer* read_buffer = nullptr;
- grpc_slice_buffer source_buffer;
- /* saved handshaker leftover data to unprotect. */
- grpc_slice_buffer leftover_bytes;
- /* buffers for read and write */
+ grpc_slice_buffer source_buffer;
+ /* saved handshaker leftover data to unprotect. */
+ grpc_slice_buffer leftover_bytes;
+ /* buffers for read and write */
grpc_slice read_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE);
grpc_slice write_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE);
- grpc_slice_buffer output_buffer;
-
- gpr_refcount ref;
+ grpc_slice_buffer output_buffer;
+
+ gpr_refcount ref;
};
} // namespace
-
-grpc_core::TraceFlag grpc_trace_secure_endpoint(false, "secure_endpoint");
-
+
+grpc_core::TraceFlag grpc_trace_secure_endpoint(false, "secure_endpoint");
+
static void destroy(secure_endpoint* ep) { delete ep; }
-
-#ifndef NDEBUG
-#define SECURE_ENDPOINT_UNREF(ep, reason) \
- secure_endpoint_unref((ep), (reason), __FILE__, __LINE__)
-#define SECURE_ENDPOINT_REF(ep, reason) \
- secure_endpoint_ref((ep), (reason), __FILE__, __LINE__)
-static void secure_endpoint_unref(secure_endpoint* ep, const char* reason,
- const char* file, int line) {
+
+#ifndef NDEBUG
+#define SECURE_ENDPOINT_UNREF(ep, reason) \
+ secure_endpoint_unref((ep), (reason), __FILE__, __LINE__)
+#define SECURE_ENDPOINT_REF(ep, reason) \
+ 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)) {
- 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,
- val - 1);
- }
- if (gpr_unref(&ep->ref)) {
- destroy(ep);
- }
-}
-
-static void secure_endpoint_ref(secure_endpoint* ep, const char* reason,
- const char* file, int line) {
+ 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,
+ val - 1);
+ }
+ if (gpr_unref(&ep->ref)) {
+ destroy(ep);
+ }
+}
+
+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)) {
- 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,
- val + 1);
- }
- gpr_ref(&ep->ref);
-}
-#else
-#define SECURE_ENDPOINT_UNREF(ep, reason) secure_endpoint_unref((ep))
-#define SECURE_ENDPOINT_REF(ep, reason) secure_endpoint_ref((ep))
-static void secure_endpoint_unref(secure_endpoint* ep) {
- if (gpr_unref(&ep->ref)) {
- destroy(ep);
- }
-}
-
-static void secure_endpoint_ref(secure_endpoint* ep) { gpr_ref(&ep->ref); }
-#endif
-
-static void flush_read_staging_buffer(secure_endpoint* ep, uint8_t** cur,
- uint8_t** end) {
- grpc_slice_buffer_add(ep->read_buffer, ep->read_staging_buffer);
- ep->read_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE);
- *cur = GRPC_SLICE_START_PTR(ep->read_staging_buffer);
- *end = GRPC_SLICE_END_PTR(ep->read_staging_buffer);
-}
-
-static void call_read_cb(secure_endpoint* ep, grpc_error* error) {
+ 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,
+ val + 1);
+ }
+ gpr_ref(&ep->ref);
+}
+#else
+#define SECURE_ENDPOINT_UNREF(ep, reason) secure_endpoint_unref((ep))
+#define SECURE_ENDPOINT_REF(ep, reason) secure_endpoint_ref((ep))
+static void secure_endpoint_unref(secure_endpoint* ep) {
+ if (gpr_unref(&ep->ref)) {
+ destroy(ep);
+ }
+}
+
+static void secure_endpoint_ref(secure_endpoint* ep) { gpr_ref(&ep->ref); }
+#endif
+
+static void flush_read_staging_buffer(secure_endpoint* ep, uint8_t** cur,
+ uint8_t** end) {
+ grpc_slice_buffer_add(ep->read_buffer, ep->read_staging_buffer);
+ ep->read_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE);
+ *cur = GRPC_SLICE_START_PTR(ep->read_staging_buffer);
+ *end = GRPC_SLICE_END_PTR(ep->read_staging_buffer);
+}
+
+static void call_read_cb(secure_endpoint* ep, grpc_error* error) {
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],
- GPR_DUMP_HEX | GPR_DUMP_ASCII);
- gpr_log(GPR_INFO, "READ %p: %s", ep, data);
- gpr_free(data);
- }
- }
- ep->read_buffer = nullptr;
+ size_t i;
+ for (i = 0; i < ep->read_buffer->count; i++) {
+ char* data = grpc_dump_slice(ep->read_buffer->slices[i],
+ GPR_DUMP_HEX | GPR_DUMP_ASCII);
+ gpr_log(GPR_INFO, "READ %p: %s", ep, data);
+ gpr_free(data);
+ }
+ }
+ ep->read_buffer = nullptr;
grpc_core::ExecCtx::Run(DEBUG_LOCATION, ep->read_cb, error);
- SECURE_ENDPOINT_UNREF(ep, "read");
-}
-
-static void on_read(void* user_data, grpc_error* error) {
- unsigned i;
- uint8_t keep_looping = 0;
- tsi_result result = TSI_OK;
- secure_endpoint* ep = static_cast<secure_endpoint*>(user_data);
- uint8_t* cur = GRPC_SLICE_START_PTR(ep->read_staging_buffer);
- uint8_t* end = GRPC_SLICE_END_PTR(ep->read_staging_buffer);
-
- if (error != GRPC_ERROR_NONE) {
- grpc_slice_buffer_reset_and_unref_internal(ep->read_buffer);
- call_read_cb(ep, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
- "Secure read failed", &error, 1));
- return;
- }
-
- if (ep->zero_copy_protector != nullptr) {
- // Use zero-copy grpc protector to unprotect.
- result = tsi_zero_copy_grpc_protector_unprotect(
- ep->zero_copy_protector, &ep->source_buffer, ep->read_buffer);
- } else {
- // Use frame protector to unprotect.
- /* TODO(yangg) check error, maybe bail out early */
- for (i = 0; i < ep->source_buffer.count; i++) {
- grpc_slice encrypted = ep->source_buffer.slices[i];
- uint8_t* message_bytes = GRPC_SLICE_START_PTR(encrypted);
- size_t message_size = GRPC_SLICE_LENGTH(encrypted);
-
- while (message_size > 0 || keep_looping) {
- size_t unprotected_buffer_size_written = static_cast<size_t>(end - cur);
- size_t processed_message_size = message_size;
- gpr_mu_lock(&ep->protector_mu);
- result = tsi_frame_protector_unprotect(
- ep->protector, message_bytes, &processed_message_size, cur,
- &unprotected_buffer_size_written);
- gpr_mu_unlock(&ep->protector_mu);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Decryption error: %s",
- tsi_result_to_string(result));
- break;
- }
- message_bytes += processed_message_size;
- message_size -= processed_message_size;
- cur += unprotected_buffer_size_written;
-
- if (cur == end) {
- flush_read_staging_buffer(ep, &cur, &end);
- /* Force to enter the loop again to extract buffered bytes in
- protector. The bytes could be buffered because of running out of
- staging_buffer. If this happens at the end of all slices, doing
- another unprotect avoids leaving data in the protector. */
- keep_looping = 1;
- } else if (unprotected_buffer_size_written > 0) {
- keep_looping = 1;
- } else {
- keep_looping = 0;
- }
- }
- if (result != TSI_OK) break;
- }
-
- if (cur != GRPC_SLICE_START_PTR(ep->read_staging_buffer)) {
- grpc_slice_buffer_add(
- ep->read_buffer,
- grpc_slice_split_head(
- &ep->read_staging_buffer,
- static_cast<size_t>(
- cur - GRPC_SLICE_START_PTR(ep->read_staging_buffer))));
- }
- }
-
- /* TODO(yangg) experiment with moving this block after read_cb to see if it
- helps latency */
- grpc_slice_buffer_reset_and_unref_internal(&ep->source_buffer);
-
- if (result != TSI_OK) {
- grpc_slice_buffer_reset_and_unref_internal(ep->read_buffer);
- call_read_cb(
- ep, grpc_set_tsi_error_result(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Unwrap failed"), result));
- return;
- }
-
- call_read_cb(ep, GRPC_ERROR_NONE);
-}
-
-static void endpoint_read(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
+ SECURE_ENDPOINT_UNREF(ep, "read");
+}
+
+static void on_read(void* user_data, grpc_error* error) {
+ unsigned i;
+ uint8_t keep_looping = 0;
+ tsi_result result = TSI_OK;
+ secure_endpoint* ep = static_cast<secure_endpoint*>(user_data);
+ uint8_t* cur = GRPC_SLICE_START_PTR(ep->read_staging_buffer);
+ uint8_t* end = GRPC_SLICE_END_PTR(ep->read_staging_buffer);
+
+ if (error != GRPC_ERROR_NONE) {
+ grpc_slice_buffer_reset_and_unref_internal(ep->read_buffer);
+ call_read_cb(ep, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
+ "Secure read failed", &error, 1));
+ return;
+ }
+
+ if (ep->zero_copy_protector != nullptr) {
+ // Use zero-copy grpc protector to unprotect.
+ result = tsi_zero_copy_grpc_protector_unprotect(
+ ep->zero_copy_protector, &ep->source_buffer, ep->read_buffer);
+ } else {
+ // Use frame protector to unprotect.
+ /* TODO(yangg) check error, maybe bail out early */
+ for (i = 0; i < ep->source_buffer.count; i++) {
+ grpc_slice encrypted = ep->source_buffer.slices[i];
+ uint8_t* message_bytes = GRPC_SLICE_START_PTR(encrypted);
+ size_t message_size = GRPC_SLICE_LENGTH(encrypted);
+
+ while (message_size > 0 || keep_looping) {
+ size_t unprotected_buffer_size_written = static_cast<size_t>(end - cur);
+ size_t processed_message_size = message_size;
+ gpr_mu_lock(&ep->protector_mu);
+ result = tsi_frame_protector_unprotect(
+ ep->protector, message_bytes, &processed_message_size, cur,
+ &unprotected_buffer_size_written);
+ gpr_mu_unlock(&ep->protector_mu);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Decryption error: %s",
+ tsi_result_to_string(result));
+ break;
+ }
+ message_bytes += processed_message_size;
+ message_size -= processed_message_size;
+ cur += unprotected_buffer_size_written;
+
+ if (cur == end) {
+ flush_read_staging_buffer(ep, &cur, &end);
+ /* Force to enter the loop again to extract buffered bytes in
+ protector. The bytes could be buffered because of running out of
+ staging_buffer. If this happens at the end of all slices, doing
+ another unprotect avoids leaving data in the protector. */
+ keep_looping = 1;
+ } else if (unprotected_buffer_size_written > 0) {
+ keep_looping = 1;
+ } else {
+ keep_looping = 0;
+ }
+ }
+ if (result != TSI_OK) break;
+ }
+
+ if (cur != GRPC_SLICE_START_PTR(ep->read_staging_buffer)) {
+ grpc_slice_buffer_add(
+ ep->read_buffer,
+ grpc_slice_split_head(
+ &ep->read_staging_buffer,
+ static_cast<size_t>(
+ cur - GRPC_SLICE_START_PTR(ep->read_staging_buffer))));
+ }
+ }
+
+ /* TODO(yangg) experiment with moving this block after read_cb to see if it
+ helps latency */
+ grpc_slice_buffer_reset_and_unref_internal(&ep->source_buffer);
+
+ if (result != TSI_OK) {
+ grpc_slice_buffer_reset_and_unref_internal(ep->read_buffer);
+ call_read_cb(
+ ep, grpc_set_tsi_error_result(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Unwrap failed"), result));
+ return;
+ }
+
+ call_read_cb(ep, GRPC_ERROR_NONE);
+}
+
+static void endpoint_read(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
grpc_closure* cb, bool urgent) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- ep->read_cb = cb;
- ep->read_buffer = slices;
- grpc_slice_buffer_reset_and_unref_internal(ep->read_buffer);
-
- SECURE_ENDPOINT_REF(ep, "read");
- if (ep->leftover_bytes.count) {
- grpc_slice_buffer_swap(&ep->leftover_bytes, &ep->source_buffer);
- GPR_ASSERT(ep->leftover_bytes.count == 0);
- on_read(ep, GRPC_ERROR_NONE);
- return;
- }
-
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ ep->read_cb = cb;
+ ep->read_buffer = slices;
+ grpc_slice_buffer_reset_and_unref_internal(ep->read_buffer);
+
+ SECURE_ENDPOINT_REF(ep, "read");
+ if (ep->leftover_bytes.count) {
+ grpc_slice_buffer_swap(&ep->leftover_bytes, &ep->source_buffer);
+ GPR_ASSERT(ep->leftover_bytes.count == 0);
+ on_read(ep, GRPC_ERROR_NONE);
+ return;
+ }
+
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,
- uint8_t** end) {
- grpc_slice_buffer_add(&ep->output_buffer, ep->write_staging_buffer);
- ep->write_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE);
- *cur = GRPC_SLICE_START_PTR(ep->write_staging_buffer);
- *end = GRPC_SLICE_END_PTR(ep->write_staging_buffer);
-}
-
-static void endpoint_write(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
+}
+
+static void flush_write_staging_buffer(secure_endpoint* ep, uint8_t** cur,
+ uint8_t** end) {
+ grpc_slice_buffer_add(&ep->output_buffer, ep->write_staging_buffer);
+ ep->write_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE);
+ *cur = GRPC_SLICE_START_PTR(ep->write_staging_buffer);
+ *end = GRPC_SLICE_END_PTR(ep->write_staging_buffer);
+}
+
+static void endpoint_write(grpc_endpoint* secure_ep, grpc_slice_buffer* slices,
grpc_closure* cb, void* arg) {
- GPR_TIMER_SCOPE("secure_endpoint.endpoint_write", 0);
-
- unsigned i;
- tsi_result result = TSI_OK;
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- uint8_t* cur = GRPC_SLICE_START_PTR(ep->write_staging_buffer);
- uint8_t* end = GRPC_SLICE_END_PTR(ep->write_staging_buffer);
-
- grpc_slice_buffer_reset_and_unref_internal(&ep->output_buffer);
-
+ GPR_TIMER_SCOPE("secure_endpoint.endpoint_write", 0);
+
+ unsigned i;
+ tsi_result result = TSI_OK;
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ uint8_t* cur = GRPC_SLICE_START_PTR(ep->write_staging_buffer);
+ uint8_t* end = GRPC_SLICE_END_PTR(ep->write_staging_buffer);
+
+ grpc_slice_buffer_reset_and_unref_internal(&ep->output_buffer);
+
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);
- gpr_log(GPR_INFO, "WRITE %p: %s", ep, data);
- gpr_free(data);
- }
- }
-
- if (ep->zero_copy_protector != nullptr) {
- // Use zero-copy grpc protector to protect.
- result = tsi_zero_copy_grpc_protector_protect(ep->zero_copy_protector,
- slices, &ep->output_buffer);
- } else {
- // Use frame protector to protect.
- for (i = 0; i < slices->count; i++) {
- grpc_slice plain = slices->slices[i];
- uint8_t* message_bytes = GRPC_SLICE_START_PTR(plain);
- size_t message_size = GRPC_SLICE_LENGTH(plain);
- while (message_size > 0) {
- size_t protected_buffer_size_to_send = static_cast<size_t>(end - cur);
- size_t processed_message_size = message_size;
- gpr_mu_lock(&ep->protector_mu);
- result = tsi_frame_protector_protect(ep->protector, message_bytes,
- &processed_message_size, cur,
- &protected_buffer_size_to_send);
- gpr_mu_unlock(&ep->protector_mu);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Encryption error: %s",
- tsi_result_to_string(result));
- break;
- }
- message_bytes += processed_message_size;
- message_size -= processed_message_size;
- cur += protected_buffer_size_to_send;
-
- if (cur == end) {
- flush_write_staging_buffer(ep, &cur, &end);
- }
- }
- if (result != TSI_OK) break;
- }
- if (result == TSI_OK) {
- size_t still_pending_size;
- do {
- size_t protected_buffer_size_to_send = static_cast<size_t>(end - cur);
- gpr_mu_lock(&ep->protector_mu);
- result = tsi_frame_protector_protect_flush(
- ep->protector, cur, &protected_buffer_size_to_send,
- &still_pending_size);
- gpr_mu_unlock(&ep->protector_mu);
- if (result != TSI_OK) break;
- cur += protected_buffer_size_to_send;
- if (cur == end) {
- flush_write_staging_buffer(ep, &cur, &end);
- }
- } while (still_pending_size > 0);
- if (cur != GRPC_SLICE_START_PTR(ep->write_staging_buffer)) {
- grpc_slice_buffer_add(
- &ep->output_buffer,
- grpc_slice_split_head(
- &ep->write_staging_buffer,
- static_cast<size_t>(
- cur - GRPC_SLICE_START_PTR(ep->write_staging_buffer))));
- }
- }
- }
-
- if (result != TSI_OK) {
- /* TODO(yangg) do different things according to the error type? */
- grpc_slice_buffer_reset_and_unref_internal(&ep->output_buffer);
+ for (i = 0; i < slices->count; i++) {
+ char* data =
+ grpc_dump_slice(slices->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII);
+ gpr_log(GPR_INFO, "WRITE %p: %s", ep, data);
+ gpr_free(data);
+ }
+ }
+
+ if (ep->zero_copy_protector != nullptr) {
+ // Use zero-copy grpc protector to protect.
+ result = tsi_zero_copy_grpc_protector_protect(ep->zero_copy_protector,
+ slices, &ep->output_buffer);
+ } else {
+ // Use frame protector to protect.
+ for (i = 0; i < slices->count; i++) {
+ grpc_slice plain = slices->slices[i];
+ uint8_t* message_bytes = GRPC_SLICE_START_PTR(plain);
+ size_t message_size = GRPC_SLICE_LENGTH(plain);
+ while (message_size > 0) {
+ size_t protected_buffer_size_to_send = static_cast<size_t>(end - cur);
+ size_t processed_message_size = message_size;
+ gpr_mu_lock(&ep->protector_mu);
+ result = tsi_frame_protector_protect(ep->protector, message_bytes,
+ &processed_message_size, cur,
+ &protected_buffer_size_to_send);
+ gpr_mu_unlock(&ep->protector_mu);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Encryption error: %s",
+ tsi_result_to_string(result));
+ break;
+ }
+ message_bytes += processed_message_size;
+ message_size -= processed_message_size;
+ cur += protected_buffer_size_to_send;
+
+ if (cur == end) {
+ flush_write_staging_buffer(ep, &cur, &end);
+ }
+ }
+ if (result != TSI_OK) break;
+ }
+ if (result == TSI_OK) {
+ size_t still_pending_size;
+ do {
+ size_t protected_buffer_size_to_send = static_cast<size_t>(end - cur);
+ gpr_mu_lock(&ep->protector_mu);
+ result = tsi_frame_protector_protect_flush(
+ ep->protector, cur, &protected_buffer_size_to_send,
+ &still_pending_size);
+ gpr_mu_unlock(&ep->protector_mu);
+ if (result != TSI_OK) break;
+ cur += protected_buffer_size_to_send;
+ if (cur == end) {
+ flush_write_staging_buffer(ep, &cur, &end);
+ }
+ } while (still_pending_size > 0);
+ if (cur != GRPC_SLICE_START_PTR(ep->write_staging_buffer)) {
+ grpc_slice_buffer_add(
+ &ep->output_buffer,
+ grpc_slice_split_head(
+ &ep->write_staging_buffer,
+ static_cast<size_t>(
+ cur - GRPC_SLICE_START_PTR(ep->write_staging_buffer))));
+ }
+ }
+ }
+
+ 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));
- return;
- }
-
+ return;
+ }
+
grpc_endpoint_write(ep->wrapped_ep, &ep->output_buffer, cb, arg);
-}
-
-static void endpoint_shutdown(grpc_endpoint* secure_ep, grpc_error* why) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- grpc_endpoint_shutdown(ep->wrapped_ep, why);
-}
-
-static void endpoint_destroy(grpc_endpoint* secure_ep) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- SECURE_ENDPOINT_UNREF(ep, "destroy");
-}
-
-static void endpoint_add_to_pollset(grpc_endpoint* secure_ep,
- grpc_pollset* pollset) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- grpc_endpoint_add_to_pollset(ep->wrapped_ep, pollset);
-}
-
-static void endpoint_add_to_pollset_set(grpc_endpoint* secure_ep,
- grpc_pollset_set* pollset_set) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- grpc_endpoint_add_to_pollset_set(ep->wrapped_ep, pollset_set);
-}
-
-static void endpoint_delete_from_pollset_set(grpc_endpoint* secure_ep,
- grpc_pollset_set* pollset_set) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- grpc_endpoint_delete_from_pollset_set(ep->wrapped_ep, pollset_set);
-}
-
+}
+
+static void endpoint_shutdown(grpc_endpoint* secure_ep, grpc_error* why) {
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ grpc_endpoint_shutdown(ep->wrapped_ep, why);
+}
+
+static void endpoint_destroy(grpc_endpoint* secure_ep) {
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ SECURE_ENDPOINT_UNREF(ep, "destroy");
+}
+
+static void endpoint_add_to_pollset(grpc_endpoint* secure_ep,
+ grpc_pollset* pollset) {
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ grpc_endpoint_add_to_pollset(ep->wrapped_ep, pollset);
+}
+
+static void endpoint_add_to_pollset_set(grpc_endpoint* secure_ep,
+ grpc_pollset_set* pollset_set) {
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ grpc_endpoint_add_to_pollset_set(ep->wrapped_ep, pollset_set);
+}
+
+static void endpoint_delete_from_pollset_set(grpc_endpoint* secure_ep,
+ grpc_pollset_set* pollset_set) {
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ grpc_endpoint_delete_from_pollset_set(ep->wrapped_ep, pollset_set);
+}
+
static y_absl::string_view endpoint_get_peer(grpc_endpoint* secure_ep) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- return grpc_endpoint_get_peer(ep->wrapped_ep);
-}
-
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ return grpc_endpoint_get_peer(ep->wrapped_ep);
+}
+
static y_absl::string_view endpoint_get_local_address(grpc_endpoint* secure_ep) {
secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
return grpc_endpoint_get_local_address(ep->wrapped_ep);
}
-static int endpoint_get_fd(grpc_endpoint* secure_ep) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- return grpc_endpoint_get_fd(ep->wrapped_ep);
-}
-
-static grpc_resource_user* endpoint_get_resource_user(
- grpc_endpoint* secure_ep) {
- secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
- return grpc_endpoint_get_resource_user(ep->wrapped_ep);
-}
-
+static int endpoint_get_fd(grpc_endpoint* secure_ep) {
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ return grpc_endpoint_get_fd(ep->wrapped_ep);
+}
+
+static grpc_resource_user* endpoint_get_resource_user(
+ grpc_endpoint* secure_ep) {
+ secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
+ return grpc_endpoint_get_resource_user(ep->wrapped_ep);
+}
+
static bool endpoint_can_track_err(grpc_endpoint* secure_ep) {
secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep);
return grpc_endpoint_can_track_err(ep->wrapped_ep);
}
-static const grpc_endpoint_vtable vtable = {endpoint_read,
- endpoint_write,
- endpoint_add_to_pollset,
- endpoint_add_to_pollset_set,
- endpoint_delete_from_pollset_set,
- endpoint_shutdown,
- endpoint_destroy,
- endpoint_get_resource_user,
- endpoint_get_peer,
+static const grpc_endpoint_vtable vtable = {endpoint_read,
+ endpoint_write,
+ endpoint_add_to_pollset,
+ endpoint_add_to_pollset_set,
+ endpoint_delete_from_pollset_set,
+ endpoint_shutdown,
+ endpoint_destroy,
+ endpoint_get_resource_user,
+ endpoint_get_peer,
endpoint_get_local_address,
endpoint_get_fd,
endpoint_can_track_err};
-
-grpc_endpoint* grpc_secure_endpoint_create(
- struct tsi_frame_protector* protector,
- struct tsi_zero_copy_grpc_protector* zero_copy_protector,
- grpc_endpoint* transport, grpc_slice* leftover_slices,
- size_t leftover_nslices) {
+
+grpc_endpoint* grpc_secure_endpoint_create(
+ struct tsi_frame_protector* protector,
+ 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);
- return &ep->base;
-}
+ return &ep->base;
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.h b/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.h
index e7e33516789..b6481650644 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.h
+++ b/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.h
@@ -1,41 +1,41 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_SECURE_ENDPOINT_H
#define GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURE_ENDPOINT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice.h>
#include "src/core/lib/iomgr/endpoint.h"
struct tsi_frame_protector;
-struct tsi_zero_copy_grpc_protector;
+struct tsi_zero_copy_grpc_protector;
-extern grpc_core::TraceFlag grpc_trace_secure_endpoint;
+extern grpc_core::TraceFlag grpc_trace_secure_endpoint;
-/* Takes ownership of protector, zero_copy_protector, and to_wrap, and refs
- * leftover_slices. If zero_copy_protector is not NULL, protector will never be
- * used. */
-grpc_endpoint* grpc_secure_endpoint_create(
- struct tsi_frame_protector* protector,
- struct tsi_zero_copy_grpc_protector* zero_copy_protector,
- grpc_endpoint* to_wrap, grpc_slice* leftover_slices,
- size_t leftover_nslices);
+/* Takes ownership of protector, zero_copy_protector, and to_wrap, and refs
+ * leftover_slices. If zero_copy_protector is not NULL, protector will never be
+ * used. */
+grpc_endpoint* grpc_secure_endpoint_create(
+ struct tsi_frame_protector* protector,
+ struct tsi_zero_copy_grpc_protector* zero_copy_protector,
+ grpc_endpoint* to_wrap, grpc_slice* leftover_slices,
+ size_t leftover_nslices);
#endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURE_ENDPOINT_H */
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 079b49c95a6..a3f4c835f58 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/security/transport/security_handshaker.h"
-
-#include <stdbool.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/lib/security/transport/security_handshaker.h"
+
+#include <stdbool.h>
+#include <string.h>
#include <limits>
-
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/handshaker.h"
-#include "src/core/lib/channel/handshaker_registry.h"
+
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/channel/channel_args.h"
+#include "src/core/lib/channel/handshaker.h"
+#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/security/context/security_context.h"
-#include "src/core/lib/security/transport/secure_endpoint.h"
-#include "src/core/lib/security/transport/tsi_error.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/tsi/transport_security_grpc.h"
-
-#define GRPC_INITIAL_HANDSHAKE_BUFFER_SIZE 256
-
+#include "src/core/lib/security/context/security_context.h"
+#include "src/core/lib/security/transport/secure_endpoint.h"
+#include "src/core/lib/security/transport/tsi_error.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/tsi/transport_security_grpc.h"
+
+#define GRPC_INITIAL_HANDSHAKE_BUFFER_SIZE 256
+
namespace grpc_core {
-
+
namespace {
class SecurityHandshaker : public Handshaker {
@@ -80,21 +80,21 @@ class SecurityHandshaker : public Handshaker {
size_t MoveReadBufferIntoHandshakeBuffer();
grpc_error* CheckPeerLocked();
- // State set at creation time.
+ // State set at creation time.
tsi_handshaker* handshaker_;
RefCountedPtr<grpc_security_connector> connector_;
-
+
gpr_mu mu_;
-
+
bool is_shutdown_ = false;
- // Endpoint and read buffer to destroy after a shutdown.
+ // Endpoint and read buffer to destroy after a shutdown.
grpc_endpoint* endpoint_to_destroy_ = nullptr;
grpc_slice_buffer* read_buffer_to_destroy_ = nullptr;
-
- // State saved while performing the handshake.
+
+ // State saved while performing the handshake.
HandshakerArgs* args_ = nullptr;
grpc_closure* on_handshake_done_ = nullptr;
-
+
size_t handshake_buffer_size_;
unsigned char* handshake_buffer_;
grpc_slice_buffer outgoing_;
@@ -105,7 +105,7 @@ class SecurityHandshaker : public Handshaker {
tsi_handshaker_result* handshaker_result_ = nullptr;
size_t max_frame_size_ = 0;
};
-
+
SecurityHandshaker::SecurityHandshaker(tsi_handshaker* handshaker,
grpc_security_connector* connector,
const grpc_channel_args* args)
@@ -132,7 +132,7 @@ SecurityHandshaker::~SecurityHandshaker() {
tsi_handshaker_result_destroy(handshaker_result_);
if (endpoint_to_destroy_ != nullptr) {
grpc_endpoint_destroy(endpoint_to_destroy_);
- }
+ }
if (read_buffer_to_destroy_ != nullptr) {
grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_);
gpr_free(read_buffer_to_destroy_);
@@ -150,19 +150,19 @@ size_t SecurityHandshaker::MoveReadBufferIntoHandshakeBuffer() {
gpr_realloc(handshake_buffer_, bytes_in_read_buffer));
handshake_buffer_size_ = bytes_in_read_buffer;
}
- size_t offset = 0;
+ 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);
- }
- return bytes_in_read_buffer;
-}
-
+ }
+ return bytes_in_read_buffer;
+}
+
// Set args_ fields to NULL, saving the endpoint and read buffer for
-// later destruction.
+// later destruction.
void SecurityHandshaker::CleanupArgsForFailureLocked() {
endpoint_to_destroy_ = args_->endpoint;
args_->endpoint = nullptr;
@@ -170,129 +170,129 @@ void SecurityHandshaker::CleanupArgsForFailureLocked() {
args_->read_buffer = nullptr;
grpc_channel_args_destroy(args_->args);
args_->args = nullptr;
-}
-
-// If the handshake failed or we're shutting down, clean up and invoke the
-// callback with the error.
+}
+
+// If the handshake failed or we're shutting down, clean up and invoke the
+// callback with the error.
void SecurityHandshaker::HandshakeFailedLocked(grpc_error* error) {
- if (error == GRPC_ERROR_NONE) {
- // If we were shut down after the handshake succeeded but before an
- // endpoint callback was invoked, we need to generate our own error.
- error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
- }
- const char* msg = grpc_error_string(error);
- gpr_log(GPR_DEBUG, "Security handshake failed: %s", msg);
-
+ if (error == GRPC_ERROR_NONE) {
+ // If we were shut down after the handshake succeeded but before an
+ // endpoint callback was invoked, we need to generate our own error.
+ error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
+ }
+ const char* msg = grpc_error_string(error);
+ gpr_log(GPR_DEBUG, "Security handshake failed: %s", msg);
+
if (!is_shutdown_) {
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
- // point this can be removed.
+ // 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));
- // Not shutting down, so the write failed. Clean up before
- // invoking the callback.
+ // Not shutting down, so the write failed. Clean up before
+ // invoking the callback.
CleanupArgsForFailureLocked();
- // Set shutdown to true so that subsequent calls to
- // security_handshaker_shutdown() do nothing.
+ // Set shutdown to true so that subsequent calls to
+ // security_handshaker_shutdown() do nothing.
is_shutdown_ = true;
- }
- // Invoke callback.
+ }
+ // Invoke callback.
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);
- 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(
+ 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);
- if (result != TSI_OK && result != TSI_UNIMPLEMENTED) {
- error = grpc_set_tsi_error_result(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Zero-copy frame protector creation failed"),
- result);
+ if (result != TSI_OK && result != TSI_UNIMPLEMENTED) {
+ error = grpc_set_tsi_error_result(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Zero-copy frame protector creation failed"),
+ result);
HandshakeFailedLocked(error);
- return;
- }
- // Create frame protector if zero-copy frame protector is NULL.
- tsi_frame_protector* protector = nullptr;
- if (zero_copy_protector == nullptr) {
+ return;
+ }
+ // 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);
- if (result != TSI_OK) {
- error = grpc_set_tsi_error_result(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Frame protector creation failed"),
- result);
+ if (result != TSI_OK) {
+ error = grpc_set_tsi_error_result(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Frame protector creation failed"),
+ result);
HandshakeFailedLocked(error);
- return;
- }
- }
- // Get unused bytes.
- const unsigned char* unused_bytes = nullptr;
- size_t unused_bytes_size = 0;
- result = tsi_handshaker_result_get_unused_bytes(
+ return;
+ }
+ }
+ // Get unused bytes.
+ const unsigned char* unused_bytes = nullptr;
+ size_t unused_bytes_size = 0;
+ result = tsi_handshaker_result_get_unused_bytes(
handshaker_result_, &unused_bytes, &unused_bytes_size);
- // Create secure endpoint.
- if (unused_bytes_size > 0) {
- grpc_slice slice =
- grpc_slice_from_copied_buffer((char*)unused_bytes, unused_bytes_size);
+ // Create secure endpoint.
+ if (unused_bytes_size > 0) {
+ grpc_slice slice =
+ grpc_slice_from_copied_buffer((char*)unused_bytes, unused_bytes_size);
args_->endpoint = grpc_secure_endpoint_create(
protector, zero_copy_protector, args_->endpoint, &slice, 1);
- grpc_slice_unref_internal(slice);
- } else {
+ grpc_slice_unref_internal(slice);
+ } else {
args_->endpoint = grpc_secure_endpoint_create(
protector, zero_copy_protector, args_->endpoint, nullptr, 0);
- }
+ }
tsi_handshaker_result_destroy(handshaker_result_);
handshaker_result_ = nullptr;
- // Add auth context to channel args.
+ // Add auth context to channel args.
grpc_arg auth_context_arg = grpc_auth_context_to_arg(auth_context_.get());
grpc_channel_args* tmp_args = args_->args;
args_->args = grpc_channel_args_copy_and_add(tmp_args, &auth_context_arg, 1);
- grpc_channel_args_destroy(tmp_args);
- // Invoke callback.
+ grpc_channel_args_destroy(tmp_args);
+ // Invoke callback.
ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, GRPC_ERROR_NONE);
- // Set shutdown to true so that subsequent calls to
- // security_handshaker_shutdown() do nothing.
+ // Set shutdown to true so that subsequent calls to
+ // security_handshaker_shutdown() do nothing.
is_shutdown_ = true;
-}
-
+}
+
void SecurityHandshaker::OnPeerCheckedFn(void* arg, grpc_error* error) {
RefCountedPtr<SecurityHandshaker>(static_cast<SecurityHandshaker*>(arg))
->OnPeerCheckedInner(GRPC_ERROR_REF(error));
-}
-
+}
+
grpc_error* SecurityHandshaker::CheckPeerLocked() {
- tsi_peer peer;
- tsi_result result =
+ tsi_peer peer;
+ tsi_result result =
tsi_handshaker_result_extract_peer(handshaker_result_, &peer);
- if (result != TSI_OK) {
- return grpc_set_tsi_error_result(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Peer extraction failed"), result);
- }
+ if (result != TSI_OK) {
+ return grpc_set_tsi_error_result(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Peer extraction failed"), result);
+ }
connector_->check_peer(peer, args_->endpoint, &auth_context_,
&on_peer_checked_);
- return GRPC_ERROR_NONE;
-}
-
+ return GRPC_ERROR_NONE;
+}
+
grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked(
tsi_result result, const unsigned char* bytes_to_send,
size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result) {
- grpc_error* error = GRPC_ERROR_NONE;
- // Handshaker was shutdown.
+ grpc_error* error = GRPC_ERROR_NONE;
+ // Handshaker was shutdown.
if (is_shutdown_) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
- }
- // Read more if we need to.
- if (result == TSI_INCOMPLETE_DATA) {
- GPR_ASSERT(bytes_to_send_size == 0);
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown");
+ }
+ // 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(
@@ -300,21 +300,21 @@ grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked(
&SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
this, grpc_schedule_on_exec_ctx),
/*urgent=*/true);
- return error;
- }
- if (result != TSI_OK) {
- return grpc_set_tsi_error_result(
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshake failed"), result);
- }
- // Update handshaker result.
- if (handshaker_result != nullptr) {
+ return error;
+ }
+ if (result != TSI_OK) {
+ return grpc_set_tsi_error_result(
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshake failed"), result);
+ }
+ // Update handshaker result.
+ if (handshaker_result != nullptr) {
GPR_ASSERT(handshaker_result_ == nullptr);
handshaker_result_ = handshaker_result;
- }
- if (bytes_to_send_size > 0) {
- // Send data to peer, if needed.
- grpc_slice to_send = grpc_slice_from_copied_buffer(
- reinterpret_cast<const char*>(bytes_to_send), bytes_to_send_size);
+ }
+ if (bytes_to_send_size > 0) {
+ // Send data to peer, if needed.
+ grpc_slice to_send = grpc_slice_from_copied_buffer(
+ 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(
@@ -324,8 +324,8 @@ grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked(
&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.
+ } 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(
@@ -333,48 +333,48 @@ grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked(
&SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
this, grpc_schedule_on_exec_ctx),
/*urgent=*/true);
- } else {
- // Handshake has finished, check peer and so on.
+ } else {
+ // Handshake has finished, check peer and so on.
error = CheckPeerLocked();
- }
- return error;
-}
-
+ }
+ return error;
+}
+
void SecurityHandshaker::OnHandshakeNextDoneGrpcWrapper(
- tsi_result result, void* user_data, const unsigned char* bytes_to_send,
- size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result) {
+ tsi_result result, void* user_data, const unsigned char* bytes_to_send,
+ size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result) {
RefCountedPtr<SecurityHandshaker> h(
static_cast<SecurityHandshaker*>(user_data));
MutexLock lock(&h->mu_);
grpc_error* error = h->OnHandshakeNextDoneLocked(
result, bytes_to_send, bytes_to_send_size, handshaker_result);
- if (error != GRPC_ERROR_NONE) {
+ if (error != GRPC_ERROR_NONE) {
h->HandshakeFailedLocked(error);
- } else {
+ } else {
h.release(); // Avoid unref
- }
-}
-
+ }
+}
+
grpc_error* SecurityHandshaker::DoHandshakerNextLocked(
const unsigned char* bytes_received, size_t bytes_received_size) {
- // Invoke TSI handshaker.
- const unsigned char* bytes_to_send = nullptr;
- size_t bytes_to_send_size = 0;
+ // Invoke TSI handshaker.
+ const unsigned char* bytes_to_send = nullptr;
+ size_t bytes_to_send_size = 0;
tsi_handshaker_result* hs_result = nullptr;
- tsi_result result = tsi_handshaker_next(
+ tsi_result result = tsi_handshaker_next(
handshaker_, bytes_received, bytes_received_size, &bytes_to_send,
&bytes_to_send_size, &hs_result, &OnHandshakeNextDoneGrpcWrapper, this);
- if (result == TSI_ASYNC) {
- // Handshaker operating asynchronously. Nothing else to do here;
- // callback will be invoked in a TSI thread.
- return GRPC_ERROR_NONE;
- }
- // Handshaker returned synchronously. Invoke callback directly in
- // this thread with our existing exec_ctx.
+ if (result == TSI_ASYNC) {
+ // Handshaker operating asynchronously. Nothing else to do here;
+ // callback will be invoked in a TSI thread.
+ return GRPC_ERROR_NONE;
+ }
+ // Handshaker returned synchronously. Invoke callback directly in
+ // this thread with our existing exec_ctx.
return OnHandshakeNextDoneLocked(result, bytes_to_send, bytes_to_send_size,
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(
@@ -395,20 +395,20 @@ void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFn(void* arg,
if (error != GRPC_ERROR_NONE || h->is_shutdown_) {
h->HandshakeFailedLocked(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Handshake read failed", &error, 1));
- return;
- }
- // Copy all slices received.
+ return;
+ }
+ // Copy all slices received.
size_t bytes_received_size = h->MoveReadBufferIntoHandshakeBuffer();
- // Call TSI handshaker.
+ // Call TSI handshaker.
error = h->DoHandshakerNextLocked(h->handshake_buffer_, bytes_received_size);
-
- if (error != GRPC_ERROR_NONE) {
+
+ if (error != GRPC_ERROR_NONE) {
h->HandshakeFailedLocked(error);
- } else {
+ } else {
h.release(); // Avoid unref
- }
-}
-
+ }
+}
+
// 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(
@@ -429,9 +429,9 @@ void SecurityHandshaker::OnHandshakeDataSentToPeerFn(void* arg,
if (error != GRPC_ERROR_NONE || h->is_shutdown_) {
h->HandshakeFailedLocked(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Handshake write failed", &error, 1));
- return;
- }
- // We may be done.
+ return;
+ }
+ // We may be done.
if (h->handshaker_result_ == nullptr) {
grpc_endpoint_read(
h->args_->endpoint, h->args_->read_buffer,
@@ -440,20 +440,20 @@ void SecurityHandshaker::OnHandshakeDataSentToPeerFn(void* arg,
&SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler,
h.get(), grpc_schedule_on_exec_ctx),
/*urgent=*/true);
- } else {
+ } else {
error = h->CheckPeerLocked();
- if (error != GRPC_ERROR_NONE) {
+ if (error != GRPC_ERROR_NONE) {
h->HandshakeFailedLocked(error);
- return;
- }
- }
+ return;
+ }
+ }
h.release(); // Avoid unref
-}
-
-//
-// public handshaker API
-//
-
+}
+
+//
+// public handshaker API
+//
+
void SecurityHandshaker::Shutdown(grpc_error* why) {
MutexLock lock(&mu_);
if (!is_shutdown_) {
@@ -461,10 +461,10 @@ void SecurityHandshaker::Shutdown(grpc_error* why) {
tsi_handshaker_shutdown(handshaker_);
grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why));
CleanupArgsForFailureLocked();
- }
- GRPC_ERROR_UNREF(why);
-}
-
+ }
+ GRPC_ERROR_UNREF(why);
+}
+
void SecurityHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
grpc_closure* on_handshake_done,
HandshakerArgs* args) {
@@ -473,19 +473,19 @@ void SecurityHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/,
args_ = args;
on_handshake_done_ = on_handshake_done;
size_t bytes_received_size = MoveReadBufferIntoHandshakeBuffer();
- grpc_error* error =
+ grpc_error* error =
DoHandshakerNextLocked(handshake_buffer_, bytes_received_size);
- if (error != GRPC_ERROR_NONE) {
+ if (error != GRPC_ERROR_NONE) {
HandshakeFailedLocked(error);
} else {
ref.release(); // Avoid unref
- }
-}
-
-//
+ }
+}
+
+//
// FailHandshaker
-//
-
+//
+
class FailHandshaker : public Handshaker {
public:
const char* name() const override { return "security_fail"; }
@@ -497,15 +497,15 @@ class FailHandshaker : public Handshaker {
GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"Failed to create security handshaker"));
}
-
+
private:
virtual ~FailHandshaker() = default;
};
-
-//
-// handshaker factories
-//
-
+
+//
+// handshaker factories
+//
+
class ClientSecurityHandshakerFactory : public HandshakerFactory {
public:
void AddHandshakers(const grpc_channel_args* args,
@@ -521,7 +521,7 @@ class ClientSecurityHandshakerFactory : public HandshakerFactory {
}
~ClientSecurityHandshakerFactory() override = default;
};
-
+
class ServerSecurityHandshakerFactory : public HandshakerFactory {
public:
void AddHandshakers(const grpc_channel_args* args,
@@ -537,25 +537,25 @@ class ServerSecurityHandshakerFactory : public HandshakerFactory {
}
~ServerSecurityHandshakerFactory() override = default;
};
-
+
} // namespace
-
-//
-// exported functions
-//
-
+
+//
+// exported functions
+//
+
RefCountedPtr<Handshaker> SecurityHandshakerCreate(
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) {
+ // 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 {
+ } else {
return MakeRefCounted<SecurityHandshaker>(handshaker, connector, args);
- }
-}
-
+ }
+}
+
void SecurityRegisterHandshakerFactories() {
HandshakerRegistry::RegisterHandshakerFactory(
false /* at_start */, HANDSHAKER_CLIENT,
@@ -563,7 +563,7 @@ void SecurityRegisterHandshakerFactories() {
HandshakerRegistry::RegisterHandshakerFactory(
false /* at_start */, HANDSHAKER_SERVER,
y_absl::make_unique<ServerSecurityHandshakerFactory>());
-}
+}
} // namespace grpc_core
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 a9e1fe83d45..1b179f357fe 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
@@ -1,28 +1,28 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_SECURITY_HANDSHAKER_H
#define GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURITY_HANDSHAKER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/channel/handshaker.h"
-#include "src/core/lib/security/security_connector/security_connector.h"
+#include "src/core/lib/security/security_connector/security_connector.h"
namespace grpc_core {
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 6f83a179b43..2eedb83cffa 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/security/context/security_context.h"
-#include "src/core/lib/security/credentials/credentials.h"
-#include "src/core/lib/security/transport/auth_filters.h"
-#include "src/core/lib/slice/slice_internal.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 <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/security/context/security_context.h"
+#include "src/core/lib/security/credentials/credentials.h"
+#include "src/core/lib/security/transport/auth_filters.h"
+#include "src/core/lib/slice/slice_internal.h"
+
static void recv_initial_metadata_ready(void* arg, grpc_error* error);
static void recv_trailing_metadata_ready(void* user_data, grpc_error* error);
-namespace {
-enum async_state {
- STATE_INIT = 0,
- STATE_DONE,
- STATE_CANCELLED,
-};
-
+namespace {
+enum async_state {
+ STATE_INIT = 0,
+ STATE_DONE,
+ STATE_CANCELLED,
+};
+
struct channel_data {
channel_data(grpc_auth_context* auth_context, grpc_server_credentials* creds)
: auth_context(auth_context->Ref()), creds(creds->Ref()) {}
@@ -47,7 +47,7 @@ struct channel_data {
grpc_core::RefCountedPtr<grpc_server_credentials> creds;
};
-struct call_data {
+struct call_data {
call_data(grpc_call_element* elem, const grpc_call_element_args& args)
: call_combiner(args.call_combiner), owning_call(args.call_stack) {
GRPC_CLOSURE_INIT(&recv_initial_metadata_ready,
@@ -75,81 +75,81 @@ struct call_data {
~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); }
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;
- grpc_closure recv_initial_metadata_ready;
+ grpc_call_stack* owning_call;
+ grpc_transport_stream_op_batch* recv_initial_metadata_batch;
+ grpc_closure* original_recv_initial_metadata_ready;
+ grpc_closure recv_initial_metadata_ready;
grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE;
grpc_closure recv_trailing_metadata_ready;
grpc_closure* original_recv_trailing_metadata_ready;
grpc_error* recv_trailing_metadata_error;
bool seen_recv_trailing_metadata_ready = false;
- grpc_metadata_array md;
- const grpc_metadata* consumed_md;
- size_t num_consumed_md;
- grpc_closure cancel_closure;
+ grpc_metadata_array md;
+ const grpc_metadata* consumed_md;
+ size_t num_consumed_md;
+ grpc_closure cancel_closure;
gpr_atm state = STATE_INIT; // async_state
-};
-
-} // namespace
-
-static grpc_metadata_array metadata_batch_to_md_array(
- const grpc_metadata_batch* batch) {
- grpc_linked_mdelem* l;
- grpc_metadata_array result;
- grpc_metadata_array_init(&result);
- for (l = batch->list.head; l != nullptr; l = l->next) {
- grpc_metadata* usr_md = nullptr;
- grpc_mdelem md = l->md;
- grpc_slice key = GRPC_MDKEY(md);
- grpc_slice value = GRPC_MDVALUE(md);
- if (result.count == result.capacity) {
- result.capacity = GPR_MAX(result.capacity + 8, result.capacity * 2);
- result.metadata = static_cast<grpc_metadata*>(gpr_realloc(
- result.metadata, result.capacity * sizeof(grpc_metadata)));
- }
- usr_md = &result.metadata[result.count++];
- usr_md->key = grpc_slice_ref_internal(key);
- usr_md->value = grpc_slice_ref_internal(value);
- }
- return result;
-}
-
-static grpc_filtered_mdelem remove_consumed_md(void* user_data,
- grpc_mdelem md) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
- call_data* calld = static_cast<call_data*>(elem->call_data);
- size_t i;
- for (i = 0; i < calld->num_consumed_md; i++) {
- const grpc_metadata* consumed_md = &calld->consumed_md[i];
- if (grpc_slice_eq(GRPC_MDKEY(md), consumed_md->key) &&
- grpc_slice_eq(GRPC_MDVALUE(md), consumed_md->value))
- return GRPC_FILTERED_REMOVE();
- }
- return GRPC_FILTERED_MDELEM(md);
-}
-
-static void on_md_processing_done_inner(grpc_call_element* elem,
- const grpc_metadata* consumed_md,
- size_t num_consumed_md,
- const grpc_metadata* response_md,
- size_t num_response_md,
- grpc_error* error) {
- call_data* calld = static_cast<call_data*>(elem->call_data);
- grpc_transport_stream_op_batch* batch = calld->recv_initial_metadata_batch;
- /* TODO(jboeuf): Implement support for response_md. */
- if (response_md != nullptr && num_response_md > 0) {
- gpr_log(GPR_INFO,
- "response_md in auth metadata processing not supported for now. "
- "Ignoring...");
- }
- if (error == GRPC_ERROR_NONE) {
- calld->consumed_md = consumed_md;
- calld->num_consumed_md = num_consumed_md;
- error = grpc_metadata_batch_filter(
- batch->payload->recv_initial_metadata.recv_initial_metadata,
- remove_consumed_md, elem, "Response metadata filtering error");
- }
+};
+
+} // namespace
+
+static grpc_metadata_array metadata_batch_to_md_array(
+ const grpc_metadata_batch* batch) {
+ grpc_linked_mdelem* l;
+ grpc_metadata_array result;
+ grpc_metadata_array_init(&result);
+ for (l = batch->list.head; l != nullptr; l = l->next) {
+ grpc_metadata* usr_md = nullptr;
+ grpc_mdelem md = l->md;
+ grpc_slice key = GRPC_MDKEY(md);
+ grpc_slice value = GRPC_MDVALUE(md);
+ if (result.count == result.capacity) {
+ result.capacity = GPR_MAX(result.capacity + 8, result.capacity * 2);
+ result.metadata = static_cast<grpc_metadata*>(gpr_realloc(
+ result.metadata, result.capacity * sizeof(grpc_metadata)));
+ }
+ usr_md = &result.metadata[result.count++];
+ usr_md->key = grpc_slice_ref_internal(key);
+ usr_md->value = grpc_slice_ref_internal(value);
+ }
+ return result;
+}
+
+static grpc_filtered_mdelem remove_consumed_md(void* user_data,
+ grpc_mdelem md) {
+ grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ size_t i;
+ for (i = 0; i < calld->num_consumed_md; i++) {
+ const grpc_metadata* consumed_md = &calld->consumed_md[i];
+ if (grpc_slice_eq(GRPC_MDKEY(md), consumed_md->key) &&
+ grpc_slice_eq(GRPC_MDVALUE(md), consumed_md->value))
+ return GRPC_FILTERED_REMOVE();
+ }
+ return GRPC_FILTERED_MDELEM(md);
+}
+
+static void on_md_processing_done_inner(grpc_call_element* elem,
+ const grpc_metadata* consumed_md,
+ size_t num_consumed_md,
+ const grpc_metadata* response_md,
+ size_t num_response_md,
+ grpc_error* error) {
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_transport_stream_op_batch* batch = calld->recv_initial_metadata_batch;
+ /* TODO(jboeuf): Implement support for response_md. */
+ if (response_md != nullptr && num_response_md > 0) {
+ gpr_log(GPR_INFO,
+ "response_md in auth metadata processing not supported for now. "
+ "Ignoring...");
+ }
+ if (error == GRPC_ERROR_NONE) {
+ calld->consumed_md = consumed_md;
+ calld->num_consumed_md = num_consumed_md;
+ error = grpc_metadata_batch_filter(
+ batch->payload->recv_initial_metadata.recv_initial_metadata,
+ remove_consumed_md, elem, "Response metadata filtering error");
+ }
calld->recv_initial_metadata_error = GRPC_ERROR_REF(error);
grpc_closure* closure = calld->original_recv_initial_metadata_ready;
calld->original_recv_initial_metadata_ready = nullptr;
@@ -160,76 +160,76 @@ static void on_md_processing_done_inner(grpc_call_element* elem,
"continue recv_trailing_metadata_ready");
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
-}
-
-// Called from application code.
-static void on_md_processing_done(
- void* user_data, const grpc_metadata* consumed_md, size_t num_consumed_md,
- const grpc_metadata* response_md, size_t num_response_md,
- grpc_status_code status, const char* error_details) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
- call_data* calld = static_cast<call_data*>(elem->call_data);
+}
+
+// Called from application code.
+static void on_md_processing_done(
+ void* user_data, const grpc_metadata* consumed_md, size_t num_consumed_md,
+ const grpc_metadata* response_md, size_t num_response_md,
+ grpc_status_code status, const char* error_details) {
+ grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- // If the call was not cancelled while we were in flight, process the result.
- if (gpr_atm_full_cas(&calld->state, static_cast<gpr_atm>(STATE_INIT),
- static_cast<gpr_atm>(STATE_DONE))) {
- grpc_error* error = GRPC_ERROR_NONE;
- if (status != GRPC_STATUS_OK) {
- if (error_details == nullptr) {
- error_details = "Authentication metadata processing failed.";
- }
- error = grpc_error_set_int(
- GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_details),
- GRPC_ERROR_INT_GRPC_STATUS, status);
- }
- on_md_processing_done_inner(elem, consumed_md, num_consumed_md, response_md,
- num_response_md, error);
- }
- // Clean up.
- for (size_t i = 0; i < calld->md.count; i++) {
- grpc_slice_unref_internal(calld->md.metadata[i].key);
- grpc_slice_unref_internal(calld->md.metadata[i].value);
- }
- grpc_metadata_array_destroy(&calld->md);
- GRPC_CALL_STACK_UNREF(calld->owning_call, "server_auth_metadata");
-}
-
-static void cancel_call(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);
- // If the result was not already processed, invoke the callback now.
- if (error != GRPC_ERROR_NONE &&
- gpr_atm_full_cas(&calld->state, static_cast<gpr_atm>(STATE_INIT),
- static_cast<gpr_atm>(STATE_CANCELLED))) {
- on_md_processing_done_inner(elem, nullptr, 0, nullptr, 0,
- GRPC_ERROR_REF(error));
- }
-}
-
-static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
- grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
- call_data* calld = static_cast<call_data*>(elem->call_data);
- grpc_transport_stream_op_batch* batch = calld->recv_initial_metadata_batch;
- if (error == GRPC_ERROR_NONE) {
+ grpc_core::ExecCtx exec_ctx;
+ // If the call was not cancelled while we were in flight, process the result.
+ if (gpr_atm_full_cas(&calld->state, static_cast<gpr_atm>(STATE_INIT),
+ static_cast<gpr_atm>(STATE_DONE))) {
+ grpc_error* error = GRPC_ERROR_NONE;
+ if (status != GRPC_STATUS_OK) {
+ if (error_details == nullptr) {
+ error_details = "Authentication metadata processing failed.";
+ }
+ error = grpc_error_set_int(
+ GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_details),
+ GRPC_ERROR_INT_GRPC_STATUS, status);
+ }
+ on_md_processing_done_inner(elem, consumed_md, num_consumed_md, response_md,
+ num_response_md, error);
+ }
+ // Clean up.
+ for (size_t i = 0; i < calld->md.count; i++) {
+ grpc_slice_unref_internal(calld->md.metadata[i].key);
+ grpc_slice_unref_internal(calld->md.metadata[i].value);
+ }
+ grpc_metadata_array_destroy(&calld->md);
+ GRPC_CALL_STACK_UNREF(calld->owning_call, "server_auth_metadata");
+}
+
+static void cancel_call(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);
+ // If the result was not already processed, invoke the callback now.
+ if (error != GRPC_ERROR_NONE &&
+ gpr_atm_full_cas(&calld->state, static_cast<gpr_atm>(STATE_INIT),
+ static_cast<gpr_atm>(STATE_CANCELLED))) {
+ on_md_processing_done_inner(elem, nullptr, 0, nullptr, 0,
+ GRPC_ERROR_REF(error));
+ }
+}
+
+static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
+ grpc_call_element* elem = static_cast<grpc_call_element*>(arg);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ call_data* calld = static_cast<call_data*>(elem->call_data);
+ grpc_transport_stream_op_batch* batch = calld->recv_initial_metadata_batch;
+ if (error == GRPC_ERROR_NONE) {
if (chand->creds != nullptr &&
chand->creds->auth_metadata_processor().process != nullptr) {
- // We're calling out to the application, so we need to make sure
- // to drop the call combiner early if we get cancelled.
- GRPC_CLOSURE_INIT(&calld->cancel_closure, cancel_call, elem,
- grpc_schedule_on_exec_ctx);
+ // We're calling out to the application, so we need to make sure
+ // 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);
- 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);
+ 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);
chand->creds->auth_metadata_processor().process(
chand->creds->auth_metadata_processor().state,
chand->auth_context.get(), calld->md.metadata, calld->md.count,
on_md_processing_done, elem);
- return;
- }
- }
+ return;
+ }
+ }
grpc_closure* closure = calld->original_recv_initial_metadata_ready;
calld->original_recv_initial_metadata_ready = nullptr;
if (calld->seen_recv_trailing_metadata_ready) {
@@ -239,8 +239,8 @@ static void recv_initial_metadata_ready(void* arg, grpc_error* error) {
"continue recv_trailing_metadata_ready");
}
grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error));
-}
-
+}
+
static void recv_trailing_metadata_ready(void* user_data, grpc_error* err) {
grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
call_data* calld = static_cast<call_data*>(elem->call_data);
@@ -259,68 +259,68 @@ static void recv_trailing_metadata_ready(void* user_data, grpc_error* err) {
}
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) {
- // Inject our callback.
- calld->recv_initial_metadata_batch = batch;
- calld->original_recv_initial_metadata_ready =
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready;
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
- &calld->recv_initial_metadata_ready;
- }
+ 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) {
+ // Inject our callback.
+ calld->recv_initial_metadata_batch = batch;
+ calld->original_recv_initial_metadata_ready =
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready;
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready =
+ &calld->recv_initial_metadata_ready;
+ }
if (batch->recv_trailing_metadata) {
calld->original_recv_trailing_metadata_ready =
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready;
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&calld->recv_trailing_metadata_ready;
}
- grpc_call_next_op(elem, batch);
-}
-
-/* Constructor for call_data */
+ grpc_call_next_op(elem, batch);
+}
+
+/* Constructor for call_data */
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 */
+ 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*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->~call_data();
}
-
-/* Constructor for channel_data */
+
+/* Constructor for channel_data */
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);
- GPR_ASSERT(auth_context != nullptr);
- grpc_server_credentials* creds =
- grpc_find_server_credentials_in_args(args->channel_args);
+ GPR_ASSERT(!args->is_last);
+ grpc_auth_context* auth_context =
+ grpc_find_auth_context_in_args(args->channel_args);
+ GPR_ASSERT(auth_context != nullptr);
+ grpc_server_credentials* creds =
+ grpc_find_server_credentials_in_args(args->channel_args);
new (elem->channel_data) channel_data(auth_context, creds);
- return GRPC_ERROR_NONE;
-}
-
-/* Destructor for channel data */
+ return GRPC_ERROR_NONE;
+}
+
+/* Destructor for channel data */
static void server_auth_destroy_channel_elem(grpc_channel_element* elem) {
- channel_data* chand = static_cast<channel_data*>(elem->channel_data);
+ channel_data* chand = static_cast<channel_data*>(elem->channel_data);
chand->~channel_data();
-}
-
-const grpc_channel_filter grpc_server_auth_filter = {
+}
+
+const grpc_channel_filter grpc_server_auth_filter = {
server_auth_start_transport_stream_op_batch,
- grpc_channel_next_op,
- sizeof(call_data),
+ grpc_channel_next_op,
+ sizeof(call_data),
server_auth_init_call_elem,
- grpc_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
server_auth_destroy_call_elem,
- sizeof(channel_data),
+ sizeof(channel_data),
server_auth_init_channel_elem,
server_auth_destroy_channel_elem,
- grpc_channel_next_get_info,
- "server-auth"};
+ grpc_channel_next_get_info,
+ "server-auth"};
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.cc b/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.cc
index f78bb8df38f..0d95883cf9e 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.cc
+++ b/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.cc
@@ -1,29 +1,29 @@
-/*
- *
- * 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/security/transport/tsi_error.h"
-
-grpc_error* grpc_set_tsi_error_result(grpc_error* error, tsi_result result) {
- return grpc_error_set_int(
- grpc_error_set_str(
- error, GRPC_ERROR_STR_TSI_ERROR,
- grpc_slice_from_static_string(tsi_result_to_string(result))),
- GRPC_ERROR_INT_TSI_CODE, result);
-}
+/*
+ *
+ * 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/security/transport/tsi_error.h"
+
+grpc_error* grpc_set_tsi_error_result(grpc_error* error, tsi_result result) {
+ return grpc_error_set_int(
+ grpc_error_set_str(
+ error, GRPC_ERROR_STR_TSI_ERROR,
+ grpc_slice_from_static_string(tsi_result_to_string(result))),
+ GRPC_ERROR_INT_TSI_CODE, result);
+}
diff --git a/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.h b/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.h
index 16e04f70f1e..6e6b30e592e 100644
--- a/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.h
+++ b/contrib/libs/grpc/src/core/lib/security/transport/tsi_error.h
@@ -1,29 +1,29 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_TSI_ERROR_H
#define GRPC_CORE_LIB_SECURITY_TRANSPORT_TSI_ERROR_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/iomgr/error.h"
-#include "src/core/tsi/transport_security_interface.h"
+#include "src/core/tsi/transport_security_interface.h"
-grpc_error* grpc_set_tsi_error_result(grpc_error* error, tsi_result result);
+grpc_error* grpc_set_tsi_error_result(grpc_error* error, tsi_result result);
#endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_TSI_ERROR_H */
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 70ed064841a..9a39ffc6b5f 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.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 <string.h>
+
#include "y_absl/strings/str_cat.h"
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/security/util/json_util.h"
@@ -37,7 +37,7 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("JSON value is not an object");
}
return nullptr;
- }
+ }
auto it = json.object_value().find(prop_name);
if (it == json.object_value().end()) {
if (error != nullptr) {
@@ -45,8 +45,8 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json,
y_absl::StrCat("Property ", prop_name, " not found in JSON object.")
.c_str());
}
- return nullptr;
- }
+ return nullptr;
+ }
if (it->second.type() != grpc_core::Json::Type::STRING) {
if (error != nullptr) {
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
@@ -57,16 +57,16 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json,
return nullptr;
}
return it->second.string_value().c_str();
-}
-
+}
+
bool grpc_copy_json_string_property(const grpc_core::Json& json,
- const char* prop_name,
- char** copied_value) {
+ 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);
- if (prop_value == nullptr) return false;
- *copied_value = gpr_strdup(prop_value);
- return true;
-}
+ 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 42f7005e00e..7acfa85421d 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
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_UTIL_JSON_UTIL_H
#define GRPC_CORE_LIB_SECURITY_UTIL_JSON_UTIL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdbool.h>
#include "src/core/lib/iomgr/error.h"
@@ -39,6 +39,6 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json,
// Copies the value of the json child property specified by prop_name.
// Returns false if the property was not found.
bool grpc_copy_json_string_property(const grpc_core::Json& json,
- const char* prop_name, char** copied_value);
+ const char* prop_name, char** copied_value);
#endif /* GRPC_CORE_LIB_SECURITY_UTIL_JSON_UTIL_H */
diff --git a/contrib/libs/grpc/src/core/lib/slice/b64.cc b/contrib/libs/grpc/src/core/lib/slice/b64.cc
index 0a06a05c934..145a8604ccc 100644
--- a/contrib/libs/grpc/src/core/lib/slice/b64.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/b64.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/slice/b64.h"
-
-#include <stdint.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-/* --- Constants. --- */
-
-static const int8_t base64_bytes[] = {
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 0x3E, -1, -1, -1, 0x3F,
- 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, -1, -1,
- -1, 0x7F, -1, -1, -1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
- 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
- 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, -1, -1, -1, -1, -1,
- -1, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24,
- 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
- 0x31, 0x32, 0x33, -1, -1, -1, -1, -1};
-
-static const char base64_url_unsafe_chars[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-static const char base64_url_safe_chars[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
-
-#define GRPC_BASE64_PAD_CHAR '='
-#define GRPC_BASE64_PAD_BYTE 0x7F
-#define GRPC_BASE64_MULTILINE_LINE_LEN 76
-#define GRPC_BASE64_MULTILINE_NUM_BLOCKS (GRPC_BASE64_MULTILINE_LINE_LEN / 4)
-
-/* --- base64 functions. --- */
-
-char* grpc_base64_encode(const void* vdata, size_t data_size, int url_safe,
- int multiline) {
- size_t result_projected_size =
+/*
+ *
+ * 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/slice/b64.h"
+
+#include <stdint.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+/* --- Constants. --- */
+
+static const int8_t base64_bytes[] = {
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, 0x3E, -1, -1, -1, 0x3F,
+ 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, -1, -1,
+ -1, 0x7F, -1, -1, -1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
+ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
+ 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, -1, -1, -1, -1, -1,
+ -1, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24,
+ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
+ 0x31, 0x32, 0x33, -1, -1, -1, -1, -1};
+
+static const char base64_url_unsafe_chars[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static const char base64_url_safe_chars[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
+
+#define GRPC_BASE64_PAD_CHAR '='
+#define GRPC_BASE64_PAD_BYTE 0x7F
+#define GRPC_BASE64_MULTILINE_LINE_LEN 76
+#define GRPC_BASE64_MULTILINE_NUM_BLOCKS (GRPC_BASE64_MULTILINE_LINE_LEN / 4)
+
+/* --- base64 functions. --- */
+
+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);
- char* result = static_cast<char*>(gpr_malloc(result_projected_size));
- grpc_base64_encode_core(result, vdata, data_size, url_safe, multiline);
- return result;
-}
-
+ 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 result_projected_size =
- 4 * ((data_size + 3) / 3) +
- 2 * (multiline ? (data_size / (3 * GRPC_BASE64_MULTILINE_NUM_BLOCKS))
- : 0) +
- 1;
- return result_projected_size;
-}
-
-void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size,
- int url_safe, int multiline) {
- const unsigned char* data = static_cast<const unsigned char*>(vdata);
- const char* base64_chars =
- url_safe ? base64_url_safe_chars : base64_url_unsafe_chars;
- const size_t result_projected_size =
+ size_t result_projected_size =
+ 4 * ((data_size + 3) / 3) +
+ 2 * (multiline ? (data_size / (3 * GRPC_BASE64_MULTILINE_NUM_BLOCKS))
+ : 0) +
+ 1;
+ return result_projected_size;
+}
+
+void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size,
+ int url_safe, int multiline) {
+ const unsigned char* data = static_cast<const unsigned char*>(vdata);
+ 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);
-
- char* current = result;
- size_t num_blocks = 0;
- size_t i = 0;
-
- /* Encode each block. */
- while (data_size >= 3) {
- *current++ = base64_chars[(data[i] >> 2) & 0x3F];
- *current++ =
- base64_chars[((data[i] & 0x03) << 4) | ((data[i + 1] >> 4) & 0x0F)];
- *current++ =
- base64_chars[((data[i + 1] & 0x0F) << 2) | ((data[i + 2] >> 6) & 0x03)];
- *current++ = base64_chars[data[i + 2] & 0x3F];
-
- data_size -= 3;
- i += 3;
- if (multiline && (++num_blocks == GRPC_BASE64_MULTILINE_NUM_BLOCKS)) {
- *current++ = '\r';
- *current++ = '\n';
- num_blocks = 0;
- }
- }
-
- /* Take care of the tail. */
- if (data_size == 2) {
- *current++ = base64_chars[(data[i] >> 2) & 0x3F];
- *current++ =
- base64_chars[((data[i] & 0x03) << 4) | ((data[i + 1] >> 4) & 0x0F)];
- *current++ = base64_chars[(data[i + 1] & 0x0F) << 2];
- *current++ = GRPC_BASE64_PAD_CHAR;
- } else if (data_size == 1) {
- *current++ = base64_chars[(data[i] >> 2) & 0x3F];
- *current++ = base64_chars[(data[i] & 0x03) << 4];
- *current++ = GRPC_BASE64_PAD_CHAR;
- *current++ = GRPC_BASE64_PAD_CHAR;
- }
-
- GPR_ASSERT(current >= result);
- GPR_ASSERT((uintptr_t)(current - result) < result_projected_size);
- result[current - result] = '\0';
-}
-
-grpc_slice grpc_base64_decode(const char* b64, int url_safe) {
- return grpc_base64_decode_with_len(b64, strlen(b64), url_safe);
-}
-
-static void decode_one_char(const unsigned char* codes, unsigned char* result,
- size_t* result_offset) {
- uint32_t packed = (static_cast<uint32_t>(codes[0]) << 2) |
- (static_cast<uint32_t>(codes[1]) >> 4);
- result[(*result_offset)++] = static_cast<unsigned char>(packed);
-}
-
-static void decode_two_chars(const unsigned char* codes, unsigned char* result,
- size_t* result_offset) {
- uint32_t packed = (static_cast<uint32_t>(codes[0]) << 10) |
- (static_cast<uint32_t>(codes[1]) << 4) |
- (static_cast<uint32_t>(codes[2]) >> 2);
- result[(*result_offset)++] = static_cast<unsigned char>(packed >> 8);
- result[(*result_offset)++] = static_cast<unsigned char>(packed);
-}
-
-static int decode_group(const unsigned char* codes, size_t num_codes,
- unsigned char* result, size_t* result_offset) {
- GPR_ASSERT(num_codes <= 4);
-
- /* Short end groups that may not have padding. */
- if (num_codes == 1) {
- gpr_log(GPR_ERROR, "Invalid group. Must be at least 2 bytes.");
- return 0;
- }
- if (num_codes == 2) {
- decode_one_char(codes, result, result_offset);
- return 1;
- }
- if (num_codes == 3) {
- decode_two_chars(codes, result, result_offset);
- return 1;
- }
-
- /* Regular 4 byte groups with padding or not. */
- GPR_ASSERT(num_codes == 4);
- if (codes[0] == GRPC_BASE64_PAD_BYTE || codes[1] == GRPC_BASE64_PAD_BYTE) {
- gpr_log(GPR_ERROR, "Invalid padding detected.");
- return 0;
- }
- if (codes[2] == GRPC_BASE64_PAD_BYTE) {
- if (codes[3] == GRPC_BASE64_PAD_BYTE) {
- decode_one_char(codes, result, result_offset);
- } else {
- gpr_log(GPR_ERROR, "Invalid padding detected.");
- return 0;
- }
- } else if (codes[3] == GRPC_BASE64_PAD_BYTE) {
- decode_two_chars(codes, result, result_offset);
- } else {
- /* No padding. */
- uint32_t packed = (static_cast<uint32_t>(codes[0]) << 18) |
- (static_cast<uint32_t>(codes[1]) << 12) |
- (static_cast<uint32_t>(codes[2]) << 6) | codes[3];
- result[(*result_offset)++] = static_cast<unsigned char>(packed >> 16);
- result[(*result_offset)++] = static_cast<unsigned char>(packed >> 8);
- result[(*result_offset)++] = static_cast<unsigned char>(packed);
- }
- return 1;
-}
-
-grpc_slice grpc_base64_decode_with_len(const char* b64, size_t b64_len,
- int url_safe) {
- grpc_slice result = GRPC_SLICE_MALLOC(b64_len);
- unsigned char* current = GRPC_SLICE_START_PTR(result);
- size_t result_size = 0;
- unsigned char codes[4];
- size_t num_codes = 0;
-
- while (b64_len--) {
- unsigned char c = static_cast<unsigned char>(*b64++);
- signed char code;
- if (c >= GPR_ARRAY_SIZE(base64_bytes)) continue;
- if (url_safe) {
- if (c == '+' || c == '/') {
- gpr_log(GPR_ERROR, "Invalid character for url safe base64 %c", c);
- goto fail;
- }
- if (c == '-') {
- c = '+';
- } else if (c == '_') {
- c = '/';
- }
- }
- code = base64_bytes[c];
- if (code == -1) {
- if (c != '\r' && c != '\n') {
- gpr_log(GPR_ERROR, "Invalid character %c", c);
- goto fail;
- }
- } else {
- codes[num_codes++] = static_cast<unsigned char>(code);
- if (num_codes == 4) {
- if (!decode_group(codes, num_codes, current, &result_size)) goto fail;
- num_codes = 0;
- }
- }
- }
-
- if (num_codes != 0 &&
- !decode_group(codes, num_codes, current, &result_size)) {
- goto fail;
- }
- GRPC_SLICE_SET_LENGTH(result, result_size);
- return result;
-
-fail:
- grpc_slice_unref_internal(result);
- return grpc_empty_slice();
-}
+
+ char* current = result;
+ size_t num_blocks = 0;
+ size_t i = 0;
+
+ /* Encode each block. */
+ while (data_size >= 3) {
+ *current++ = base64_chars[(data[i] >> 2) & 0x3F];
+ *current++ =
+ base64_chars[((data[i] & 0x03) << 4) | ((data[i + 1] >> 4) & 0x0F)];
+ *current++ =
+ base64_chars[((data[i + 1] & 0x0F) << 2) | ((data[i + 2] >> 6) & 0x03)];
+ *current++ = base64_chars[data[i + 2] & 0x3F];
+
+ data_size -= 3;
+ i += 3;
+ if (multiline && (++num_blocks == GRPC_BASE64_MULTILINE_NUM_BLOCKS)) {
+ *current++ = '\r';
+ *current++ = '\n';
+ num_blocks = 0;
+ }
+ }
+
+ /* Take care of the tail. */
+ if (data_size == 2) {
+ *current++ = base64_chars[(data[i] >> 2) & 0x3F];
+ *current++ =
+ base64_chars[((data[i] & 0x03) << 4) | ((data[i + 1] >> 4) & 0x0F)];
+ *current++ = base64_chars[(data[i + 1] & 0x0F) << 2];
+ *current++ = GRPC_BASE64_PAD_CHAR;
+ } else if (data_size == 1) {
+ *current++ = base64_chars[(data[i] >> 2) & 0x3F];
+ *current++ = base64_chars[(data[i] & 0x03) << 4];
+ *current++ = GRPC_BASE64_PAD_CHAR;
+ *current++ = GRPC_BASE64_PAD_CHAR;
+ }
+
+ GPR_ASSERT(current >= result);
+ GPR_ASSERT((uintptr_t)(current - result) < result_projected_size);
+ result[current - result] = '\0';
+}
+
+grpc_slice grpc_base64_decode(const char* b64, int url_safe) {
+ return grpc_base64_decode_with_len(b64, strlen(b64), url_safe);
+}
+
+static void decode_one_char(const unsigned char* codes, unsigned char* result,
+ size_t* result_offset) {
+ uint32_t packed = (static_cast<uint32_t>(codes[0]) << 2) |
+ (static_cast<uint32_t>(codes[1]) >> 4);
+ result[(*result_offset)++] = static_cast<unsigned char>(packed);
+}
+
+static void decode_two_chars(const unsigned char* codes, unsigned char* result,
+ size_t* result_offset) {
+ uint32_t packed = (static_cast<uint32_t>(codes[0]) << 10) |
+ (static_cast<uint32_t>(codes[1]) << 4) |
+ (static_cast<uint32_t>(codes[2]) >> 2);
+ result[(*result_offset)++] = static_cast<unsigned char>(packed >> 8);
+ result[(*result_offset)++] = static_cast<unsigned char>(packed);
+}
+
+static int decode_group(const unsigned char* codes, size_t num_codes,
+ unsigned char* result, size_t* result_offset) {
+ GPR_ASSERT(num_codes <= 4);
+
+ /* Short end groups that may not have padding. */
+ if (num_codes == 1) {
+ gpr_log(GPR_ERROR, "Invalid group. Must be at least 2 bytes.");
+ return 0;
+ }
+ if (num_codes == 2) {
+ decode_one_char(codes, result, result_offset);
+ return 1;
+ }
+ if (num_codes == 3) {
+ decode_two_chars(codes, result, result_offset);
+ return 1;
+ }
+
+ /* Regular 4 byte groups with padding or not. */
+ GPR_ASSERT(num_codes == 4);
+ if (codes[0] == GRPC_BASE64_PAD_BYTE || codes[1] == GRPC_BASE64_PAD_BYTE) {
+ gpr_log(GPR_ERROR, "Invalid padding detected.");
+ return 0;
+ }
+ if (codes[2] == GRPC_BASE64_PAD_BYTE) {
+ if (codes[3] == GRPC_BASE64_PAD_BYTE) {
+ decode_one_char(codes, result, result_offset);
+ } else {
+ gpr_log(GPR_ERROR, "Invalid padding detected.");
+ return 0;
+ }
+ } else if (codes[3] == GRPC_BASE64_PAD_BYTE) {
+ decode_two_chars(codes, result, result_offset);
+ } else {
+ /* No padding. */
+ uint32_t packed = (static_cast<uint32_t>(codes[0]) << 18) |
+ (static_cast<uint32_t>(codes[1]) << 12) |
+ (static_cast<uint32_t>(codes[2]) << 6) | codes[3];
+ result[(*result_offset)++] = static_cast<unsigned char>(packed >> 16);
+ result[(*result_offset)++] = static_cast<unsigned char>(packed >> 8);
+ result[(*result_offset)++] = static_cast<unsigned char>(packed);
+ }
+ return 1;
+}
+
+grpc_slice grpc_base64_decode_with_len(const char* b64, size_t b64_len,
+ int url_safe) {
+ grpc_slice result = GRPC_SLICE_MALLOC(b64_len);
+ unsigned char* current = GRPC_SLICE_START_PTR(result);
+ size_t result_size = 0;
+ unsigned char codes[4];
+ size_t num_codes = 0;
+
+ while (b64_len--) {
+ unsigned char c = static_cast<unsigned char>(*b64++);
+ signed char code;
+ if (c >= GPR_ARRAY_SIZE(base64_bytes)) continue;
+ if (url_safe) {
+ if (c == '+' || c == '/') {
+ gpr_log(GPR_ERROR, "Invalid character for url safe base64 %c", c);
+ goto fail;
+ }
+ if (c == '-') {
+ c = '+';
+ } else if (c == '_') {
+ c = '/';
+ }
+ }
+ code = base64_bytes[c];
+ if (code == -1) {
+ if (c != '\r' && c != '\n') {
+ gpr_log(GPR_ERROR, "Invalid character %c", c);
+ goto fail;
+ }
+ } else {
+ codes[num_codes++] = static_cast<unsigned char>(code);
+ if (num_codes == 4) {
+ if (!decode_group(codes, num_codes, current, &result_size)) goto fail;
+ num_codes = 0;
+ }
+ }
+ }
+
+ if (num_codes != 0 &&
+ !decode_group(codes, num_codes, current, &result_size)) {
+ goto fail;
+ }
+ GRPC_SLICE_SET_LENGTH(result, result_size);
+ return result;
+
+fail:
+ grpc_slice_unref_internal(result);
+ return grpc_empty_slice();
+}
diff --git a/contrib/libs/grpc/src/core/lib/slice/b64.h b/contrib/libs/grpc/src/core/lib/slice/b64.h
index 65ba6622b20..11a8162d11e 100644
--- a/contrib/libs/grpc/src/core/lib/slice/b64.h
+++ b/contrib/libs/grpc/src/core/lib/slice/b64.h
@@ -1,50 +1,50 @@
-/*
- *
- * 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_SLICE_B64_H
-#define GRPC_CORE_LIB_SLICE_B64_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.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_SLICE_B64_H
+#define GRPC_CORE_LIB_SLICE_B64_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice.h>
+
/* 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,
- int multiline);
-
-/* 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. */
+ 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,
+ int multiline);
+
+/* 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);
-
-/* Encodes data using base64 and write it to memory pointed to by result. It is
+
+/* 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
- * encoded data. */
-void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size,
- int url_safe, int multiline);
-
-/* Decodes data according to the base64 specification. Returns an empty
- slice in case of failure. */
-grpc_slice grpc_base64_decode(const char* b64, int url_safe);
-
-/* Same as above except that the length is provided by the caller. */
-grpc_slice grpc_base64_decode_with_len(const char* b64, size_t b64_len,
- int url_safe);
-
-#endif /* GRPC_CORE_LIB_SLICE_B64_H */
+ * encoded data. */
+void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size,
+ int url_safe, int multiline);
+
+/* Decodes data according to the base64 specification. Returns an empty
+ slice in case of failure. */
+grpc_slice grpc_base64_decode(const char* b64, int url_safe);
+
+/* Same as above except that the length is provided by the caller. */
+grpc_slice grpc_base64_decode_with_len(const char* b64, size_t b64_len,
+ int url_safe);
+
+#endif /* GRPC_CORE_LIB_SLICE_B64_H */
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 79a4805bc91..9fdb056d0fc 100644
--- a/contrib/libs/grpc/src/core/lib/slice/percent_encoding.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/percent_encoding.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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/slice/percent_encoding.h"
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/slice/slice_internal.h"
-
-const uint8_t grpc_url_percent_encoding_unreserved_bytes[256 / 8] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xff, 0x03, 0xfe, 0xff, 0xff,
- 0x87, 0xfe, 0xff, 0xff, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-const uint8_t grpc_compatible_percent_encoding_unreserved_bytes[256 / 8] = {
- 0x00, 0x00, 0x00, 0x00, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
-static bool is_unreserved_character(uint8_t c,
- const uint8_t* unreserved_bytes) {
- return ((unreserved_bytes[c / 8] >> (c % 8)) & 1) != 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 <grpc/support/port_platform.h>
+
+#include "src/core/lib/slice/percent_encoding.h"
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/slice/slice_internal.h"
+
+const uint8_t grpc_url_percent_encoding_unreserved_bytes[256 / 8] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xff, 0x03, 0xfe, 0xff, 0xff,
+ 0x87, 0xfe, 0xff, 0xff, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t grpc_compatible_percent_encoding_unreserved_bytes[256 / 8] = {
+ 0x00, 0x00, 0x00, 0x00, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+static bool is_unreserved_character(uint8_t c,
+ const uint8_t* unreserved_bytes) {
+ return ((unreserved_bytes[c / 8] >> (c % 8)) & 1) != 0;
+}
+
grpc_slice grpc_percent_encode_slice(const grpc_slice& slice,
- const uint8_t* unreserved_bytes) {
- static const uint8_t hex[] = "0123456789ABCDEF";
-
- // first pass: count the number of bytes needed to output this string
- size_t output_length = 0;
- const uint8_t* slice_start = GRPC_SLICE_START_PTR(slice);
- const uint8_t* slice_end = GRPC_SLICE_END_PTR(slice);
- const uint8_t* p;
- bool any_reserved_bytes = false;
- for (p = slice_start; p < slice_end; p++) {
- bool unres = is_unreserved_character(*p, unreserved_bytes);
- output_length += unres ? 1 : 3;
- any_reserved_bytes |= !unres;
- }
- // no unreserved bytes: return the string unmodified
- if (!any_reserved_bytes) {
- return grpc_slice_ref_internal(slice);
- }
- // second pass: actually encode
- grpc_slice out = GRPC_SLICE_MALLOC(output_length);
- uint8_t* q = GRPC_SLICE_START_PTR(out);
- for (p = slice_start; p < slice_end; p++) {
- if (is_unreserved_character(*p, unreserved_bytes)) {
- *q++ = *p;
- } else {
- *q++ = '%';
- *q++ = hex[*p >> 4];
- *q++ = hex[*p & 15];
- }
- }
- GPR_ASSERT(q == GRPC_SLICE_END_PTR(out));
- return out;
-}
-
-static bool valid_hex(const uint8_t* p, const uint8_t* end) {
- if (p >= end) return false;
- return (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') ||
- (*p >= 'A' && *p <= 'F');
-}
-
-static uint8_t dehex(uint8_t c) {
- if (c >= '0' && c <= '9') return static_cast<uint8_t>(c - '0');
- if (c >= 'A' && c <= 'F') return static_cast<uint8_t>(c - 'A' + 10);
- if (c >= 'a' && c <= 'f') return static_cast<uint8_t>(c - 'a' + 10);
- GPR_UNREACHABLE_CODE(return 255);
-}
-
+ const uint8_t* unreserved_bytes) {
+ static const uint8_t hex[] = "0123456789ABCDEF";
+
+ // first pass: count the number of bytes needed to output this string
+ size_t output_length = 0;
+ const uint8_t* slice_start = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* slice_end = GRPC_SLICE_END_PTR(slice);
+ const uint8_t* p;
+ bool any_reserved_bytes = false;
+ for (p = slice_start; p < slice_end; p++) {
+ bool unres = is_unreserved_character(*p, unreserved_bytes);
+ output_length += unres ? 1 : 3;
+ any_reserved_bytes |= !unres;
+ }
+ // no unreserved bytes: return the string unmodified
+ if (!any_reserved_bytes) {
+ return grpc_slice_ref_internal(slice);
+ }
+ // second pass: actually encode
+ grpc_slice out = GRPC_SLICE_MALLOC(output_length);
+ uint8_t* q = GRPC_SLICE_START_PTR(out);
+ for (p = slice_start; p < slice_end; p++) {
+ if (is_unreserved_character(*p, unreserved_bytes)) {
+ *q++ = *p;
+ } else {
+ *q++ = '%';
+ *q++ = hex[*p >> 4];
+ *q++ = hex[*p & 15];
+ }
+ }
+ GPR_ASSERT(q == GRPC_SLICE_END_PTR(out));
+ return out;
+}
+
+static bool valid_hex(const uint8_t* p, const uint8_t* end) {
+ if (p >= end) return false;
+ return (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') ||
+ (*p >= 'A' && *p <= 'F');
+}
+
+static uint8_t dehex(uint8_t c) {
+ if (c >= '0' && c <= '9') return static_cast<uint8_t>(c - '0');
+ if (c >= 'A' && c <= 'F') return static_cast<uint8_t>(c - 'A' + 10);
+ if (c >= 'a' && c <= 'f') return static_cast<uint8_t>(c - 'a' + 10);
+ GPR_UNREACHABLE_CODE(return 255);
+}
+
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);
- const uint8_t* in_end = GRPC_SLICE_END_PTR(slice_in);
- size_t out_length = 0;
- bool any_percent_encoded_stuff = false;
- while (p != in_end) {
- if (*p == '%') {
- if (!valid_hex(++p, in_end)) return false;
- if (!valid_hex(++p, in_end)) return false;
- p++;
- out_length++;
- any_percent_encoded_stuff = true;
- } else if (is_unreserved_character(*p, unreserved_bytes)) {
- p++;
- out_length++;
- } else {
- return false;
- }
- }
- if (!any_percent_encoded_stuff) {
- *slice_out = grpc_slice_ref_internal(slice_in);
- return true;
- }
- p = GRPC_SLICE_START_PTR(slice_in);
- *slice_out = GRPC_SLICE_MALLOC(out_length);
- uint8_t* q = GRPC_SLICE_START_PTR(*slice_out);
- while (p != in_end) {
- if (*p == '%') {
- *q++ = static_cast<uint8_t>(dehex(p[1]) << 4) | (dehex(p[2]));
- p += 3;
- } else {
- *q++ = *p++;
- }
- }
- GPR_ASSERT(q == GRPC_SLICE_END_PTR(*slice_out));
- return true;
-}
-
+ const uint8_t* unreserved_bytes,
+ grpc_slice* slice_out) {
+ 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;
+ bool any_percent_encoded_stuff = false;
+ while (p != in_end) {
+ if (*p == '%') {
+ if (!valid_hex(++p, in_end)) return false;
+ if (!valid_hex(++p, in_end)) return false;
+ p++;
+ out_length++;
+ any_percent_encoded_stuff = true;
+ } else if (is_unreserved_character(*p, unreserved_bytes)) {
+ p++;
+ out_length++;
+ } else {
+ return false;
+ }
+ }
+ if (!any_percent_encoded_stuff) {
+ *slice_out = grpc_slice_ref_internal(slice_in);
+ return true;
+ }
+ p = GRPC_SLICE_START_PTR(slice_in);
+ *slice_out = GRPC_SLICE_MALLOC(out_length);
+ uint8_t* q = GRPC_SLICE_START_PTR(*slice_out);
+ while (p != in_end) {
+ if (*p == '%') {
+ *q++ = static_cast<uint8_t>(dehex(p[1]) << 4) | (dehex(p[2]));
+ p += 3;
+ } else {
+ *q++ = *p++;
+ }
+ }
+ GPR_ASSERT(q == GRPC_SLICE_END_PTR(*slice_out));
+ return true;
+}
+
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;
- bool any_percent_encoded_stuff = false;
- while (p != in_end) {
- if (*p == '%') {
- if (!valid_hex(p + 1, in_end) || !valid_hex(p + 2, in_end)) {
- p++;
- out_length++;
- } else {
- p += 3;
- out_length++;
- any_percent_encoded_stuff = true;
- }
- } else {
- p++;
- out_length++;
- }
- }
- if (!any_percent_encoded_stuff) {
- return grpc_slice_ref_internal(slice_in);
- }
- p = GRPC_SLICE_START_PTR(slice_in);
- grpc_slice out = GRPC_SLICE_MALLOC(out_length);
- uint8_t* q = GRPC_SLICE_START_PTR(out);
- while (p != in_end) {
- if (*p == '%') {
- if (!valid_hex(p + 1, in_end) || !valid_hex(p + 2, in_end)) {
- *q++ = *p++;
- } else {
- *q++ = static_cast<uint8_t>(dehex(p[1]) << 4) | (dehex(p[2]));
- p += 3;
- }
- } else {
- *q++ = *p++;
- }
- }
- GPR_ASSERT(q == GRPC_SLICE_END_PTR(out));
- return out;
-}
+ 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;
+ bool any_percent_encoded_stuff = false;
+ while (p != in_end) {
+ if (*p == '%') {
+ if (!valid_hex(p + 1, in_end) || !valid_hex(p + 2, in_end)) {
+ p++;
+ out_length++;
+ } else {
+ p += 3;
+ out_length++;
+ any_percent_encoded_stuff = true;
+ }
+ } else {
+ p++;
+ out_length++;
+ }
+ }
+ if (!any_percent_encoded_stuff) {
+ return grpc_slice_ref_internal(slice_in);
+ }
+ p = GRPC_SLICE_START_PTR(slice_in);
+ grpc_slice out = GRPC_SLICE_MALLOC(out_length);
+ uint8_t* q = GRPC_SLICE_START_PTR(out);
+ while (p != in_end) {
+ if (*p == '%') {
+ if (!valid_hex(p + 1, in_end) || !valid_hex(p + 2, in_end)) {
+ *q++ = *p++;
+ } else {
+ *q++ = static_cast<uint8_t>(dehex(p[1]) << 4) | (dehex(p[2]));
+ p += 3;
+ }
+ } else {
+ *q++ = *p++;
+ }
+ }
+ GPR_ASSERT(q == GRPC_SLICE_END_PTR(out));
+ return out;
+}
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 43b20f090f0..37b0e679679 100644
--- a/contrib/libs/grpc/src/core/lib/slice/percent_encoding.h
+++ b/contrib/libs/grpc/src/core/lib/slice/percent_encoding.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -26,8 +26,8 @@
and another which applies percent encoding only to non-http2 header
bytes (the 'compatible' variant) */
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdbool.h>
#include <grpc/slice.h>
@@ -47,7 +47,7 @@ extern const uint8_t grpc_compatible_percent_encoding_unreserved_bytes[256 / 8];
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,
- const uint8_t* unreserved_bytes);
+ const uint8_t* unreserved_bytes);
/* Percent-decode a slice, strictly.
If the input is legal (contains no unreserved bytes, and legal % encodings),
returns true and sets *slice_out to the decoded slice.
@@ -55,8 +55,8 @@ grpc_slice grpc_percent_encode_slice(const grpc_slice& slice,
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,
- const uint8_t* unreserved_bytes,
- grpc_slice* slice_out);
+ 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. */
diff --git a/contrib/libs/grpc/src/core/lib/slice/slice.cc b/contrib/libs/grpc/src/core/lib/slice/slice.cc
index 838cf4ba498..92241e851fc 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/slice.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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/slice/slice_internal.h"
-
-#include <grpc/slice.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.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/lib/slice/slice_internal.h"
+
+#include <grpc/slice.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include <string.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) {
- char* out = static_cast<char*>(gpr_malloc(GRPC_SLICE_LENGTH(slice) + 1));
- memcpy(out, GRPC_SLICE_START_PTR(slice), GRPC_SLICE_LENGTH(slice));
- out[GRPC_SLICE_LENGTH(slice)] = 0;
- return out;
-}
-
+#include "src/core/lib/iomgr/exec_ctx.h"
+
+char* grpc_slice_to_c_string(grpc_slice slice) {
+ char* out = static_cast<char*>(gpr_malloc(GRPC_SLICE_LENGTH(slice) + 1));
+ memcpy(out, GRPC_SLICE_START_PTR(slice), GRPC_SLICE_LENGTH(slice));
+ out[GRPC_SLICE_LENGTH(slice)] = 0;
+ return out;
+}
+
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));
- memcpy(GRPC_SLICE_START_PTR(out), GRPC_SLICE_START_PTR(s),
- GRPC_SLICE_LENGTH(s));
- return out;
-}
-
-/* Public API */
-grpc_slice grpc_slice_ref(grpc_slice slice) {
- return grpc_slice_ref_internal(slice);
-}
-
-/* Public API */
-void grpc_slice_unref(grpc_slice slice) {
- if (grpc_core::ExecCtx::Get() == nullptr) {
- grpc_core::ExecCtx exec_ctx;
- grpc_slice_unref_internal(slice);
- } else {
- grpc_slice_unref_internal(slice);
- }
-}
-
+
+grpc_slice grpc_slice_copy(grpc_slice s) {
+ grpc_slice out = GRPC_SLICE_MALLOC(GRPC_SLICE_LENGTH(s));
+ memcpy(GRPC_SLICE_START_PTR(out), GRPC_SLICE_START_PTR(s),
+ GRPC_SLICE_LENGTH(s));
+ return out;
+}
+
+/* Public API */
+grpc_slice grpc_slice_ref(grpc_slice slice) {
+ return grpc_slice_ref_internal(slice);
+}
+
+/* Public API */
+void grpc_slice_unref(grpc_slice slice) {
+ if (grpc_core::ExecCtx::Get() == nullptr) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_slice_unref_internal(slice);
+ } else {
+ grpc_slice_unref_internal(slice);
+ }
+}
+
namespace grpc_core {
-/* grpc_slice_from_static_string support structure - a refcount that does
- nothing */
+/* 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_),
@@ -101,39 +101,39 @@ size_t grpc_slice_memory_usage(grpc_slice s) {
}
}
-grpc_slice grpc_slice_from_static_buffer(const void* s, size_t len) {
+grpc_slice grpc_slice_from_static_buffer(const void* s, size_t len) {
return grpc_core::ExternallyManagedSlice(s, len);
-}
-
-grpc_slice grpc_slice_from_static_string(const char* s) {
+}
+
+grpc_slice grpc_slice_from_static_string(const char* 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;
+}
+
+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.data.refcounted.bytes = static_cast<uint8_t*>(p);
- slice.data.refcounted.length = len;
- return slice;
-}
-
-grpc_slice grpc_slice_new(void* p, size_t len, void (*destroy)(void*)) {
- /* Pass "p" to *destroy when the slice is no longer needed. */
- return grpc_slice_new_with_user_data(p, len, destroy, p);
-}
-
+ slice.data.refcounted.bytes = static_cast<uint8_t*>(p);
+ slice.data.refcounted.length = len;
+ return slice;
+}
+
+grpc_slice grpc_slice_new(void* p, size_t len, void (*destroy)(void*)) {
+ /* Pass "p" to *destroy when the slice is no longer needed. */
+ return grpc_slice_new_with_user_data(p, len, destroy, p);
+}
+
namespace grpc_core {
-/* grpc_slice_new_with_len support structures - we create a refcount object
- extended with the user provided data pointer & destroy function */
+/* 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,
@@ -142,7 +142,7 @@ class NewWithLenSliceRefcount {
user_length_(user_length),
user_destroy_(destroy) {}
~NewWithLenSliceRefcount() { user_destroy_(user_data_, user_length_); }
-
+
grpc_slice_refcount* base_refcount() { return &base_; }
private:
@@ -166,13 +166,13 @@ class MovedStringSliceRefCount {
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_from_cpp_string() ref count.
class MovedCppStringSliceRefCount {
public:
@@ -195,16 +195,16 @@ class MovedCppStringSliceRefCount {
} // namespace grpc_core
-grpc_slice grpc_slice_new_with_len(void* p, size_t len,
- void (*destroy)(void*, size_t)) {
- grpc_slice slice;
+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.data.refcounted.bytes = static_cast<uint8_t*>(p);
- slice.data.refcounted.length = len;
- return slice;
-}
-
+ 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)) {
@@ -222,14 +222,14 @@ 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) {
+grpc_slice grpc_slice_from_copied_buffer(const char* source, size_t length) {
return grpc_core::UnmanagedMemorySlice(source, length);
-}
-
-grpc_slice grpc_slice_from_copied_string(const char* source) {
+}
+
+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());
@@ -246,12 +246,12 @@ grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p,
}
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) {
grpc_slice slice;
if (str.size() <= sizeof(slice.data.inlined.bytes)) {
@@ -276,14 +276,14 @@ class MallocRefCount {
static void Destroy(void* arg) {
MallocRefCount* r = static_cast<MallocRefCount*>(arg);
r->~MallocRefCount();
- gpr_free(r);
- }
-
+ gpr_free(r);
+ }
+
MallocRefCount()
: base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
&base_) {}
~MallocRefCount() = default;
-
+
grpc_slice_refcount* base_refcount() { return &base_; }
private:
@@ -293,77 +293,77 @@ class MallocRefCount {
} // namespace
-grpc_slice grpc_slice_malloc_large(size_t length) {
+grpc_slice grpc_slice_malloc_large(size_t length) {
return grpc_core::UnmanagedMemorySlice(
length, grpc_core::UnmanagedMemorySlice::ForceHeapAllocation());
}
-
+
void grpc_core::UnmanagedMemorySlice::HeapInit(size_t length) {
- /* Memory layout used by the slice created here:
-
- +-----------+----------------------------------------------------------+
- | refcount | bytes |
- +-----------+----------------------------------------------------------+
-
- 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 */
+ /* Memory layout used by the slice created here:
+
+ +-----------+----------------------------------------------------------+
+ | refcount | bytes |
+ +-----------+----------------------------------------------------------+
+
+ 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));
-
- /* Initial refcount on rc is 1 - and it's up to the caller to release
- this reference. */
+
+ /* Initial refcount on rc is 1 - and it's up to the caller to release
+ this reference. */
new (rc) MallocRefCount();
-
- /* Build up the slice to be returned. */
- /* The slices refcount points back to the allocated block. */
+
+ /* Build up the slice to be returned. */
+ /* The slices refcount points back to the allocated block. */
refcount = rc->base_refcount();
- /* The data bytes are placed immediately after the refcount struct */
+ /* The data bytes are placed immediately after the refcount struct */
data.refcounted.bytes = reinterpret_cast<uint8_t*>(rc + 1);
- /* And the length of the block is set to the requested length */
+ /* And the length of the block is set to the requested length */
data.refcounted.length = length;
-}
-
-grpc_slice grpc_slice_malloc(size_t length) {
+}
+
+grpc_slice grpc_slice_malloc(size_t length) {
return grpc_core::UnmanagedMemorySlice(length);
}
-
+
grpc_core::UnmanagedMemorySlice::UnmanagedMemorySlice(size_t length) {
if (length > sizeof(data.inlined.bytes)) {
HeapInit(length);
- } else {
- /* small slice: just inline the data */
+ } else {
+ /* small slice: just inline the data */
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;
-
- GPR_ASSERT(end >= begin);
-
- if (source.refcount) {
- /* Enforce preconditions */
- GPR_ASSERT(source.data.refcounted.length >= end);
-
- /* Build the result */
+
+ GPR_ASSERT(end >= begin);
+
+ if (source.refcount) {
+ /* Enforce preconditions */
+ GPR_ASSERT(source.data.refcounted.length >= end);
+
+ /* Build the result */
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;
- } else {
- /* Enforce preconditions */
- GPR_ASSERT(source.data.inlined.length >= end);
- subset.refcount = nullptr;
- subset.data.inlined.length = static_cast<uint8_t>(end - begin);
- memcpy(subset.data.inlined.bytes, source.data.inlined.bytes + begin,
- end - begin);
- }
- return subset;
-}
-
+ /* Point into the source array */
+ subset.data.refcounted.bytes = source.data.refcounted.bytes + begin;
+ subset.data.refcounted.length = end - begin;
+ } else {
+ /* Enforce preconditions */
+ GPR_ASSERT(source.data.inlined.length >= end);
+ subset.refcount = nullptr;
+ subset.data.inlined.length = static_cast<uint8_t>(end - begin);
+ memcpy(subset.data.inlined.bytes, source.data.inlined.bytes + begin,
+ end - begin);
+ }
+ 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);
}
@@ -373,133 +373,133 @@ grpc_core::UnmanagedMemorySlice grpc_slice_sub_no_ref(
return sub_no_ref(source, begin, end);
}
-grpc_slice grpc_slice_sub(grpc_slice source, size_t begin, size_t end) {
- grpc_slice subset;
-
- if (end - begin <= sizeof(subset.data.inlined.bytes)) {
- subset.refcount = nullptr;
- subset.data.inlined.length = static_cast<uint8_t>(end - begin);
- memcpy(subset.data.inlined.bytes, GRPC_SLICE_START_PTR(source) + begin,
- end - begin);
- } else {
- subset = grpc_slice_sub_no_ref(source, begin, end);
- /* Bump the refcount */
+grpc_slice grpc_slice_sub(grpc_slice source, size_t begin, size_t end) {
+ grpc_slice subset;
+
+ if (end - begin <= sizeof(subset.data.inlined.bytes)) {
+ subset.refcount = nullptr;
+ subset.data.inlined.length = static_cast<uint8_t>(end - begin);
+ memcpy(subset.data.inlined.bytes, GRPC_SLICE_START_PTR(source) + begin,
+ end - begin);
+ } else {
+ subset = grpc_slice_sub_no_ref(source, begin, end);
+ /* Bump the refcount */
subset.refcount->Ref();
- }
- return subset;
-}
-
-grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice* source, size_t split,
- grpc_slice_ref_whom ref_whom) {
- grpc_slice tail;
-
- if (source->refcount == nullptr) {
- /* inlined data, copy it out */
- GPR_ASSERT(source->data.inlined.length >= split);
- tail.refcount = nullptr;
- tail.data.inlined.length =
- static_cast<uint8_t>(source->data.inlined.length - split);
- memcpy(tail.data.inlined.bytes, source->data.inlined.bytes + split,
- tail.data.inlined.length);
- source->data.inlined.length = static_cast<uint8_t>(split);
- } else {
- size_t tail_length = source->data.refcounted.length - split;
- GPR_ASSERT(source->data.refcounted.length >= split);
- if (tail_length < sizeof(tail.data.inlined.bytes) &&
- ref_whom != GRPC_SLICE_REF_TAIL) {
- /* Copy out the bytes - it'll be cheaper than refcounting */
- tail.refcount = nullptr;
- tail.data.inlined.length = static_cast<uint8_t>(tail_length);
- memcpy(tail.data.inlined.bytes, source->data.refcounted.bytes + split,
- tail_length);
+ }
+ return subset;
+}
+
+grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice* source, size_t split,
+ grpc_slice_ref_whom ref_whom) {
+ grpc_slice tail;
+
+ if (source->refcount == nullptr) {
+ /* inlined data, copy it out */
+ GPR_ASSERT(source->data.inlined.length >= split);
+ tail.refcount = nullptr;
+ tail.data.inlined.length =
+ static_cast<uint8_t>(source->data.inlined.length - split);
+ memcpy(tail.data.inlined.bytes, source->data.inlined.bytes + split,
+ tail.data.inlined.length);
+ source->data.inlined.length = static_cast<uint8_t>(split);
+ } else {
+ size_t tail_length = source->data.refcounted.length - split;
+ GPR_ASSERT(source->data.refcounted.length >= split);
+ if (tail_length < sizeof(tail.data.inlined.bytes) &&
+ ref_whom != GRPC_SLICE_REF_TAIL) {
+ /* Copy out the bytes - it'll be cheaper than refcounting */
+ tail.refcount = nullptr;
+ 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();
- } else {
- /* Build the result */
- switch (ref_whom) {
- case GRPC_SLICE_REF_TAIL:
+ } else {
+ /* Build the result */
+ switch (ref_whom) {
+ case GRPC_SLICE_REF_TAIL:
tail.refcount = source->refcount->sub_refcount();
source->refcount = &grpc_core::kNoopRefcount;
- break;
- case GRPC_SLICE_REF_HEAD:
+ break;
+ case GRPC_SLICE_REF_HEAD:
tail.refcount = &grpc_core::kNoopRefcount;
source->refcount = source->refcount->sub_refcount();
- break;
- case GRPC_SLICE_REF_BOTH:
+ break;
+ case GRPC_SLICE_REF_BOTH:
tail.refcount = source->refcount->sub_refcount();
source->refcount = source->refcount->sub_refcount();
- /* Bump the refcount */
+ /* Bump the refcount */
tail.refcount->Ref();
- break;
- }
- /* Point into the source array */
- tail.data.refcounted.bytes = source->data.refcounted.bytes + split;
- tail.data.refcounted.length = tail_length;
- }
- source->data.refcounted.length = split;
- }
-
- return tail;
-}
-
-grpc_slice grpc_slice_split_tail(grpc_slice* source, size_t split) {
- return grpc_slice_split_tail_maybe_ref(source, split, GRPC_SLICE_REF_BOTH);
-}
-
-grpc_slice grpc_slice_split_head(grpc_slice* source, size_t split) {
- grpc_slice head;
-
- if (source->refcount == nullptr) {
- GPR_ASSERT(source->data.inlined.length >= split);
-
- head.refcount = nullptr;
- head.data.inlined.length = static_cast<uint8_t>(split);
- memcpy(head.data.inlined.bytes, source->data.inlined.bytes, split);
- source->data.inlined.length =
- static_cast<uint8_t>(source->data.inlined.length - split);
- memmove(source->data.inlined.bytes, source->data.inlined.bytes + split,
- source->data.inlined.length);
- } else if (split < sizeof(head.data.inlined.bytes)) {
- GPR_ASSERT(source->data.refcounted.length >= split);
-
- head.refcount = nullptr;
- head.data.inlined.length = static_cast<uint8_t>(split);
- memcpy(head.data.inlined.bytes, source->data.refcounted.bytes, split);
+ break;
+ }
+ /* Point into the source array */
+ tail.data.refcounted.bytes = source->data.refcounted.bytes + split;
+ tail.data.refcounted.length = tail_length;
+ }
+ source->data.refcounted.length = split;
+ }
+
+ return tail;
+}
+
+grpc_slice grpc_slice_split_tail(grpc_slice* source, size_t split) {
+ return grpc_slice_split_tail_maybe_ref(source, split, GRPC_SLICE_REF_BOTH);
+}
+
+grpc_slice grpc_slice_split_head(grpc_slice* source, size_t split) {
+ grpc_slice head;
+
+ if (source->refcount == nullptr) {
+ GPR_ASSERT(source->data.inlined.length >= split);
+
+ head.refcount = nullptr;
+ head.data.inlined.length = static_cast<uint8_t>(split);
+ memcpy(head.data.inlined.bytes, source->data.inlined.bytes, split);
+ source->data.inlined.length =
+ static_cast<uint8_t>(source->data.inlined.length - split);
+ memmove(source->data.inlined.bytes, source->data.inlined.bytes + split,
+ source->data.inlined.length);
+ } else if (split < sizeof(head.data.inlined.bytes)) {
+ GPR_ASSERT(source->data.refcounted.length >= 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->data.refcounted.bytes += split;
- source->data.refcounted.length -= split;
- } else {
- GPR_ASSERT(source->data.refcounted.length >= split);
-
- /* Build the result */
+ 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();
- /* Bump the refcount */
+ /* Bump the refcount */
head.refcount->Ref();
- /* Point into the source array */
- head.data.refcounted.bytes = source->data.refcounted.bytes;
- head.data.refcounted.length = split;
+ /* 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->data.refcounted.bytes += split;
- source->data.refcounted.length -= split;
- }
-
- return head;
-}
-
-int grpc_slice_default_eq_impl(grpc_slice a, grpc_slice b) {
- if (GRPC_SLICE_LENGTH(a) != GRPC_SLICE_LENGTH(b)) return false;
- if (GRPC_SLICE_LENGTH(a) == 0) return true;
- return 0 == memcmp(GRPC_SLICE_START_PTR(a), GRPC_SLICE_START_PTR(b),
- GRPC_SLICE_LENGTH(a));
-}
-
-int grpc_slice_eq(grpc_slice a, grpc_slice b) {
+ source->data.refcounted.bytes += split;
+ source->data.refcounted.length -= split;
+ }
+
+ return head;
+}
+
+int grpc_slice_default_eq_impl(grpc_slice a, grpc_slice b) {
+ if (GRPC_SLICE_LENGTH(a) != GRPC_SLICE_LENGTH(b)) return false;
+ if (GRPC_SLICE_LENGTH(a) == 0) return true;
+ return 0 == memcmp(GRPC_SLICE_START_PTR(a), GRPC_SLICE_START_PTR(b),
+ GRPC_SLICE_LENGTH(a));
+}
+
+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);
- }
- return grpc_slice_default_eq_impl(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;
@@ -525,72 +525,72 @@ int grpc_slice_differs_refcounted(const grpc_slice& a,
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;
- return memcmp(GRPC_SLICE_START_PTR(a), GRPC_SLICE_START_PTR(b),
- GRPC_SLICE_LENGTH(a));
-}
-
-int grpc_slice_str_cmp(grpc_slice a, const char* b) {
- size_t b_length = strlen(b);
- int d = static_cast<int>(GRPC_SLICE_LENGTH(a) - b_length);
- if (d != 0) return d;
- return memcmp(GRPC_SLICE_START_PTR(a), b, b_length);
-}
-
-int grpc_slice_is_equivalent(grpc_slice a, grpc_slice b) {
- if (a.refcount == nullptr || b.refcount == nullptr) {
- return grpc_slice_eq(a, b);
- }
- return a.data.refcounted.length == b.data.refcounted.length &&
- a.data.refcounted.bytes == b.data.refcounted.bytes;
-}
-
-int grpc_slice_buf_start_eq(grpc_slice a, const void* b, size_t len) {
- if (GRPC_SLICE_LENGTH(a) < len) return 0;
- return 0 == memcmp(GRPC_SLICE_START_PTR(a), b, len);
-}
-
-int grpc_slice_rchr(grpc_slice s, char c) {
- const char* b = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s);
- int i;
- for (i = static_cast<int> GRPC_SLICE_LENGTH(s) - 1; i != -1 && b[i] != c; i--)
- ;
- return i;
-}
-
-int grpc_slice_chr(grpc_slice s, char c) {
- const char* b = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s);
- const char* p = static_cast<const char*>(memchr(b, c, GRPC_SLICE_LENGTH(s)));
- return p == nullptr ? -1 : static_cast<int>(p - b);
-}
-
-int grpc_slice_slice(grpc_slice haystack, grpc_slice needle) {
- size_t haystack_len = GRPC_SLICE_LENGTH(haystack);
- const uint8_t* haystack_bytes = GRPC_SLICE_START_PTR(haystack);
- size_t needle_len = GRPC_SLICE_LENGTH(needle);
- const uint8_t* needle_bytes = GRPC_SLICE_START_PTR(needle);
-
- if (haystack_len == 0 || needle_len == 0) return -1;
- if (haystack_len < needle_len) return -1;
- if (haystack_len == needle_len)
- return grpc_slice_eq(haystack, needle) ? 0 : -1;
- if (needle_len == 1)
- return grpc_slice_chr(haystack, static_cast<char>(*needle_bytes));
-
- const uint8_t* last = haystack_bytes + haystack_len - needle_len;
- for (const uint8_t* cur = haystack_bytes; cur != last; ++cur) {
- if (0 == memcmp(cur, needle_bytes, needle_len)) {
- return static_cast<int>(cur - haystack_bytes);
- }
- }
- return -1;
-}
-
-grpc_slice grpc_slice_dup(grpc_slice a) {
- grpc_slice copy = GRPC_SLICE_MALLOC(GRPC_SLICE_LENGTH(a));
- memcpy(GRPC_SLICE_START_PTR(copy), GRPC_SLICE_START_PTR(a),
- GRPC_SLICE_LENGTH(a));
- return copy;
-}
+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;
+ return memcmp(GRPC_SLICE_START_PTR(a), GRPC_SLICE_START_PTR(b),
+ GRPC_SLICE_LENGTH(a));
+}
+
+int grpc_slice_str_cmp(grpc_slice a, const char* b) {
+ size_t b_length = strlen(b);
+ int d = static_cast<int>(GRPC_SLICE_LENGTH(a) - b_length);
+ if (d != 0) return d;
+ return memcmp(GRPC_SLICE_START_PTR(a), b, b_length);
+}
+
+int grpc_slice_is_equivalent(grpc_slice a, grpc_slice b) {
+ if (a.refcount == nullptr || b.refcount == nullptr) {
+ return grpc_slice_eq(a, b);
+ }
+ return a.data.refcounted.length == b.data.refcounted.length &&
+ a.data.refcounted.bytes == b.data.refcounted.bytes;
+}
+
+int grpc_slice_buf_start_eq(grpc_slice a, const void* b, size_t len) {
+ if (GRPC_SLICE_LENGTH(a) < len) return 0;
+ return 0 == memcmp(GRPC_SLICE_START_PTR(a), b, len);
+}
+
+int grpc_slice_rchr(grpc_slice s, char c) {
+ const char* b = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s);
+ int i;
+ for (i = static_cast<int> GRPC_SLICE_LENGTH(s) - 1; i != -1 && b[i] != c; i--)
+ ;
+ return i;
+}
+
+int grpc_slice_chr(grpc_slice s, char c) {
+ const char* b = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s);
+ const char* p = static_cast<const char*>(memchr(b, c, GRPC_SLICE_LENGTH(s)));
+ return p == nullptr ? -1 : static_cast<int>(p - b);
+}
+
+int grpc_slice_slice(grpc_slice haystack, grpc_slice needle) {
+ size_t haystack_len = GRPC_SLICE_LENGTH(haystack);
+ const uint8_t* haystack_bytes = GRPC_SLICE_START_PTR(haystack);
+ size_t needle_len = GRPC_SLICE_LENGTH(needle);
+ const uint8_t* needle_bytes = GRPC_SLICE_START_PTR(needle);
+
+ if (haystack_len == 0 || needle_len == 0) return -1;
+ if (haystack_len < needle_len) return -1;
+ if (haystack_len == needle_len)
+ return grpc_slice_eq(haystack, needle) ? 0 : -1;
+ if (needle_len == 1)
+ return grpc_slice_chr(haystack, static_cast<char>(*needle_bytes));
+
+ const uint8_t* last = haystack_bytes + haystack_len - needle_len;
+ for (const uint8_t* cur = haystack_bytes; cur != last; ++cur) {
+ if (0 == memcmp(cur, needle_bytes, needle_len)) {
+ return static_cast<int>(cur - haystack_bytes);
+ }
+ }
+ return -1;
+}
+
+grpc_slice grpc_slice_dup(grpc_slice a) {
+ grpc_slice copy = GRPC_SLICE_MALLOC(GRPC_SLICE_LENGTH(a));
+ memcpy(GRPC_SLICE_START_PTR(copy), GRPC_SLICE_START_PTR(a),
+ GRPC_SLICE_LENGTH(a));
+ return copy;
+}
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 2d666947362..01fd4ecf552 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc
@@ -1,37 +1,37 @@
-/*
- *
- * 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 <grpc/slice_buffer.h>
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-/* grow a buffer; requires GRPC_SLICE_BUFFER_INLINE_ELEMENTS > 1 */
-#define GROW(x) (3 * (x) / 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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice_buffer.h>
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+/* 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
@@ -60,332 +60,332 @@ static void GPR_ATTRIBUTE_NOINLINE do_embiggen(grpc_slice_buffer* sb,
}
}
-static void maybe_embiggen(grpc_slice_buffer* sb) {
+static void maybe_embiggen(grpc_slice_buffer* sb) {
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;
+ /* 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);
- }
-}
-
-void grpc_slice_buffer_init(grpc_slice_buffer* sb) {
- sb->count = 0;
- sb->length = 0;
- sb->capacity = GRPC_SLICE_BUFFER_INLINE_ELEMENTS;
- sb->base_slices = sb->slices = sb->inlined;
-}
-
-void grpc_slice_buffer_destroy_internal(grpc_slice_buffer* sb) {
- grpc_slice_buffer_reset_and_unref_internal(sb);
- if (sb->base_slices != sb->inlined) {
- gpr_free(sb->base_slices);
- }
-}
-
-void grpc_slice_buffer_destroy(grpc_slice_buffer* sb) {
- if (grpc_core::ExecCtx::Get() == nullptr) {
- grpc_core::ExecCtx exec_ctx;
- grpc_slice_buffer_destroy_internal(sb);
- } else {
- grpc_slice_buffer_destroy_internal(sb);
- }
-}
-
-uint8_t* grpc_slice_buffer_tiny_add(grpc_slice_buffer* sb, size_t n) {
- grpc_slice* back;
- uint8_t* out;
-
- sb->length += n;
-
+ }
+}
+
+void grpc_slice_buffer_init(grpc_slice_buffer* sb) {
+ sb->count = 0;
+ sb->length = 0;
+ sb->capacity = GRPC_SLICE_BUFFER_INLINE_ELEMENTS;
+ sb->base_slices = sb->slices = sb->inlined;
+}
+
+void grpc_slice_buffer_destroy_internal(grpc_slice_buffer* sb) {
+ grpc_slice_buffer_reset_and_unref_internal(sb);
+ if (sb->base_slices != sb->inlined) {
+ gpr_free(sb->base_slices);
+ }
+}
+
+void grpc_slice_buffer_destroy(grpc_slice_buffer* sb) {
+ if (grpc_core::ExecCtx::Get() == nullptr) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_slice_buffer_destroy_internal(sb);
+ } else {
+ grpc_slice_buffer_destroy_internal(sb);
+ }
+}
+
+uint8_t* grpc_slice_buffer_tiny_add(grpc_slice_buffer* sb, size_t n) {
+ grpc_slice* back;
+ uint8_t* out;
+
+ sb->length += n;
+
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))
- goto add_new;
- out = back->data.inlined.bytes + back->data.inlined.length;
- back->data.inlined.length =
- static_cast<uint8_t>(back->data.inlined.length + n);
- return out;
-
-add_new:
- maybe_embiggen(sb);
+ back = &sb->slices[sb->count - 1];
+ if (back->refcount) goto add_new;
+ if ((back->data.inlined.length + n) > sizeof(back->data.inlined.bytes))
+ goto add_new;
+ out = back->data.inlined.bytes + back->data.inlined.length;
+ back->data.inlined.length =
+ static_cast<uint8_t>(back->data.inlined.length + n);
+ return out;
+
+add_new:
+ maybe_embiggen(sb);
add_first:
- back = &sb->slices[sb->count];
- sb->count++;
- back->refcount = nullptr;
- back->data.inlined.length = static_cast<uint8_t>(n);
- return back->data.inlined.bytes;
-}
-
-size_t grpc_slice_buffer_add_indexed(grpc_slice_buffer* sb, grpc_slice s) {
- size_t out = sb->count;
- maybe_embiggen(sb);
- sb->slices[out] = s;
- sb->length += GRPC_SLICE_LENGTH(s);
- sb->count = out + 1;
- return out;
-}
-
-void grpc_slice_buffer_add(grpc_slice_buffer* sb, grpc_slice s) {
- size_t n = sb->count;
- /* if both the last slice in the slice buffer and the slice being added
- are inlined (that is, that they carry their data inside the slice data
- structure), and the back slice is not full, then concatenate directly
- into the back slice, preventing many small slices being passed into
- writes */
- if (!s.refcount && n) {
- grpc_slice* back = &sb->slices[n - 1];
- if (!back->refcount &&
- back->data.inlined.length < GRPC_SLICE_INLINED_SIZE) {
- if (s.data.inlined.length + back->data.inlined.length <=
- GRPC_SLICE_INLINED_SIZE) {
- memcpy(back->data.inlined.bytes + back->data.inlined.length,
- s.data.inlined.bytes, s.data.inlined.length);
- back->data.inlined.length = static_cast<uint8_t>(
- back->data.inlined.length + s.data.inlined.length);
- } else {
- size_t cp1 = GRPC_SLICE_INLINED_SIZE - back->data.inlined.length;
- memcpy(back->data.inlined.bytes + back->data.inlined.length,
- s.data.inlined.bytes, cp1);
- back->data.inlined.length = GRPC_SLICE_INLINED_SIZE;
- maybe_embiggen(sb);
- back = &sb->slices[n];
- sb->count = n + 1;
- back->refcount = nullptr;
- back->data.inlined.length =
- static_cast<uint8_t>(s.data.inlined.length - cp1);
- memcpy(back->data.inlined.bytes, s.data.inlined.bytes + cp1,
- s.data.inlined.length - cp1);
- }
- sb->length += s.data.inlined.length;
- return; /* early out */
- }
- }
- grpc_slice_buffer_add_indexed(sb, s);
-}
-
-void grpc_slice_buffer_addn(grpc_slice_buffer* sb, grpc_slice* s, size_t n) {
- size_t i;
- for (i = 0; i < n; i++) {
- grpc_slice_buffer_add(sb, s[i]);
- }
-}
-
-void grpc_slice_buffer_pop(grpc_slice_buffer* sb) {
- if (sb->count != 0) {
- size_t count = --sb->count;
- sb->length -= GRPC_SLICE_LENGTH(sb->slices[count]);
- }
-}
-
-void grpc_slice_buffer_reset_and_unref_internal(grpc_slice_buffer* sb) {
- size_t i;
- for (i = 0; i < sb->count; i++) {
- grpc_slice_unref_internal(sb->slices[i]);
- }
-
- sb->count = 0;
- sb->length = 0;
+ back = &sb->slices[sb->count];
+ sb->count++;
+ back->refcount = nullptr;
+ back->data.inlined.length = static_cast<uint8_t>(n);
+ return back->data.inlined.bytes;
+}
+
+size_t grpc_slice_buffer_add_indexed(grpc_slice_buffer* sb, grpc_slice s) {
+ size_t out = sb->count;
+ maybe_embiggen(sb);
+ sb->slices[out] = s;
+ sb->length += GRPC_SLICE_LENGTH(s);
+ sb->count = out + 1;
+ return out;
+}
+
+void grpc_slice_buffer_add(grpc_slice_buffer* sb, grpc_slice s) {
+ size_t n = sb->count;
+ /* if both the last slice in the slice buffer and the slice being added
+ are inlined (that is, that they carry their data inside the slice data
+ structure), and the back slice is not full, then concatenate directly
+ into the back slice, preventing many small slices being passed into
+ writes */
+ if (!s.refcount && n) {
+ grpc_slice* back = &sb->slices[n - 1];
+ if (!back->refcount &&
+ back->data.inlined.length < GRPC_SLICE_INLINED_SIZE) {
+ if (s.data.inlined.length + back->data.inlined.length <=
+ GRPC_SLICE_INLINED_SIZE) {
+ memcpy(back->data.inlined.bytes + back->data.inlined.length,
+ s.data.inlined.bytes, s.data.inlined.length);
+ back->data.inlined.length = static_cast<uint8_t>(
+ back->data.inlined.length + s.data.inlined.length);
+ } else {
+ size_t cp1 = GRPC_SLICE_INLINED_SIZE - back->data.inlined.length;
+ memcpy(back->data.inlined.bytes + back->data.inlined.length,
+ s.data.inlined.bytes, cp1);
+ back->data.inlined.length = GRPC_SLICE_INLINED_SIZE;
+ maybe_embiggen(sb);
+ back = &sb->slices[n];
+ sb->count = n + 1;
+ back->refcount = nullptr;
+ back->data.inlined.length =
+ static_cast<uint8_t>(s.data.inlined.length - cp1);
+ memcpy(back->data.inlined.bytes, s.data.inlined.bytes + cp1,
+ s.data.inlined.length - cp1);
+ }
+ sb->length += s.data.inlined.length;
+ return; /* early out */
+ }
+ }
+ grpc_slice_buffer_add_indexed(sb, s);
+}
+
+void grpc_slice_buffer_addn(grpc_slice_buffer* sb, grpc_slice* s, size_t n) {
+ size_t i;
+ for (i = 0; i < n; i++) {
+ grpc_slice_buffer_add(sb, s[i]);
+ }
+}
+
+void grpc_slice_buffer_pop(grpc_slice_buffer* sb) {
+ if (sb->count != 0) {
+ size_t count = --sb->count;
+ sb->length -= GRPC_SLICE_LENGTH(sb->slices[count]);
+ }
+}
+
+void grpc_slice_buffer_reset_and_unref_internal(grpc_slice_buffer* sb) {
+ size_t i;
+ for (i = 0; i < sb->count; i++) {
+ grpc_slice_unref_internal(sb->slices[i]);
+ }
+
+ sb->count = 0;
+ sb->length = 0;
sb->slices = sb->base_slices;
-}
-
-void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer* sb) {
- if (grpc_core::ExecCtx::Get() == nullptr) {
- grpc_core::ExecCtx exec_ctx;
- grpc_slice_buffer_reset_and_unref_internal(sb);
- } else {
- grpc_slice_buffer_reset_and_unref_internal(sb);
- }
-}
-
-void grpc_slice_buffer_swap(grpc_slice_buffer* a, grpc_slice_buffer* b) {
- size_t a_offset = static_cast<size_t>(a->slices - a->base_slices);
- size_t b_offset = static_cast<size_t>(b->slices - b->base_slices);
-
- size_t a_count = a->count + a_offset;
- size_t b_count = b->count + b_offset;
-
- if (a->base_slices == a->inlined) {
- if (b->base_slices == b->inlined) {
- /* swap contents of inlined buffer */
- grpc_slice temp[GRPC_SLICE_BUFFER_INLINE_ELEMENTS];
- memcpy(temp, a->base_slices, a_count * sizeof(grpc_slice));
- memcpy(a->base_slices, b->base_slices, b_count * sizeof(grpc_slice));
- memcpy(b->base_slices, temp, a_count * sizeof(grpc_slice));
- } else {
- /* a is inlined, b is not - copy a inlined into b, fix pointers */
- a->base_slices = b->base_slices;
- b->base_slices = b->inlined;
- memcpy(b->base_slices, a->inlined, a_count * sizeof(grpc_slice));
- }
- } else if (b->base_slices == b->inlined) {
- /* b is inlined, a is not - copy b inlined int a, fix pointers */
- b->base_slices = a->base_slices;
- a->base_slices = a->inlined;
- memcpy(a->base_slices, b->inlined, b_count * sizeof(grpc_slice));
- } else {
- /* no inlining: easy swap */
- GPR_SWAP(grpc_slice*, a->base_slices, b->base_slices);
- }
-
- /* Update the slices pointers (cannot do a GPR_SWAP on slices fields here).
- * Also note that since the base_slices pointers are already swapped we need
- * use 'b_offset' for 'a->base_slices' and vice versa */
- a->slices = a->base_slices + b_offset;
- b->slices = b->base_slices + a_offset;
-
- /* base_slices and slices fields are correctly set. Swap all other fields */
- GPR_SWAP(size_t, a->count, b->count);
- GPR_SWAP(size_t, a->capacity, b->capacity);
- GPR_SWAP(size_t, a->length, b->length);
-}
-
-void grpc_slice_buffer_move_into(grpc_slice_buffer* src,
- grpc_slice_buffer* dst) {
- /* anything to move? */
- if (src->count == 0) {
- return;
- }
- /* anything in dst? */
- if (dst->count == 0) {
- grpc_slice_buffer_swap(src, dst);
- return;
- }
- /* both buffers have data - copy, and reset src */
- grpc_slice_buffer_addn(dst, src->slices, src->count);
- src->count = 0;
- src->length = 0;
-}
-
+}
+
+void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer* sb) {
+ if (grpc_core::ExecCtx::Get() == nullptr) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_slice_buffer_reset_and_unref_internal(sb);
+ } else {
+ grpc_slice_buffer_reset_and_unref_internal(sb);
+ }
+}
+
+void grpc_slice_buffer_swap(grpc_slice_buffer* a, grpc_slice_buffer* b) {
+ size_t a_offset = static_cast<size_t>(a->slices - a->base_slices);
+ size_t b_offset = static_cast<size_t>(b->slices - b->base_slices);
+
+ size_t a_count = a->count + a_offset;
+ size_t b_count = b->count + b_offset;
+
+ if (a->base_slices == a->inlined) {
+ if (b->base_slices == b->inlined) {
+ /* swap contents of inlined buffer */
+ grpc_slice temp[GRPC_SLICE_BUFFER_INLINE_ELEMENTS];
+ memcpy(temp, a->base_slices, a_count * sizeof(grpc_slice));
+ memcpy(a->base_slices, b->base_slices, b_count * sizeof(grpc_slice));
+ memcpy(b->base_slices, temp, a_count * sizeof(grpc_slice));
+ } else {
+ /* a is inlined, b is not - copy a inlined into b, fix pointers */
+ a->base_slices = b->base_slices;
+ b->base_slices = b->inlined;
+ memcpy(b->base_slices, a->inlined, a_count * sizeof(grpc_slice));
+ }
+ } else if (b->base_slices == b->inlined) {
+ /* b is inlined, a is not - copy b inlined int a, fix pointers */
+ b->base_slices = a->base_slices;
+ a->base_slices = a->inlined;
+ memcpy(a->base_slices, b->inlined, b_count * sizeof(grpc_slice));
+ } else {
+ /* no inlining: easy swap */
+ GPR_SWAP(grpc_slice*, a->base_slices, b->base_slices);
+ }
+
+ /* Update the slices pointers (cannot do a GPR_SWAP on slices fields here).
+ * Also note that since the base_slices pointers are already swapped we need
+ * use 'b_offset' for 'a->base_slices' and vice versa */
+ a->slices = a->base_slices + b_offset;
+ b->slices = b->base_slices + a_offset;
+
+ /* base_slices and slices fields are correctly set. Swap all other fields */
+ GPR_SWAP(size_t, a->count, b->count);
+ GPR_SWAP(size_t, a->capacity, b->capacity);
+ GPR_SWAP(size_t, a->length, b->length);
+}
+
+void grpc_slice_buffer_move_into(grpc_slice_buffer* src,
+ grpc_slice_buffer* dst) {
+ /* anything to move? */
+ if (src->count == 0) {
+ return;
+ }
+ /* anything in dst? */
+ if (dst->count == 0) {
+ grpc_slice_buffer_swap(src, dst);
+ return;
+ }
+ /* both buffers have data - copy, and reset src */
+ grpc_slice_buffer_addn(dst, src->slices, src->count);
+ src->count = 0;
+ src->length = 0;
+}
+
template <bool incref>
-static void slice_buffer_move_first_maybe_ref(grpc_slice_buffer* src, size_t n,
+static void slice_buffer_move_first_maybe_ref(grpc_slice_buffer* src, size_t n,
grpc_slice_buffer* dst) {
- GPR_ASSERT(src->length >= n);
- if (src->length == n) {
- grpc_slice_buffer_move_into(src, dst);
- return;
- }
-
- size_t output_len = dst->length + n;
- size_t new_input_len = src->length - n;
-
- while (src->count > 0) {
- grpc_slice slice = grpc_slice_buffer_take_first(src);
- size_t slice_len = GRPC_SLICE_LENGTH(slice);
- if (n > slice_len) {
- grpc_slice_buffer_add(dst, slice);
- n -= slice_len;
- } else if (n == slice_len) {
- grpc_slice_buffer_add(dst, slice);
- break;
- } else if (incref) { /* n < slice_len */
- grpc_slice_buffer_undo_take_first(
- src, grpc_slice_split_tail_maybe_ref(&slice, n, GRPC_SLICE_REF_BOTH));
- GPR_ASSERT(GRPC_SLICE_LENGTH(slice) == n);
- grpc_slice_buffer_add(dst, slice);
- break;
- } else { /* n < slice_len */
- grpc_slice_buffer_undo_take_first(
- src, grpc_slice_split_tail_maybe_ref(&slice, n, GRPC_SLICE_REF_TAIL));
- GPR_ASSERT(GRPC_SLICE_LENGTH(slice) == n);
- grpc_slice_buffer_add_indexed(dst, slice);
- break;
- }
- }
- GPR_ASSERT(dst->length == output_len);
- GPR_ASSERT(src->length == new_input_len);
- GPR_ASSERT(src->count > 0);
-}
-
-void grpc_slice_buffer_move_first(grpc_slice_buffer* src, size_t n,
- grpc_slice_buffer* dst) {
+ GPR_ASSERT(src->length >= n);
+ if (src->length == n) {
+ grpc_slice_buffer_move_into(src, dst);
+ return;
+ }
+
+ size_t output_len = dst->length + n;
+ size_t new_input_len = src->length - n;
+
+ while (src->count > 0) {
+ grpc_slice slice = grpc_slice_buffer_take_first(src);
+ size_t slice_len = GRPC_SLICE_LENGTH(slice);
+ if (n > slice_len) {
+ grpc_slice_buffer_add(dst, slice);
+ n -= slice_len;
+ } else if (n == slice_len) {
+ grpc_slice_buffer_add(dst, slice);
+ break;
+ } else if (incref) { /* n < slice_len */
+ grpc_slice_buffer_undo_take_first(
+ src, grpc_slice_split_tail_maybe_ref(&slice, n, GRPC_SLICE_REF_BOTH));
+ GPR_ASSERT(GRPC_SLICE_LENGTH(slice) == n);
+ grpc_slice_buffer_add(dst, slice);
+ break;
+ } else { /* n < slice_len */
+ grpc_slice_buffer_undo_take_first(
+ src, grpc_slice_split_tail_maybe_ref(&slice, n, GRPC_SLICE_REF_TAIL));
+ GPR_ASSERT(GRPC_SLICE_LENGTH(slice) == n);
+ grpc_slice_buffer_add_indexed(dst, slice);
+ break;
+ }
+ }
+ GPR_ASSERT(dst->length == output_len);
+ GPR_ASSERT(src->length == new_input_len);
+ GPR_ASSERT(src->count > 0);
+}
+
+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);
-}
-
-void grpc_slice_buffer_move_first_no_ref(grpc_slice_buffer* src, size_t n,
- grpc_slice_buffer* 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);
-}
-
-void grpc_slice_buffer_move_first_into_buffer(grpc_slice_buffer* src, size_t n,
- void* dst) {
- char* dstp = static_cast<char*>(dst);
- GPR_ASSERT(src->length >= n);
-
- while (n > 0) {
- grpc_slice slice = grpc_slice_buffer_take_first(src);
- size_t slice_len = GRPC_SLICE_LENGTH(slice);
- if (slice_len > n) {
- memcpy(dstp, GRPC_SLICE_START_PTR(slice), n);
- grpc_slice_buffer_undo_take_first(
- src, grpc_slice_sub_no_ref(slice, n, slice_len));
- n = 0;
- } else if (slice_len == n) {
- memcpy(dstp, GRPC_SLICE_START_PTR(slice), n);
- grpc_slice_unref_internal(slice);
- n = 0;
- } else {
- memcpy(dstp, GRPC_SLICE_START_PTR(slice), slice_len);
- dstp += slice_len;
- n -= slice_len;
- grpc_slice_unref_internal(slice);
- }
- }
-}
-
-void grpc_slice_buffer_trim_end(grpc_slice_buffer* sb, size_t n,
- grpc_slice_buffer* garbage) {
- GPR_ASSERT(n <= sb->length);
- sb->length -= n;
- for (;;) {
- size_t idx = sb->count - 1;
- grpc_slice slice = sb->slices[idx];
- size_t slice_len = GRPC_SLICE_LENGTH(slice);
- if (slice_len > n) {
- sb->slices[idx] = grpc_slice_split_head(&slice, slice_len - n);
+}
+
+void grpc_slice_buffer_move_first_into_buffer(grpc_slice_buffer* src, size_t n,
+ void* dst) {
+ char* dstp = static_cast<char*>(dst);
+ GPR_ASSERT(src->length >= n);
+
+ while (n > 0) {
+ grpc_slice slice = grpc_slice_buffer_take_first(src);
+ size_t slice_len = GRPC_SLICE_LENGTH(slice);
+ if (slice_len > n) {
+ memcpy(dstp, GRPC_SLICE_START_PTR(slice), n);
+ grpc_slice_buffer_undo_take_first(
+ src, grpc_slice_sub_no_ref(slice, n, slice_len));
+ n = 0;
+ } else if (slice_len == n) {
+ memcpy(dstp, GRPC_SLICE_START_PTR(slice), n);
+ grpc_slice_unref_internal(slice);
+ n = 0;
+ } else {
+ memcpy(dstp, GRPC_SLICE_START_PTR(slice), slice_len);
+ dstp += slice_len;
+ n -= slice_len;
+ grpc_slice_unref_internal(slice);
+ }
+ }
+}
+
+void grpc_slice_buffer_trim_end(grpc_slice_buffer* sb, size_t n,
+ grpc_slice_buffer* garbage) {
+ GPR_ASSERT(n <= sb->length);
+ sb->length -= n;
+ for (;;) {
+ size_t idx = sb->count - 1;
+ grpc_slice slice = sb->slices[idx];
+ size_t slice_len = GRPC_SLICE_LENGTH(slice);
+ if (slice_len > n) {
+ sb->slices[idx] = grpc_slice_split_head(&slice, slice_len - n);
if (garbage) {
grpc_slice_buffer_add_indexed(garbage, slice);
} else {
grpc_slice_unref_internal(slice);
}
- return;
- } else if (slice_len == n) {
+ return;
+ } else if (slice_len == n) {
if (garbage) {
grpc_slice_buffer_add_indexed(garbage, slice);
} else {
grpc_slice_unref_internal(slice);
}
- sb->count = idx;
- return;
- } else {
+ sb->count = idx;
+ return;
+ } else {
if (garbage) {
grpc_slice_buffer_add_indexed(garbage, slice);
} else {
grpc_slice_unref_internal(slice);
}
- n -= slice_len;
- sb->count = idx;
- }
- }
-}
-
-grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer* sb) {
- grpc_slice slice;
- GPR_ASSERT(sb->count > 0);
- slice = sb->slices[0];
- sb->slices++;
- sb->count--;
- sb->length -= GRPC_SLICE_LENGTH(slice);
-
- return slice;
-}
-
+ n -= slice_len;
+ sb->count = idx;
+ }
+ }
+}
+
+grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer* sb) {
+ grpc_slice slice;
+ GPR_ASSERT(sb->count > 0);
+ slice = sb->slices[0];
+ sb->slices++;
+ sb->count--;
+ sb->length -= GRPC_SLICE_LENGTH(slice);
+
+ 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]);
@@ -404,10 +404,10 @@ void grpc_slice_buffer_sub_first(grpc_slice_buffer* sb, size_t begin,
sb->length += end - begin;
}
-void grpc_slice_buffer_undo_take_first(grpc_slice_buffer* sb,
- grpc_slice slice) {
- sb->slices--;
- sb->slices[0] = slice;
- sb->count++;
- sb->length += GRPC_SLICE_LENGTH(slice);
-}
+void grpc_slice_buffer_undo_take_first(grpc_slice_buffer* sb,
+ grpc_slice slice) {
+ sb->slices--;
+ sb->slices[0] = slice;
+ sb->count++;
+ sb->length += GRPC_SLICE_LENGTH(slice);
+}
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 b41628c70b0..a51ba3f9593 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_intern.cc
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_intern.cc
@@ -1,68 +1,68 @@
-/*
- *
- * 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/slice/slice_internal.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/slice/slice_internal.h"
#include "src/core/lib/slice/slice_utils.h"
-
-#include <inttypes.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/murmur_hash.h"
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/murmur_hash.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"
-#include "src/core/lib/transport/static_metadata.h"
-
-#define LOG2_SHARD_COUNT 5
-#define SHARD_COUNT (1 << LOG2_SHARD_COUNT)
-#define INITIAL_SHARD_CAPACITY 8
-
-#define TABLE_IDX(hash, capacity) (((hash) >> LOG2_SHARD_COUNT) % (capacity))
-#define SHARD_IDX(hash) ((hash) & ((1 << LOG2_SHARD_COUNT) - 1))
-
+#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"
+#include "src/core/lib/transport/static_metadata.h"
+
+#define LOG2_SHARD_COUNT 5
+#define SHARD_COUNT (1 << LOG2_SHARD_COUNT)
+#define INITIAL_SHARD_CAPACITY 8
+
+#define TABLE_IDX(hash, capacity) (((hash) >> LOG2_SHARD_COUNT) % (capacity))
+#define SHARD_IDX(hash) ((hash) & ((1 << LOG2_SHARD_COUNT) - 1))
+
using grpc_core::InternedSliceRefcount;
-
-typedef struct slice_shard {
- gpr_mu mu;
+
+typedef struct slice_shard {
+ gpr_mu mu;
InternedSliceRefcount** strs;
- size_t count;
- size_t capacity;
-} slice_shard;
-
-static slice_shard g_shards[SHARD_COUNT];
-
+ size_t count;
+ size_t capacity;
+} slice_shard;
+
+static slice_shard g_shards[SHARD_COUNT];
+
struct static_metadata_hash_ent {
- uint32_t hash;
- uint32_t idx;
+ uint32_t hash;
+ uint32_t idx;
};
-static static_metadata_hash_ent
- static_metadata_hash[4 * GRPC_STATIC_MDSTR_COUNT];
-static uint32_t max_static_metadata_hash_probe;
+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;
@@ -73,90 +73,90 @@ InternedSliceRefcount::~InternedSliceRefcount() {
InternedSliceRefcount** prev_next;
InternedSliceRefcount* cur;
for (prev_next = &shard->strs[TABLE_IDX(this->hash, shard->capacity)],
- cur = *prev_next;
+ cur = *prev_next;
cur != this; prev_next = &cur->bucket_next, cur = cur->bucket_next)
- ;
- *prev_next = cur->bucket_next;
- shard->count--;
-}
-
+ ;
+ *prev_next = cur->bucket_next;
+ shard->count--;
+}
+
} // 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;
+
+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;
-
+
strtab = static_cast<InternedSliceRefcount**>(
gpr_zalloc(sizeof(InternedSliceRefcount*) * capacity));
-
- for (i = 0; i < shard->capacity; i++) {
- for (s = shard->strs[i]; s; s = next) {
- size_t idx = TABLE_IDX(s->hash, capacity);
- next = s->bucket_next;
- s->bucket_next = strtab[idx];
- strtab[idx] = s;
- }
- }
- gpr_free(shard->strs);
- shard->strs = strtab;
- shard->capacity = capacity;
-}
-
+
+ for (i = 0; i < shard->capacity; i++) {
+ for (s = shard->strs[i]; s; s = next) {
+ size_t idx = TABLE_IDX(s->hash, capacity);
+ next = s->bucket_next;
+ s->bucket_next = strtab[idx];
+ strtab[idx] = s;
+ }
+ }
+ gpr_free(shard->strs);
+ shard->strs = strtab;
+ 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;
-}
-
-uint32_t grpc_slice_default_hash_impl(grpc_slice s) {
- return gpr_murmur_hash3(GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s),
+}
+
+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);
-}
-
-uint32_t grpc_static_slice_hash(grpc_slice s) {
+}
+
+uint32_t grpc_static_slice_hash(grpc_slice 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);
-}
-
+}
+
+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); }
-
-grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
- bool* returned_slice_is_different) {
- if (GRPC_IS_STATIC_METADATA_STRING(slice)) {
- return slice;
- }
-
+
+grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
+ bool* returned_slice_is_different) {
+ if (GRPC_IS_STATIC_METADATA_STRING(slice)) {
+ return 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)];
+ 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();
- if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
+ if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
grpc_slice_eq_static_interned(slice, static_slice_table[ent.idx])) {
- *returned_slice_is_different = true;
+ *returned_slice_is_different = true;
return static_slice_table[ent.idx];
- }
- }
-
- return slice;
-}
-
+ }
+ }
+
+ 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);
-}
-
+}
+
// 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.
@@ -165,19 +165,19 @@ grpc_slice grpc_slice_intern(grpc_slice slice) {
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)];
+ 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();
- if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
+ if (ent.hash == hash && ent.idx < GRPC_STATIC_MDSTR_COUNT &&
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().
@@ -193,7 +193,7 @@ static const void* GetBuffer(const grpc_slice& 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
@@ -223,7 +223,7 @@ static InternedSliceRefcount* InternNewStringLocked(slice_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
@@ -236,17 +236,17 @@ static InternedSliceRefcount* MatchInternedSliceLocked(uint32_t hash,
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) {
+ /* 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;
- }
- }
- }
+ }
+ }
+ }
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.
@@ -268,11 +268,11 @@ static InternedSliceRefcount* FindOrCreateInternedSlice(uint32_t hash,
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);
@@ -284,9 +284,9 @@ grpc_core::ManagedMemorySlice::ManagedMemorySlice(const char* string,
} 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;
@@ -301,75 +301,75 @@ grpc_core::ManagedMemorySlice::ManagedMemorySlice(const grpc_slice* slice_ptr) {
} else {
*this = grpc_core::InternedSlice(FindOrCreateInternedSlice(hash, slice));
}
-}
-
-void grpc_test_only_set_slice_hash_seed(uint32_t seed) {
+}
+
+void grpc_test_only_set_slice_hash_seed(uint32_t seed) {
grpc_core::g_hash_seed = seed;
grpc_core::g_forced_hash_seed = true;
-}
-
-void grpc_slice_intern_init(void) {
+}
+
+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);
- }
- 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;
+ }
+ 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**>(
- gpr_zalloc(sizeof(*shard->strs) * shard->capacity));
- }
- for (size_t i = 0; i < GPR_ARRAY_SIZE(static_metadata_hash); i++) {
- static_metadata_hash[i].hash = 0;
- static_metadata_hash[i].idx = GRPC_STATIC_MDSTR_COUNT;
- }
- max_static_metadata_hash_probe = 0;
+ gpr_zalloc(sizeof(*shard->strs) * shard->capacity));
+ }
+ for (size_t i = 0; i < GPR_ARRAY_SIZE(static_metadata_hash); i++) {
+ static_metadata_hash[i].hash = 0;
+ 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();
- for (size_t i = 0; i < GRPC_STATIC_MDSTR_COUNT; i++) {
+ 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]);
- for (size_t j = 0; j < GPR_ARRAY_SIZE(static_metadata_hash); j++) {
+ for (size_t j = 0; j < GPR_ARRAY_SIZE(static_metadata_hash); 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) {
+ 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].idx = static_cast<uint32_t>(i);
- if (j > max_static_metadata_hash_probe) {
- max_static_metadata_hash_probe = static_cast<uint32_t>(j);
- }
- break;
- }
- }
- }
+ 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);
+ }
+ break;
+ }
+ }
+ }
// 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) {
- for (size_t i = 0; i < SHARD_COUNT; i++) {
- slice_shard* shard = &g_shards[i];
- gpr_mu_destroy(&shard->mu);
- /* TODO(ctiller): GPR_ASSERT(shard->count == 0); */
- if (shard->count != 0) {
- gpr_log(GPR_DEBUG, "WARNING: %" PRIuPTR " metadata strings were leaked",
- shard->count);
- for (size_t j = 0; j < shard->capacity; j++) {
+}
+
+void grpc_slice_intern_shutdown(void) {
+ for (size_t i = 0; i < SHARD_COUNT; i++) {
+ slice_shard* shard = &g_shards[i];
+ gpr_mu_destroy(&shard->mu);
+ /* TODO(ctiller): GPR_ASSERT(shard->count == 0); */
+ if (shard->count != 0) {
+ 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);
- gpr_log(GPR_DEBUG, "LEAKED: %s", text);
- gpr_free(text);
- }
- }
- if (grpc_iomgr_abort_on_leaks()) {
- abort();
- }
- }
- gpr_free(shard->strs);
- }
-}
+ gpr_log(GPR_DEBUG, "LEAKED: %s", text);
+ gpr_free(text);
+ }
+ }
+ if (grpc_iomgr_abort_on_leaks()) {
+ abort();
+ }
+ }
+ gpr_free(shard->strs);
+ }
+}
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 8a17b6e72ee..c55f03f0dae 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_internal.h
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_internal.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_INTERNAL_H
#define GRPC_CORE_LIB_SLICE_SLICE_INTERNAL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/support/log.h>
#include <grpc/slice.h>
@@ -275,10 +275,10 @@ inline void grpc_slice_unref_internal(const grpc_slice& slice) {
}
}
-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);
+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.
@@ -294,32 +294,32 @@ void grpc_slice_buffer_remove_first(grpc_slice_buffer* sb);
void grpc_slice_buffer_sub_first(grpc_slice_buffer* sb, size_t begin,
size_t end);
-/* Check if a slice is interned */
+/* 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;
}
-void grpc_slice_intern_init(void);
-void grpc_slice_intern_shutdown(void);
-void grpc_test_only_set_slice_hash_seed(uint32_t key);
-// if slice matches a static slice, returns the static slice
-// otherwise returns the passed in slice (without reffing it)
-// used for surface boundaries where we might receive an un-interned static
-// string
-grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
- bool* returned_slice_is_different);
-uint32_t grpc_static_slice_hash(grpc_slice s);
-int grpc_static_slice_eq(grpc_slice a, grpc_slice b);
-
+void grpc_slice_intern_init(void);
+void grpc_slice_intern_shutdown(void);
+void grpc_test_only_set_slice_hash_seed(uint32_t key);
+// if slice matches a static slice, returns the static slice
+// otherwise returns the passed in slice (without reffing it)
+// used for surface boundaries where we might receive an un-interned static
+// string
+grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice,
+ bool* returned_slice_is_different);
+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);
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 7887e0305fb..f6f3bc9654f 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
@@ -1,38 +1,38 @@
-/*
- *
- * 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/slice/slice_string_helpers.h"
-
-#include <string.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/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/lib/slice/slice_string_helpers.h"
+
+#include <string.h>
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/slice/slice_internal.h"
-
+#include "src/core/lib/slice/slice_internal.h"
+
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);
-}
-
+ 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(
@@ -41,87 +41,87 @@ grpc_slice grpc_dump_slice_to_slice(const grpc_slice& s, uint32_t flags) {
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.
- *
- * Returns 1 and updates \a begin and \a end. Returns 0 otherwise. */
-static int slice_find_separator_offset(const grpc_slice str, const char* sep,
- const size_t read_offset, size_t* begin,
- size_t* end) {
- size_t i;
- const uint8_t* str_ptr = GRPC_SLICE_START_PTR(str) + read_offset;
- const size_t str_len = GRPC_SLICE_LENGTH(str) - read_offset;
- const size_t sep_len = strlen(sep);
- if (str_len < sep_len) {
- return 0;
- }
-
- for (i = 0; i <= str_len - sep_len; i++) {
- if (memcmp(str_ptr + i, sep, sep_len) == 0) {
- *begin = read_offset;
- *end = read_offset + i;
- return 1;
- }
- }
- return 0;
-}
-
-static void skip_leading_trailing_spaces(const uint8_t* str_buffer,
- size_t* begin, size_t* end) {
- while (*begin < *end && str_buffer[*begin] == ' ') {
- (*begin)++;
- }
- while (*begin < *end && str_buffer[*end - 1] == ' ') {
- (*end)--;
- }
-}
-
-static void grpc_slice_split_inner(grpc_slice str, const char* sep,
- grpc_slice_buffer* dst, bool no_space) {
- const size_t sep_len = strlen(sep);
- size_t begin, end;
- const uint8_t* str_buffer = GRPC_SLICE_START_PTR(str);
- size_t sep_pos;
-
- GPR_ASSERT(sep_len > 0);
-
- if (slice_find_separator_offset(str, sep, 0, &begin, &end) != 0) {
- do {
- sep_pos = end;
- if (no_space) {
- skip_leading_trailing_spaces(str_buffer, &begin, &end);
- }
- grpc_slice_buffer_add_indexed(dst, grpc_slice_sub(str, begin, end));
- } while (slice_find_separator_offset(str, sep, sep_pos + sep_len, &begin,
- &end) != 0);
- begin = sep_pos + sep_len;
- end = GRPC_SLICE_LENGTH(str);
- if (no_space) {
- skip_leading_trailing_spaces(str_buffer, &begin, &end);
- }
- grpc_slice_buffer_add_indexed(dst, grpc_slice_sub(str, begin, end));
- } else { /* no sep found, add whole input */
- begin = 0;
- end = GRPC_SLICE_LENGTH(str);
- if (no_space) {
- skip_leading_trailing_spaces(str_buffer, &begin, &end);
- }
- grpc_slice_buffer_add_indexed(dst, grpc_slice_sub(str, begin, end));
- }
-}
-
-void grpc_slice_split(grpc_slice str, const char* sep, grpc_slice_buffer* dst) {
- grpc_slice_split_inner(str, sep, dst, false);
-}
-
-void grpc_slice_split_without_space(grpc_slice str, const char* sep,
- grpc_slice_buffer* dst) {
- grpc_slice_split_inner(str, sep, dst, true);
-}
-
-bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t* result) {
- return gpr_parse_bytes_to_uint32(
- reinterpret_cast<const char*> GRPC_SLICE_START_PTR(str),
- GRPC_SLICE_LENGTH(str), result) != 0;
-}
+/** 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.
+ *
+ * Returns 1 and updates \a begin and \a end. Returns 0 otherwise. */
+static int slice_find_separator_offset(const grpc_slice str, const char* sep,
+ const size_t read_offset, size_t* begin,
+ size_t* end) {
+ size_t i;
+ const uint8_t* str_ptr = GRPC_SLICE_START_PTR(str) + read_offset;
+ const size_t str_len = GRPC_SLICE_LENGTH(str) - read_offset;
+ const size_t sep_len = strlen(sep);
+ if (str_len < sep_len) {
+ return 0;
+ }
+
+ for (i = 0; i <= str_len - sep_len; i++) {
+ if (memcmp(str_ptr + i, sep, sep_len) == 0) {
+ *begin = read_offset;
+ *end = read_offset + i;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static void skip_leading_trailing_spaces(const uint8_t* str_buffer,
+ size_t* begin, size_t* end) {
+ while (*begin < *end && str_buffer[*begin] == ' ') {
+ (*begin)++;
+ }
+ while (*begin < *end && str_buffer[*end - 1] == ' ') {
+ (*end)--;
+ }
+}
+
+static void grpc_slice_split_inner(grpc_slice str, const char* sep,
+ grpc_slice_buffer* dst, bool no_space) {
+ const size_t sep_len = strlen(sep);
+ size_t begin, end;
+ const uint8_t* str_buffer = GRPC_SLICE_START_PTR(str);
+ size_t sep_pos;
+
+ GPR_ASSERT(sep_len > 0);
+
+ if (slice_find_separator_offset(str, sep, 0, &begin, &end) != 0) {
+ do {
+ sep_pos = end;
+ if (no_space) {
+ skip_leading_trailing_spaces(str_buffer, &begin, &end);
+ }
+ grpc_slice_buffer_add_indexed(dst, grpc_slice_sub(str, begin, end));
+ } while (slice_find_separator_offset(str, sep, sep_pos + sep_len, &begin,
+ &end) != 0);
+ begin = sep_pos + sep_len;
+ end = GRPC_SLICE_LENGTH(str);
+ if (no_space) {
+ skip_leading_trailing_spaces(str_buffer, &begin, &end);
+ }
+ grpc_slice_buffer_add_indexed(dst, grpc_slice_sub(str, begin, end));
+ } else { /* no sep found, add whole input */
+ begin = 0;
+ end = GRPC_SLICE_LENGTH(str);
+ if (no_space) {
+ skip_leading_trailing_spaces(str_buffer, &begin, &end);
+ }
+ grpc_slice_buffer_add_indexed(dst, grpc_slice_sub(str, begin, end));
+ }
+}
+
+void grpc_slice_split(grpc_slice str, const char* sep, grpc_slice_buffer* dst) {
+ grpc_slice_split_inner(str, sep, dst, false);
+}
+
+void grpc_slice_split_without_space(grpc_slice str, const char* sep,
+ grpc_slice_buffer* dst) {
+ grpc_slice_split_inner(str, sep, dst, true);
+}
+
+bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t* result) {
+ return gpr_parse_bytes_to_uint32(
+ reinterpret_cast<const char*> GRPC_SLICE_START_PTR(str),
+ GRPC_SLICE_LENGTH(str), result) != 0;
+}
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 6551a6df75d..2e64e7f501f 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
@@ -1,33 +1,33 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_STRING_HELPERS_H
#define GRPC_CORE_LIB_SLICE_SLICE_STRING_HELPERS_H
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
#include <stddef.h>
#include <grpc/slice.h>
#include <grpc/slice_buffer.h>
-#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gpr/string.h"
/* Calls gpr_dump on a slice. */
char* grpc_dump_slice(const grpc_slice& slice, uint32_t flags);
@@ -36,14 +36,14 @@ 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. */
-void grpc_slice_split(grpc_slice str, const char* sep, grpc_slice_buffer* dst);
-
-/** Split \a str by the separator \a sep and remove the leading and trailing
- * spaces of each resulting token. Results are stored in \a dst, which should be
- * a properly initialized instance. */
-void grpc_slice_split_without_space(grpc_slice str, const char* sep,
- grpc_slice_buffer* dst);
+void grpc_slice_split(grpc_slice str, const char* sep, grpc_slice_buffer* dst);
-bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t* result);
+/** Split \a str by the separator \a sep and remove the leading and trailing
+ * spaces of each resulting token. Results are stored in \a dst, which should be
+ * a properly initialized instance. */
+void grpc_slice_split_without_space(grpc_slice str, const char* sep,
+ grpc_slice_buffer* dst);
+bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t* result);
+
#endif /* GRPC_CORE_LIB_SLICE_SLICE_STRING_HELPERS_H */
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 07d13cd8b54..78f2403162d 100644
--- a/contrib/libs/grpc/src/core/lib/slice/slice_traits.h
+++ b/contrib/libs/grpc/src/core/lib/slice/slice_traits.h
@@ -1,31 +1,31 @@
-/*
- *
- * 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_SLICE_SLICE_TRAITS_H
-#define GRPC_CORE_LIB_SLICE_SLICE_TRAITS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.h>
-#include <stdbool.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_SLICE_SLICE_TRAITS_H
+#define GRPC_CORE_LIB_SLICE_SLICE_TRAITS_H
+
+#include <grpc/support/port_platform.h>
+
+#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);
-
-#endif /* GRPC_CORE_LIB_SLICE_SLICE_TRAITS_H */
+
+#endif /* GRPC_CORE_LIB_SLICE_SLICE_TRAITS_H */
diff --git a/contrib/libs/grpc/src/core/lib/surface/api_trace.cc b/contrib/libs/grpc/src/core/lib/surface/api_trace.cc
index bab5a7910c0..42e5da1dbc6 100644
--- a/contrib/libs/grpc/src/core/lib/surface/api_trace.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/api_trace.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/surface/api_trace.h"
-
-grpc_core::TraceFlag grpc_api_trace(false, "api");
+/*
+ *
+ * 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/debug/trace.h"
+#include "src/core/lib/surface/api_trace.h"
+
+grpc_core::TraceFlag grpc_api_trace(false, "api");
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 51d1f522230..57061ac3fd7 100644
--- a/contrib/libs/grpc/src/core/lib/surface/api_trace.h
+++ b/contrib/libs/grpc/src/core/lib/surface/api_trace.h
@@ -1,30 +1,30 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_API_TRACE_H
#define GRPC_CORE_LIB_SURFACE_API_TRACE_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/support/log.h>
#include "src/core/lib/debug/trace.h"
-extern grpc_core::TraceFlag grpc_api_trace;
+extern grpc_core::TraceFlag grpc_api_trace;
/* Provide unwrapping macros because we're in C89 and variadic macros weren't
introduced until C99... */
diff --git a/contrib/libs/grpc/src/core/lib/surface/byte_buffer.cc b/contrib/libs/grpc/src/core/lib/surface/byte_buffer.cc
index 6246796e46c..776db0da430 100644
--- a/contrib/libs/grpc/src/core/lib/surface/byte_buffer.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/byte_buffer.cc
@@ -1,92 +1,92 @@
-/*
- *
- * 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 <grpc/byte_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-grpc_byte_buffer* grpc_raw_byte_buffer_create(grpc_slice* slices,
- size_t nslices) {
- return grpc_raw_compressed_byte_buffer_create(slices, nslices,
- GRPC_COMPRESS_NONE);
-}
-
-grpc_byte_buffer* grpc_raw_compressed_byte_buffer_create(
- grpc_slice* slices, size_t nslices,
- grpc_compression_algorithm compression) {
- size_t i;
- grpc_byte_buffer* bb =
- static_cast<grpc_byte_buffer*>(gpr_malloc(sizeof(grpc_byte_buffer)));
- bb->type = GRPC_BB_RAW;
- bb->data.raw.compression = compression;
- grpc_slice_buffer_init(&bb->data.raw.slice_buffer);
- for (i = 0; i < nslices; i++) {
- grpc_slice_ref_internal(slices[i]);
- grpc_slice_buffer_add(&bb->data.raw.slice_buffer, slices[i]);
- }
- return bb;
-}
-
-grpc_byte_buffer* grpc_raw_byte_buffer_from_reader(
- grpc_byte_buffer_reader* reader) {
- grpc_byte_buffer* bb =
- static_cast<grpc_byte_buffer*>(gpr_malloc(sizeof(grpc_byte_buffer)));
- grpc_slice slice;
- bb->type = GRPC_BB_RAW;
- bb->data.raw.compression = GRPC_COMPRESS_NONE;
- grpc_slice_buffer_init(&bb->data.raw.slice_buffer);
-
- while (grpc_byte_buffer_reader_next(reader, &slice)) {
- grpc_slice_buffer_add(&bb->data.raw.slice_buffer, slice);
- }
- return bb;
-}
-
-grpc_byte_buffer* grpc_byte_buffer_copy(grpc_byte_buffer* bb) {
- switch (bb->type) {
- case GRPC_BB_RAW:
- return grpc_raw_compressed_byte_buffer_create(
- bb->data.raw.slice_buffer.slices, bb->data.raw.slice_buffer.count,
- bb->data.raw.compression);
- }
- GPR_UNREACHABLE_CODE(return nullptr);
-}
-
-void grpc_byte_buffer_destroy(grpc_byte_buffer* bb) {
- if (!bb) return;
- grpc_core::ExecCtx exec_ctx;
- switch (bb->type) {
- case GRPC_BB_RAW:
- grpc_slice_buffer_destroy_internal(&bb->data.raw.slice_buffer);
- break;
- }
- gpr_free(bb);
-}
-
-size_t grpc_byte_buffer_length(grpc_byte_buffer* bb) {
- switch (bb->type) {
- case GRPC_BB_RAW:
- return bb->data.raw.slice_buffer.length;
- }
- GPR_UNREACHABLE_CODE(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 <grpc/support/port_platform.h>
+
+#include <grpc/byte_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+grpc_byte_buffer* grpc_raw_byte_buffer_create(grpc_slice* slices,
+ size_t nslices) {
+ return grpc_raw_compressed_byte_buffer_create(slices, nslices,
+ GRPC_COMPRESS_NONE);
+}
+
+grpc_byte_buffer* grpc_raw_compressed_byte_buffer_create(
+ grpc_slice* slices, size_t nslices,
+ grpc_compression_algorithm compression) {
+ size_t i;
+ grpc_byte_buffer* bb =
+ static_cast<grpc_byte_buffer*>(gpr_malloc(sizeof(grpc_byte_buffer)));
+ bb->type = GRPC_BB_RAW;
+ bb->data.raw.compression = compression;
+ grpc_slice_buffer_init(&bb->data.raw.slice_buffer);
+ for (i = 0; i < nslices; i++) {
+ grpc_slice_ref_internal(slices[i]);
+ grpc_slice_buffer_add(&bb->data.raw.slice_buffer, slices[i]);
+ }
+ return bb;
+}
+
+grpc_byte_buffer* grpc_raw_byte_buffer_from_reader(
+ grpc_byte_buffer_reader* reader) {
+ grpc_byte_buffer* bb =
+ static_cast<grpc_byte_buffer*>(gpr_malloc(sizeof(grpc_byte_buffer)));
+ grpc_slice slice;
+ bb->type = GRPC_BB_RAW;
+ bb->data.raw.compression = GRPC_COMPRESS_NONE;
+ grpc_slice_buffer_init(&bb->data.raw.slice_buffer);
+
+ while (grpc_byte_buffer_reader_next(reader, &slice)) {
+ grpc_slice_buffer_add(&bb->data.raw.slice_buffer, slice);
+ }
+ return bb;
+}
+
+grpc_byte_buffer* grpc_byte_buffer_copy(grpc_byte_buffer* bb) {
+ switch (bb->type) {
+ case GRPC_BB_RAW:
+ return grpc_raw_compressed_byte_buffer_create(
+ bb->data.raw.slice_buffer.slices, bb->data.raw.slice_buffer.count,
+ bb->data.raw.compression);
+ }
+ GPR_UNREACHABLE_CODE(return nullptr);
+}
+
+void grpc_byte_buffer_destroy(grpc_byte_buffer* bb) {
+ if (!bb) return;
+ grpc_core::ExecCtx exec_ctx;
+ switch (bb->type) {
+ case GRPC_BB_RAW:
+ grpc_slice_buffer_destroy_internal(&bb->data.raw.slice_buffer);
+ break;
+ }
+ gpr_free(bb);
+}
+
+size_t grpc_byte_buffer_length(grpc_byte_buffer* bb) {
+ switch (bb->type) {
+ case GRPC_BB_RAW:
+ return bb->data.raw.slice_buffer.length;
+ }
+ GPR_UNREACHABLE_CODE(return 0);
+}
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 3689c79455e..381b060ec02 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/byte_buffer_reader.h>
-#include <string.h>
-
-#include <grpc/byte_buffer.h>
-#include <grpc/grpc.h>
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader,
- grpc_byte_buffer* buffer) {
- reader->buffer_in = buffer;
- switch (reader->buffer_in->type) {
- case GRPC_BB_RAW:
+/*
+ *
+ * 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 <grpc/byte_buffer_reader.h>
+#include <string.h>
+
+#include <grpc/byte_buffer.h>
+#include <grpc/grpc.h>
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader,
+ grpc_byte_buffer* buffer) {
+ reader->buffer_in = buffer;
+ switch (reader->buffer_in->type) {
+ case GRPC_BB_RAW:
reader->buffer_out = reader->buffer_in;
- reader->current.index = 0;
- break;
- }
- return 1;
-}
-
-void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader* reader) {
+ reader->current.index = 0;
+ break;
+ }
+ return 1;
+}
+
+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) {
@@ -63,39 +63,39 @@ int grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader,
return 0;
}
-int grpc_byte_buffer_reader_next(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 = grpc_slice_ref_internal(
- slice_buffer->slices[reader->current.index]);
- reader->current.index += 1;
- return 1;
- }
- break;
- }
- }
- return 0;
-}
-
-grpc_slice grpc_byte_buffer_reader_readall(grpc_byte_buffer_reader* reader) {
- grpc_slice in_slice;
- size_t bytes_read = 0;
- const size_t input_size = grpc_byte_buffer_length(reader->buffer_out);
- grpc_slice out_slice = GRPC_SLICE_MALLOC(input_size);
- uint8_t* const outbuf = GRPC_SLICE_START_PTR(out_slice); /* just an alias */
-
- grpc_core::ExecCtx exec_ctx;
- while (grpc_byte_buffer_reader_next(reader, &in_slice) != 0) {
- const size_t slice_length = GRPC_SLICE_LENGTH(in_slice);
- memcpy(&(outbuf[bytes_read]), GRPC_SLICE_START_PTR(in_slice), slice_length);
- bytes_read += slice_length;
- grpc_slice_unref_internal(in_slice);
- GPR_ASSERT(bytes_read <= input_size);
- }
-
- return out_slice;
-}
+int grpc_byte_buffer_reader_next(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 = grpc_slice_ref_internal(
+ slice_buffer->slices[reader->current.index]);
+ reader->current.index += 1;
+ return 1;
+ }
+ break;
+ }
+ }
+ return 0;
+}
+
+grpc_slice grpc_byte_buffer_reader_readall(grpc_byte_buffer_reader* reader) {
+ grpc_slice in_slice;
+ size_t bytes_read = 0;
+ const size_t input_size = grpc_byte_buffer_length(reader->buffer_out);
+ grpc_slice out_slice = GRPC_SLICE_MALLOC(input_size);
+ uint8_t* const outbuf = GRPC_SLICE_START_PTR(out_slice); /* just an alias */
+
+ grpc_core::ExecCtx exec_ctx;
+ while (grpc_byte_buffer_reader_next(reader, &in_slice) != 0) {
+ const size_t slice_length = GRPC_SLICE_LENGTH(in_slice);
+ memcpy(&(outbuf[bytes_read]), GRPC_SLICE_START_PTR(in_slice), slice_length);
+ bytes_read += slice_length;
+ grpc_slice_unref_internal(in_slice);
+ GPR_ASSERT(bytes_read <= input_size);
+ }
+
+ return out_slice;
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/call.cc b/contrib/libs/grpc/src/core/lib/surface/call.cc
index fe4c774c526..4c8c602e1b7 100644
--- a/contrib/libs/grpc/src/core/lib/surface/call.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/call.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 <assert.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.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 <assert.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
#include <util/generic/string.h>
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_format.h"
-#include <grpc/compression.h>
-#include <grpc/grpc.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/channel/channel_stack.h"
-#include "src/core/lib/compression/algorithm_metadata.h"
-#include "src/core/lib/debug/stats.h"
+#include <grpc/compression.h>
+#include <grpc/grpc.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/channel/channel_stack.h"
+#include "src/core/lib/compression/algorithm_metadata.h"
+#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/string.h"
#include "src/core/lib/gpr/time_precise.h"
-#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/arena.h"
-#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/gprpp/manual_constructor.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/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/surface/api_trace.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/surface/call_test_only.h"
-#include "src/core/lib/surface/channel.h"
-#include "src/core/lib/surface/completion_queue.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"
+#include "src/core/lib/surface/channel.h"
+#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/server.h"
-#include "src/core/lib/surface/validate_metadata.h"
-#include "src/core/lib/transport/error_utils.h"
-#include "src/core/lib/transport/metadata.h"
-#include "src/core/lib/transport/static_metadata.h"
-#include "src/core/lib/transport/status_metadata.h"
-#include "src/core/lib/transport/transport.h"
-
+#include "src/core/lib/surface/validate_metadata.h"
+#include "src/core/lib/transport/error_utils.h"
+#include "src/core/lib/transport/metadata.h"
+#include "src/core/lib/transport/static_metadata.h"
+#include "src/core/lib/transport/status_metadata.h"
+#include "src/core/lib/transport/transport.h"
+
#include <util/system/yassert.h>
-/** The maximum number of concurrent batches possible.
- Based upon the maximum number of individually queueable ops in the batch
- api:
- - initial metadata send
- - message send
- - status/close send (depending on client/server)
- - initial metadata recv
- - message recv
- - status/close recv (depending on client/server) */
-#define MAX_CONCURRENT_BATCHES 6
-
-#define MAX_SEND_EXTRA_METADATA_COUNT 3
-
+/** The maximum number of concurrent batches possible.
+ Based upon the maximum number of individually queueable ops in the batch
+ api:
+ - initial metadata send
+ - message send
+ - status/close send (depending on client/server)
+ - initial metadata recv
+ - message recv
+ - status/close recv (depending on client/server) */
+#define MAX_CONCURRENT_BATCHES 6
+
+#define MAX_SEND_EXTRA_METADATA_COUNT 3
+
// Used to create arena for the first call.
#define ESTIMATED_MDELEM_COUNT 16
-
+
struct batch_control {
batch_control() = default;
-
+
grpc_call* call = nullptr;
grpc_transport_stream_op_batch op;
- /* Share memory for cq_completion and notify_tag as they are never needed
- simultaneously. Each byte used in this data structure count as six bytes
- per call, so any savings we can make are worthwhile,
-
- We use notify_tag to determine whether or not to send notification to the
- completion queue. Once we've made that determination, we can reuse the
- memory for cq_completion. */
- union {
- grpc_cq_completion cq_completion;
- struct {
- /* Any given op indicates completion by either (a) calling a closure or
- (b) sending a notification on the call's completion queue. If
- \a is_closure is true, \a tag indicates a closure to be invoked;
- otherwise, \a tag indicates the tag to be used in the notification to
- be sent to the completion queue. */
- void* tag;
- bool is_closure;
- } notify_tag;
- } completion_data;
- grpc_closure start_batch;
- grpc_closure finish_batch;
+ /* Share memory for cq_completion and notify_tag as they are never needed
+ simultaneously. Each byte used in this data structure count as six bytes
+ per call, so any savings we can make are worthwhile,
+
+ We use notify_tag to determine whether or not to send notification to the
+ completion queue. Once we've made that determination, we can reuse the
+ memory for cq_completion. */
+ union {
+ grpc_cq_completion cq_completion;
+ struct {
+ /* Any given op indicates completion by either (a) calling a closure or
+ (b) sending a notification on the call's completion queue. If
+ \a is_closure is true, \a tag indicates a closure to be invoked;
+ otherwise, \a tag indicates the tag to be used in the notification to
+ be sent to the completion queue. */
+ void* tag;
+ bool is_closure;
+ } notify_tag;
+ } completion_data;
+ grpc_closure start_batch;
+ grpc_closure finish_batch;
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) {
@@ -116,29 +116,29 @@ struct batch_control {
return steps_to_complete.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1;
}
};
-
+
struct parent_call {
parent_call() { gpr_mu_init(&child_list_mu); }
~parent_call() { gpr_mu_destroy(&child_list_mu); }
-
- gpr_mu child_list_mu;
+
+ gpr_mu child_list_mu;
grpc_call* first_child = nullptr;
};
-
+
struct child_call {
child_call(grpc_call* parent) : parent(parent) {}
- grpc_call* parent;
- /** siblings: children of the same parent form a list, and this list is
- protected under
- parent->mu */
+ grpc_call* parent;
+ /** siblings: children of the same parent form a list, and this list is
+ protected under
+ parent->mu */
grpc_call* sibling_next = nullptr;
grpc_call* sibling_prev = nullptr;
};
-
-#define RECV_NONE ((gpr_atm)0)
-#define RECV_INITIAL_METADATA_FIRST ((gpr_atm)1)
-
-struct grpc_call {
+
+#define RECV_NONE ((gpr_atm)0)
+#define RECV_INITIAL_METADATA_FIRST ((gpr_atm)1)
+
+struct grpc_call {
grpc_call(grpc_core::Arena* arena, const grpc_call_create_args& args)
: arena(arena),
cq(args.cq),
@@ -159,20 +159,20 @@ struct grpc_call {
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;
+ grpc_completion_queue* cq;
+ grpc_polling_entity pollent;
+ grpc_channel* channel;
gpr_cycle_counter start_time = gpr_get_cycle_counter();
/* parent_call* */ gpr_atm parent_call_atm = 0;
child_call* child = nullptr;
-
- /* client or server call */
- bool is_client;
- /** has grpc_call_unref been called */
+
+ /* client or server call */
+ bool is_client;
+ /** has grpc_call_unref been called */
bool destroy_called = false;
- /** flag indicating that cancellation is inherited */
+ /** flag indicating that cancellation is inherited */
bool cancellation_is_inherited = false;
- /** which ops are in-flight */
+ /** which ops are in-flight */
bool sent_initial_metadata = false;
bool sending_message = false;
bool sent_final_op = false;
@@ -181,99 +181,99 @@ struct grpc_call {
bool requested_final_op = false;
gpr_atm any_ops_sent_atm = 0;
gpr_atm received_final_op_atm = 0;
-
+
batch_control* active_batches[MAX_CONCURRENT_BATCHES] = {};
- grpc_transport_stream_op_batch_payload stream_op_payload;
-
- /* first idx: is_receiving, second idx: is_trailing */
+ grpc_transport_stream_op_batch_payload stream_op_payload;
+
+ /* first idx: is_receiving, second idx: is_trailing */
grpc_metadata_batch metadata_batch[2][2] = {};
-
- /* Buffered read metadata waiting to be returned to the application.
- Element 0 is initial metadata, element 1 is trailing metadata. */
+
+ /* Buffered read metadata waiting to be returned to the application.
+ Element 0 is initial metadata, element 1 is trailing metadata. */
grpc_metadata_array* buffered_metadata[2] = {};
-
- grpc_metadata compression_md;
-
- // A char* indicating the peer name.
+
+ grpc_metadata compression_md;
+
+ // A char* indicating the peer name.
gpr_atm peer_string = 0;
-
- /* Call data useful used for reporting. Only valid after the call has
- * completed */
- grpc_call_final_info final_info;
-
- /* Compression algorithm for *incoming* data */
+
+ /* Call data useful used for reporting. Only valid after the call has
+ * completed */
+ grpc_call_final_info final_info;
+
+ /* Compression algorithm for *incoming* data */
grpc_message_compression_algorithm incoming_message_compression_algorithm =
GRPC_MESSAGE_COMPRESS_NONE;
- /* Stream compression algorithm for *incoming* data */
+ /* Stream compression algorithm for *incoming* data */
grpc_stream_compression_algorithm incoming_stream_compression_algorithm =
GRPC_STREAM_COMPRESS_NONE;
/* Supported encodings (compression algorithms), a bitset.
* Always support no compression. */
uint32_t encodings_accepted_by_peer = 1 << GRPC_MESSAGE_COMPRESS_NONE;
- /* Supported stream encodings (stream compression algorithms), a bitset */
+ /* Supported stream encodings (stream compression algorithms), a bitset */
uint32_t stream_encodings_accepted_by_peer = 0;
-
- /* Contexts for various subsystems (security, tracing, ...). */
+
+ /* Contexts for various subsystems (security, tracing, ...). */
grpc_call_context_element context[GRPC_CONTEXT_COUNT] = {};
-
- /* for the client, extra metadata is initial metadata; for the
- server, it's trailing metadata */
- grpc_linked_mdelem send_extra_metadata[MAX_SEND_EXTRA_METADATA_COUNT];
- int send_extra_metadata_count;
- grpc_millis send_deadline;
-
- grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> sending_stream;
-
- grpc_core::OrphanablePtr<grpc_core::ByteStream> receiving_stream;
+
+ /* for the client, extra metadata is initial metadata; for the
+ server, it's trailing metadata */
+ grpc_linked_mdelem send_extra_metadata[MAX_SEND_EXTRA_METADATA_COUNT];
+ int send_extra_metadata_count;
+ grpc_millis send_deadline;
+
+ grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> sending_stream;
+
+ grpc_core::OrphanablePtr<grpc_core::ByteStream> receiving_stream;
grpc_byte_buffer** receiving_buffer = nullptr;
grpc_slice receiving_slice = grpc_empty_slice();
- grpc_closure receiving_slice_ready;
- grpc_closure receiving_stream_ready;
- grpc_closure receiving_initial_metadata_ready;
+ grpc_closure receiving_slice_ready;
+ grpc_closure receiving_stream_ready;
+ grpc_closure receiving_initial_metadata_ready;
grpc_closure receiving_trailing_metadata_ready;
uint32_t test_only_last_message_flags = 0;
// Status about operation of call
bool sent_server_trailing_metadata = false;
gpr_atm cancelled_with_error = 0;
-
- grpc_closure release_call;
-
- union {
- struct {
- grpc_status_code* status;
- grpc_slice* status_details;
- const char** error_string;
- } client;
- struct {
- int* cancelled;
+
+ grpc_closure release_call;
+
+ union {
+ struct {
+ grpc_status_code* status;
+ grpc_slice* status_details;
+ const char** error_string;
+ } client;
+ struct {
+ int* cancelled;
// backpointer to owning server if this is a server side call.
grpc_core::Server* core_server;
- } server;
- } final_op;
+ } server;
+ } final_op;
gpr_atm status_error = 0;
-
- /* recv_state can contain one of the following values:
- RECV_NONE : : no initial metadata and messages received
- RECV_INITIAL_METADATA_FIRST : received initial metadata first
- a batch_control* : received messages first
-
- +------1------RECV_NONE------3-----+
- | |
- | |
- v v
- RECV_INITIAL_METADATA_FIRST receiving_stream_ready_bctlp
- | ^ | ^
- | | | |
- +-----2-----+ +-----4-----+
-
- For 1, 4: See receiving_initial_metadata_ready() function
- For 2, 3: See receiving_stream_ready() function */
+
+ /* recv_state can contain one of the following values:
+ RECV_NONE : : no initial metadata and messages received
+ RECV_INITIAL_METADATA_FIRST : received initial metadata first
+ a batch_control* : received messages first
+
+ +------1------RECV_NONE------3-----+
+ | |
+ | |
+ v v
+ RECV_INITIAL_METADATA_FIRST receiving_stream_ready_bctlp
+ | ^ | ^
+ | | | |
+ +-----2-----+ +-----4-----+
+
+ For 1, 4: See receiving_initial_metadata_ready() function
+ For 2, 3: See receiving_stream_ready() function */
gpr_atm recv_state = 0;
-};
-
-grpc_core::TraceFlag grpc_call_error_trace(false, "call_error");
-grpc_core::TraceFlag grpc_compression_trace(false, "compression");
-
+};
+
+grpc_core::TraceFlag grpc_call_error_trace(false, "call_error");
+grpc_core::TraceFlag grpc_compression_trace(false, "compression");
+
#define CALL_STACK_FROM_CALL(call) \
(grpc_call_stack*)((char*)(call) + \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call)))
@@ -281,69 +281,69 @@ grpc_core::TraceFlag grpc_compression_trace(false, "compression");
(grpc_call*)(((char*)(call_stack)) - \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call)))
-#define CALL_ELEM_FROM_CALL(call, idx) \
- grpc_call_stack_element(CALL_STACK_FROM_CALL(call), idx)
-#define CALL_FROM_TOP_ELEM(top_elem) \
- CALL_FROM_CALL_STACK(grpc_call_stack_from_top_element(top_elem))
-
-static void execute_batch(grpc_call* call, grpc_transport_stream_op_batch* op,
- grpc_closure* start_batch_closure);
+#define CALL_ELEM_FROM_CALL(call, idx) \
+ grpc_call_stack_element(CALL_STACK_FROM_CALL(call), idx)
+#define CALL_FROM_TOP_ELEM(top_elem) \
+ CALL_FROM_CALL_STACK(grpc_call_stack_from_top_element(top_elem))
+
+static void execute_batch(grpc_call* call, grpc_transport_stream_op_batch* op,
+ grpc_closure* start_batch_closure);
static void cancel_with_status(grpc_call* c, grpc_status_code status,
- const char* description);
+ const char* description);
static void cancel_with_error(grpc_call* c, grpc_error* error);
-static void destroy_call(void* call_stack, grpc_error* error);
-static void receiving_slice_ready(void* bctlp, grpc_error* error);
+static void destroy_call(void* call_stack, grpc_error* error);
+static void receiving_slice_ready(void* bctlp, grpc_error* error);
static void set_final_status(grpc_call* call, grpc_error* error);
-static void process_data_after_md(batch_control* bctl);
-static void post_batch_completion(batch_control* bctl);
-
-static void add_init_error(grpc_error** composite, grpc_error* new_err) {
- if (new_err == GRPC_ERROR_NONE) return;
- if (*composite == GRPC_ERROR_NONE)
- *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Call creation failed");
- *composite = grpc_error_add_child(*composite, new_err);
-}
-
-void* grpc_call_arena_alloc(grpc_call* call, size_t size) {
+static void process_data_after_md(batch_control* bctl);
+static void post_batch_completion(batch_control* bctl);
+
+static void add_init_error(grpc_error** composite, grpc_error* new_err) {
+ if (new_err == GRPC_ERROR_NONE) return;
+ if (*composite == GRPC_ERROR_NONE)
+ *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Call creation failed");
+ *composite = grpc_error_add_child(*composite, new_err);
+}
+
+void* grpc_call_arena_alloc(grpc_call* call, size_t 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) {
+}
+
+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>();
- if (!gpr_atm_rel_cas(&call->parent_call_atm, (gpr_atm) nullptr,
- (gpr_atm)p)) {
+ if (!gpr_atm_rel_cas(&call->parent_call_atm, (gpr_atm) nullptr,
+ (gpr_atm)p)) {
p->~parent_call();
- p = (parent_call*)gpr_atm_acq_load(&call->parent_call_atm);
- }
- }
- return p;
-}
-
-static parent_call* get_parent_call(grpc_call* call) {
- return (parent_call*)gpr_atm_acq_load(&call->parent_call_atm);
-}
-
+ p = (parent_call*)gpr_atm_acq_load(&call->parent_call_atm);
+ }
+ }
+ return p;
+}
+
+static parent_call* get_parent_call(grpc_call* call) {
+ return (parent_call*)gpr_atm_acq_load(&call->parent_call_atm);
+}
+
size_t grpc_call_get_initial_size_estimate() {
return sizeof(grpc_call) + sizeof(batch_control) * MAX_CONCURRENT_BATCHES +
sizeof(grpc_linked_mdelem) * ESTIMATED_MDELEM_COUNT;
}
-grpc_error* grpc_call_create(const grpc_call_create_args* args,
- grpc_call** out_call) {
- GPR_TIMER_SCOPE("grpc_call_create", 0);
+grpc_error* grpc_call_create(const grpc_call_create_args* args,
+ grpc_call** out_call) {
+ GPR_TIMER_SCOPE("grpc_call_create", 0);
GRPC_CHANNEL_INTERNAL_REF(args->channel, "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);
+ 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;
@@ -354,124 +354,124 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args,
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;
+ *out_call = call;
grpc_slice path = grpc_empty_slice();
- if (call->is_client) {
+ if (call->is_client) {
call->final_op.client.status_details = nullptr;
call->final_op.client.status = nullptr;
call->final_op.client.error_string = nullptr;
- GRPC_STATS_INC_CLIENT_CALLS_CREATED();
- GPR_ASSERT(args->add_initial_metadata_count <
- MAX_SEND_EXTRA_METADATA_COUNT);
+ GRPC_STATS_INC_CLIENT_CALLS_CREATED();
+ GPR_ASSERT(args->add_initial_metadata_count <
+ 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];
+ 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)) {
- path = grpc_slice_ref_internal(
- GRPC_MDVALUE(args->add_initial_metadata[i]));
- }
- }
- call->send_extra_metadata_count =
- static_cast<int>(args->add_initial_metadata_count);
- } else {
+ path = grpc_slice_ref_internal(
+ GRPC_MDVALUE(args->add_initial_metadata[i]));
+ }
+ }
+ call->send_extra_metadata_count =
+ static_cast<int>(args->add_initial_metadata_count);
+ } else {
GRPC_STATS_INC_SERVER_CALLS_CREATED();
call->final_op.server.cancelled = nullptr;
call->final_op.server.core_server = args->server;
- GPR_ASSERT(args->add_initial_metadata_count == 0);
- call->send_extra_metadata_count = 0;
- }
-
- grpc_millis send_deadline = args->send_deadline;
- bool immediately_cancel = false;
-
- if (args->parent != nullptr) {
+ GPR_ASSERT(args->add_initial_metadata_count == 0);
+ call->send_extra_metadata_count = 0;
+ }
+
+ grpc_millis send_deadline = args->send_deadline;
+ 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);
-
- GRPC_CALL_INTERNAL_REF(args->parent, "child");
- GPR_ASSERT(call->is_client);
- GPR_ASSERT(!args->parent->is_client);
-
- if (args->propagation_mask & GRPC_PROPAGATE_DEADLINE) {
- send_deadline = GPR_MIN(send_deadline, args->parent->send_deadline);
- }
- /* for now GRPC_PROPAGATE_TRACING_CONTEXT *MUST* be passed with
- * GRPC_PROPAGATE_STATS_CONTEXT */
- /* TODO(ctiller): This should change to use the appropriate census start_op
- * call. */
- if (args->propagation_mask & GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT) {
- if (0 == (args->propagation_mask & GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)) {
- add_init_error(&error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Census tracing propagation requested "
- "without Census context propagation"));
- }
- grpc_call_context_set(call, GRPC_CONTEXT_TRACING,
- args->parent->context[GRPC_CONTEXT_TRACING].value,
- nullptr);
- } else if (args->propagation_mask & GRPC_PROPAGATE_CENSUS_STATS_CONTEXT) {
- add_init_error(&error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Census context propagation requested "
- "without Census tracing propagation"));
- }
- if (args->propagation_mask & GRPC_PROPAGATE_CANCELLATION) {
- call->cancellation_is_inherited = 1;
- if (gpr_atm_acq_load(&args->parent->received_final_op_atm)) {
- immediately_cancel = true;
- }
- }
- }
- call->send_deadline = send_deadline;
- /* initial refcount dropped by grpc_call_unref */
- grpc_call_element_args call_args = {CALL_STACK_FROM_CALL(call),
- args->server_transport_data,
- call->context,
- path,
- call->start_time,
- send_deadline,
- call->arena,
- &call->call_combiner};
- add_init_error(&error, grpc_call_stack_init(channel_stack, 1, destroy_call,
- call, &call_args));
- // Publish this call to parent only after the call stack has been initialized.
- if (args->parent != nullptr) {
- child_call* cc = call->child;
- parent_call* pc = get_or_create_parent_call(args->parent);
- gpr_mu_lock(&pc->child_list_mu);
- if (pc->first_child == nullptr) {
- pc->first_child = call;
- cc->sibling_next = cc->sibling_prev = call;
- } else {
- cc->sibling_next = pc->first_child;
- cc->sibling_prev = pc->first_child->child->sibling_prev;
- cc->sibling_next->child->sibling_prev =
- cc->sibling_prev->child->sibling_next = call;
- }
- gpr_mu_unlock(&pc->child_list_mu);
- }
-
- if (error != GRPC_ERROR_NONE) {
+
+ GRPC_CALL_INTERNAL_REF(args->parent, "child");
+ GPR_ASSERT(call->is_client);
+ GPR_ASSERT(!args->parent->is_client);
+
+ if (args->propagation_mask & GRPC_PROPAGATE_DEADLINE) {
+ send_deadline = GPR_MIN(send_deadline, args->parent->send_deadline);
+ }
+ /* for now GRPC_PROPAGATE_TRACING_CONTEXT *MUST* be passed with
+ * GRPC_PROPAGATE_STATS_CONTEXT */
+ /* TODO(ctiller): This should change to use the appropriate census start_op
+ * call. */
+ if (args->propagation_mask & GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT) {
+ if (0 == (args->propagation_mask & GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)) {
+ add_init_error(&error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Census tracing propagation requested "
+ "without Census context propagation"));
+ }
+ grpc_call_context_set(call, GRPC_CONTEXT_TRACING,
+ args->parent->context[GRPC_CONTEXT_TRACING].value,
+ nullptr);
+ } else if (args->propagation_mask & GRPC_PROPAGATE_CENSUS_STATS_CONTEXT) {
+ add_init_error(&error, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Census context propagation requested "
+ "without Census tracing propagation"));
+ }
+ if (args->propagation_mask & GRPC_PROPAGATE_CANCELLATION) {
+ call->cancellation_is_inherited = 1;
+ if (gpr_atm_acq_load(&args->parent->received_final_op_atm)) {
+ immediately_cancel = true;
+ }
+ }
+ }
+ call->send_deadline = send_deadline;
+ /* initial refcount dropped by grpc_call_unref */
+ grpc_call_element_args call_args = {CALL_STACK_FROM_CALL(call),
+ args->server_transport_data,
+ call->context,
+ path,
+ call->start_time,
+ send_deadline,
+ call->arena,
+ &call->call_combiner};
+ add_init_error(&error, grpc_call_stack_init(channel_stack, 1, destroy_call,
+ call, &call_args));
+ // Publish this call to parent only after the call stack has been initialized.
+ if (args->parent != nullptr) {
+ child_call* cc = call->child;
+ parent_call* pc = get_or_create_parent_call(args->parent);
+ gpr_mu_lock(&pc->child_list_mu);
+ if (pc->first_child == nullptr) {
+ pc->first_child = call;
+ cc->sibling_next = cc->sibling_prev = call;
+ } else {
+ cc->sibling_next = pc->first_child;
+ cc->sibling_prev = pc->first_child->child->sibling_prev;
+ cc->sibling_next->child->sibling_prev =
+ cc->sibling_prev->child->sibling_next = call;
+ }
+ gpr_mu_unlock(&pc->child_list_mu);
+ }
+
+ if (error != GRPC_ERROR_NONE) {
cancel_with_error(call, GRPC_ERROR_REF(error));
- }
- if (immediately_cancel) {
+ }
+ if (immediately_cancel) {
cancel_with_error(call, GRPC_ERROR_CANCELLED);
- }
- if (args->cq != nullptr) {
- GPR_ASSERT(args->pollset_set_alternative == nullptr &&
- "Only one of 'cq' and 'pollset_set_alternative' should be "
- "non-nullptr.");
- GRPC_CQ_INTERNAL_REF(args->cq, "bind");
- call->pollent =
- grpc_polling_entity_create_from_pollset(grpc_cq_pollset(args->cq));
- }
- if (args->pollset_set_alternative != nullptr) {
- call->pollent = grpc_polling_entity_create_from_pollset_set(
- args->pollset_set_alternative);
- }
- if (!grpc_polling_entity_is_empty(&call->pollent)) {
- grpc_call_stack_set_pollset_or_pollset_set(CALL_STACK_FROM_CALL(call),
- &call->pollent);
- }
-
+ }
+ if (args->cq != nullptr) {
+ GPR_ASSERT(args->pollset_set_alternative == nullptr &&
+ "Only one of 'cq' and 'pollset_set_alternative' should be "
+ "non-nullptr.");
+ GRPC_CQ_INTERNAL_REF(args->cq, "bind");
+ call->pollent =
+ grpc_polling_entity_create_from_pollset(grpc_cq_pollset(args->cq));
+ }
+ if (args->pollset_set_alternative != nullptr) {
+ call->pollent = grpc_polling_entity_create_from_pollset_set(
+ args->pollset_set_alternative);
+ }
+ if (!grpc_polling_entity_is_empty(&call->pollent)) {
+ grpc_call_stack_set_pollset_or_pollset_set(CALL_STACK_FROM_CALL(call),
+ &call->pollent);
+ }
+
if (call->is_client) {
grpc_core::channelz::ChannelNode* channelz_channel =
grpc_channel_get_channelz_node(call->channel);
@@ -486,261 +486,261 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args,
}
}
- grpc_slice_unref_internal(path);
-
- return error;
-}
-
-void grpc_call_set_completion_queue(grpc_call* call,
- grpc_completion_queue* cq) {
- GPR_ASSERT(cq);
-
- if (grpc_polling_entity_pollset_set(&call->pollent) != nullptr) {
- gpr_log(GPR_ERROR, "A pollset_set is already registered for this call.");
- abort();
- }
- call->cq = cq;
- GRPC_CQ_INTERNAL_REF(cq, "bind");
- call->pollent = grpc_polling_entity_create_from_pollset(grpc_cq_pollset(cq));
- grpc_call_stack_set_pollset_or_pollset_set(CALL_STACK_FROM_CALL(call),
- &call->pollent);
-}
-
-#ifndef NDEBUG
-#define REF_REASON reason
-#define REF_ARG , const char* reason
-#else
-#define REF_REASON ""
-#define REF_ARG
-#endif
-void grpc_call_internal_ref(grpc_call* c REF_ARG) {
- GRPC_CALL_STACK_REF(CALL_STACK_FROM_CALL(c), REF_REASON);
-}
-void grpc_call_internal_unref(grpc_call* c REF_ARG) {
- GRPC_CALL_STACK_UNREF(CALL_STACK_FROM_CALL(c), REF_REASON);
-}
-
+ grpc_slice_unref_internal(path);
+
+ return error;
+}
+
+void grpc_call_set_completion_queue(grpc_call* call,
+ grpc_completion_queue* cq) {
+ GPR_ASSERT(cq);
+
+ if (grpc_polling_entity_pollset_set(&call->pollent) != nullptr) {
+ gpr_log(GPR_ERROR, "A pollset_set is already registered for this call.");
+ abort();
+ }
+ call->cq = cq;
+ GRPC_CQ_INTERNAL_REF(cq, "bind");
+ call->pollent = grpc_polling_entity_create_from_pollset(grpc_cq_pollset(cq));
+ grpc_call_stack_set_pollset_or_pollset_set(CALL_STACK_FROM_CALL(call),
+ &call->pollent);
+}
+
+#ifndef NDEBUG
+#define REF_REASON reason
+#define REF_ARG , const char* reason
+#else
+#define REF_REASON ""
+#define REF_ARG
+#endif
+void grpc_call_internal_ref(grpc_call* c REF_ARG) {
+ GRPC_CALL_STACK_REF(CALL_STACK_FROM_CALL(c), REF_REASON);
+}
+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*/) {
- grpc_call* c = static_cast<grpc_call*>(call);
- grpc_channel* channel = c->channel;
+ grpc_call* c = static_cast<grpc_call*>(call);
+ grpc_channel* channel = c->channel;
grpc_core::Arena* arena = c->arena;
c->~grpc_call();
grpc_channel_update_call_size_estimate(channel, arena->Destroy());
- GRPC_CHANNEL_INTERNAL_UNREF(channel, "call");
-}
-
+ GRPC_CHANNEL_INTERNAL_UNREF(channel, "call");
+}
+
static void destroy_call(void* call, grpc_error* /*error*/) {
- GPR_TIMER_SCOPE("destroy_call", 0);
- size_t i;
- int ii;
- grpc_call* c = static_cast<grpc_call*>(call);
- for (i = 0; i < 2; i++) {
- grpc_metadata_batch_destroy(
- &c->metadata_batch[1 /* is_receiving */][i /* is_initial */]);
- }
- c->receiving_stream.reset();
- parent_call* pc = get_parent_call(c);
- if (pc != nullptr) {
+ GPR_TIMER_SCOPE("destroy_call", 0);
+ size_t i;
+ int ii;
+ grpc_call* c = static_cast<grpc_call*>(call);
+ for (i = 0; i < 2; i++) {
+ grpc_metadata_batch_destroy(
+ &c->metadata_batch[1 /* is_receiving */][i /* is_initial */]);
+ }
+ c->receiving_stream.reset();
+ parent_call* pc = get_parent_call(c);
+ if (pc != nullptr) {
pc->~parent_call();
- }
- for (ii = 0; ii < c->send_extra_metadata_count; ii++) {
- GRPC_MDELEM_UNREF(c->send_extra_metadata[ii].md);
- }
- for (i = 0; i < GRPC_CONTEXT_COUNT; i++) {
- if (c->context[i].destroy) {
- c->context[i].destroy(c->context[i].value);
- }
- }
- if (c->cq) {
- GRPC_CQ_INTERNAL_UNREF(c->cq, "bind");
- }
-
+ }
+ for (ii = 0; ii < c->send_extra_metadata_count; ii++) {
+ GRPC_MDELEM_UNREF(c->send_extra_metadata[ii].md);
+ }
+ for (i = 0; i < GRPC_CONTEXT_COUNT; i++) {
+ if (c->context[i].destroy) {
+ c->context[i].destroy(c->context[i].value);
+ }
+ }
+ if (c->cq) {
+ GRPC_CQ_INTERNAL_UNREF(c->cq, "bind");
+ }
+
grpc_error* status_error =
reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&c->status_error));
grpc_error_get_status(status_error, c->send_deadline,
&c->final_info.final_status, nullptr, nullptr,
&(c->final_info.error_string));
GRPC_ERROR_UNREF(status_error);
- c->final_info.stats.latency =
+ c->final_info.stats.latency =
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));
-}
-
+ 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_unref(grpc_call* c) {
+
+void grpc_call_unref(grpc_call* c) {
if (GPR_LIKELY(!c->ext_ref.Unref())) return;
-
- GPR_TIMER_SCOPE("grpc_call_unref", 0);
-
- child_call* cc = c->child;
+
+ GPR_TIMER_SCOPE("grpc_call_unref", 0);
+
+ child_call* cc = c->child;
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
-
- GRPC_API_TRACE("grpc_call_unref(c=%p)", 1, (c));
-
- if (cc) {
- parent_call* pc = get_parent_call(cc->parent);
- gpr_mu_lock(&pc->child_list_mu);
- if (c == pc->first_child) {
- pc->first_child = cc->sibling_next;
- if (c == pc->first_child) {
- pc->first_child = nullptr;
- }
- }
- cc->sibling_prev->child->sibling_next = cc->sibling_next;
- cc->sibling_next->child->sibling_prev = cc->sibling_prev;
- gpr_mu_unlock(&pc->child_list_mu);
- GRPC_CALL_INTERNAL_UNREF(cc->parent, "child");
- }
-
- GPR_ASSERT(!c->destroy_called);
- c->destroy_called = 1;
- bool cancel = gpr_atm_acq_load(&c->any_ops_sent_atm) != 0 &&
- gpr_atm_acq_load(&c->received_final_op_atm) == 0;
- if (cancel) {
+ grpc_core::ExecCtx exec_ctx;
+
+ GRPC_API_TRACE("grpc_call_unref(c=%p)", 1, (c));
+
+ if (cc) {
+ parent_call* pc = get_parent_call(cc->parent);
+ gpr_mu_lock(&pc->child_list_mu);
+ if (c == pc->first_child) {
+ pc->first_child = cc->sibling_next;
+ if (c == pc->first_child) {
+ pc->first_child = nullptr;
+ }
+ }
+ cc->sibling_prev->child->sibling_next = cc->sibling_next;
+ cc->sibling_next->child->sibling_prev = cc->sibling_prev;
+ gpr_mu_unlock(&pc->child_list_mu);
+ GRPC_CALL_INTERNAL_UNREF(cc->parent, "child");
+ }
+
+ GPR_ASSERT(!c->destroy_called);
+ c->destroy_called = 1;
+ bool cancel = gpr_atm_acq_load(&c->any_ops_sent_atm) != 0 &&
+ gpr_atm_acq_load(&c->received_final_op_atm) == 0;
+ if (cancel) {
cancel_with_error(c, GRPC_ERROR_CANCELLED);
- } else {
- // Unset the call combiner cancellation closure. This has the
- // effect of scheduling the previously set cancellation closure, if
- // any, so that it can release any internal references it may be
+ } else {
+ // Unset the call combiner cancellation closure. This has the
+ // effect of scheduling the previously set cancellation closure, if
+ // any, so that it can release any internal references it may be
// 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);
grpc_core::ExecCtx::Get()->Flush();
- }
- GRPC_CALL_INTERNAL_UNREF(c, "destroy");
-}
-
-grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved) {
- GRPC_API_TRACE("grpc_call_cancel(call=%p, reserved=%p)", 2, (call, reserved));
- GPR_ASSERT(!reserved);
+ }
+ GRPC_CALL_INTERNAL_UNREF(c, "destroy");
+}
+
+grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved) {
+ GRPC_API_TRACE("grpc_call_cancel(call=%p, reserved=%p)", 2, (call, reserved));
+ GPR_ASSERT(!reserved);
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
cancel_with_error(call, GRPC_ERROR_CANCELLED);
- return GRPC_CALL_OK;
-}
-
-// This is called via the call combiner to start sending a batch down
-// the filter stack.
+ return GRPC_CALL_OK;
+}
+
+// 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*/) {
- GPR_TIMER_SCOPE("execute_batch_in_call_combiner", 0);
- grpc_transport_stream_op_batch* batch =
- static_cast<grpc_transport_stream_op_batch*>(arg);
- grpc_call* call = static_cast<grpc_call*>(batch->handler_private.extra_arg);
- grpc_call_element* elem = CALL_ELEM_FROM_CALL(call, 0);
- GRPC_CALL_LOG_OP(GPR_INFO, elem, batch);
- elem->filter->start_transport_stream_op_batch(elem, batch);
-}
-
-// start_batch_closure points to a caller-allocated closure to be used
-// for entering the call combiner.
-static void execute_batch(grpc_call* call,
- grpc_transport_stream_op_batch* batch,
- grpc_closure* start_batch_closure) {
- batch->handler_private.extra_arg = call;
- GRPC_CLOSURE_INIT(start_batch_closure, execute_batch_in_call_combiner, batch,
- grpc_schedule_on_exec_ctx);
- GRPC_CALL_COMBINER_START(&call->call_combiner, start_batch_closure,
- GRPC_ERROR_NONE, "executing batch");
-}
-
-char* grpc_call_get_peer(grpc_call* call) {
- char* peer_string = (char*)gpr_atm_acq_load(&call->peer_string);
- if (peer_string != nullptr) return gpr_strdup(peer_string);
- peer_string = grpc_channel_get_target(call->channel);
- if (peer_string != nullptr) return peer_string;
- return gpr_strdup("unknown");
-}
-
-grpc_call* grpc_call_from_top_element(grpc_call_element* elem) {
- return CALL_FROM_TOP_ELEM(elem);
-}
-
-/*******************************************************************************
- * CANCELLATION
- */
-
-grpc_call_error grpc_call_cancel_with_status(grpc_call* c,
- grpc_status_code status,
- const char* description,
- void* reserved) {
+ GPR_TIMER_SCOPE("execute_batch_in_call_combiner", 0);
+ grpc_transport_stream_op_batch* batch =
+ static_cast<grpc_transport_stream_op_batch*>(arg);
+ grpc_call* call = static_cast<grpc_call*>(batch->handler_private.extra_arg);
+ grpc_call_element* elem = CALL_ELEM_FROM_CALL(call, 0);
+ GRPC_CALL_LOG_OP(GPR_INFO, elem, batch);
+ elem->filter->start_transport_stream_op_batch(elem, batch);
+}
+
+// start_batch_closure points to a caller-allocated closure to be used
+// for entering the call combiner.
+static void execute_batch(grpc_call* call,
+ grpc_transport_stream_op_batch* batch,
+ grpc_closure* start_batch_closure) {
+ batch->handler_private.extra_arg = call;
+ GRPC_CLOSURE_INIT(start_batch_closure, execute_batch_in_call_combiner, batch,
+ grpc_schedule_on_exec_ctx);
+ GRPC_CALL_COMBINER_START(&call->call_combiner, start_batch_closure,
+ GRPC_ERROR_NONE, "executing batch");
+}
+
+char* grpc_call_get_peer(grpc_call* call) {
+ char* peer_string = (char*)gpr_atm_acq_load(&call->peer_string);
+ if (peer_string != nullptr) return gpr_strdup(peer_string);
+ peer_string = grpc_channel_get_target(call->channel);
+ if (peer_string != nullptr) return peer_string;
+ return gpr_strdup("unknown");
+}
+
+grpc_call* grpc_call_from_top_element(grpc_call_element* elem) {
+ return CALL_FROM_TOP_ELEM(elem);
+}
+
+/*******************************************************************************
+ * CANCELLATION
+ */
+
+grpc_call_error grpc_call_cancel_with_status(grpc_call* c,
+ grpc_status_code status,
+ const char* description,
+ void* reserved) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE(
- "grpc_call_cancel_with_status("
- "c=%p, status=%d, description=%s, reserved=%p)",
- 4, (c, (int)status, description, reserved));
- GPR_ASSERT(reserved == nullptr);
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE(
+ "grpc_call_cancel_with_status("
+ "c=%p, status=%d, description=%s, reserved=%p)",
+ 4, (c, (int)status, description, reserved));
+ GPR_ASSERT(reserved == nullptr);
cancel_with_status(c, status, description);
- return GRPC_CALL_OK;
-}
-
+ return GRPC_CALL_OK;
+}
+
struct cancel_state {
- grpc_call* call;
- grpc_closure start_batch;
- grpc_closure finish_batch;
+ grpc_call* call;
+ grpc_closure start_batch;
+ grpc_closure finish_batch;
};
-// The on_complete callback used when sending a cancel_stream batch down
-// the filter stack. Yields the call combiner when the batch is done.
+// 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*/) {
- cancel_state* state = static_cast<cancel_state*>(arg);
- GRPC_CALL_COMBINER_STOP(&state->call->call_combiner,
- "on_complete for cancel_stream op");
- GRPC_CALL_INTERNAL_UNREF(state->call, "termination");
- gpr_free(state);
-}
-
+ cancel_state* state = static_cast<cancel_state*>(arg);
+ GRPC_CALL_COMBINER_STOP(&state->call->call_combiner,
+ "on_complete for cancel_stream op");
+ GRPC_CALL_INTERNAL_UNREF(state->call, "termination");
+ gpr_free(state);
+}
+
static void cancel_with_error(grpc_call* c, grpc_error* error) {
if (!gpr_atm_rel_cas(&c->cancelled_with_error, 0, 1)) {
GRPC_ERROR_UNREF(error);
return;
}
- GRPC_CALL_INTERNAL_REF(c, "termination");
- // Inform the call combiner of the cancellation, so that it can cancel
- // 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.
+ GRPC_CALL_INTERNAL_REF(c, "termination");
+ // Inform the call combiner of the cancellation, so that it can cancel
+ // 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));
- cancel_state* state = static_cast<cancel_state*>(gpr_malloc(sizeof(*state)));
- state->call = c;
- GRPC_CLOSURE_INIT(&state->finish_batch, done_termination, state,
- grpc_schedule_on_exec_ctx);
- grpc_transport_stream_op_batch* op =
- grpc_make_transport_stream_op(&state->finish_batch);
- op->cancel_stream = true;
- op->payload->cancel_stream.cancel_error = error;
- execute_batch(c, op, &state->start_batch);
-}
-
+ cancel_state* state = static_cast<cancel_state*>(gpr_malloc(sizeof(*state)));
+ state->call = c;
+ GRPC_CLOSURE_INIT(&state->finish_batch, done_termination, state,
+ grpc_schedule_on_exec_ctx);
+ grpc_transport_stream_op_batch* op =
+ grpc_make_transport_stream_op(&state->finish_batch);
+ op->cancel_stream = true;
+ op->payload->cancel_stream.cancel_error = error;
+ execute_batch(c, op, &state->start_batch);
+}
+
void grpc_call_cancel_internal(grpc_call* call) {
cancel_with_error(call, GRPC_ERROR_CANCELLED);
}
-static grpc_error* error_from_status(grpc_status_code status,
- const char* description) {
- // copying 'description' is needed to ensure the grpc_call_cancel_with_status
- // guarantee that can be short-lived.
- return grpc_error_set_int(
- grpc_error_set_str(GRPC_ERROR_CREATE_FROM_COPIED_STRING(description),
- GRPC_ERROR_STR_GRPC_MESSAGE,
- grpc_slice_from_copied_string(description)),
- GRPC_ERROR_INT_GRPC_STATUS, status);
-}
-
+static grpc_error* error_from_status(grpc_status_code status,
+ const char* description) {
+ // copying 'description' is needed to ensure the grpc_call_cancel_with_status
+ // guarantee that can be short-lived.
+ return grpc_error_set_int(
+ grpc_error_set_str(GRPC_ERROR_CREATE_FROM_COPIED_STRING(description),
+ GRPC_ERROR_STR_GRPC_MESSAGE,
+ grpc_slice_from_copied_string(description)),
+ GRPC_ERROR_INT_GRPC_STATUS, status);
+}
+
static void cancel_with_status(grpc_call* c, grpc_status_code status,
- const char* description) {
+ const char* description) {
cancel_with_error(c, error_from_status(status, description));
-}
-
+}
+
static void set_final_status(grpc_call* call, grpc_error* error) {
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));
- }
+ }
if (call->is_client) {
grpc_error_get_status(error, call->send_deadline,
call->final_op.client.status,
@@ -756,8 +756,8 @@ static void set_final_status(grpc_call* call, grpc_error* error) {
channelz_channel->RecordCallFailed();
} else {
channelz_channel->RecordCallSucceeded();
- }
- }
+ }
+ }
} else {
*call->final_op.server.cancelled =
error != GRPC_ERROR_NONE || !call->sent_server_trailing_metadata;
@@ -770,292 +770,292 @@ static void set_final_status(grpc_call* call, grpc_error* error) {
channelz_node->RecordCallFailed();
} else {
channelz_node->RecordCallSucceeded();
- }
- }
- GRPC_ERROR_UNREF(error);
- }
-}
-
-/*******************************************************************************
- * COMPRESSION
- */
-
-static void set_incoming_message_compression_algorithm(
- grpc_call* call, grpc_message_compression_algorithm algo) {
- GPR_ASSERT(algo < GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT);
- call->incoming_message_compression_algorithm = algo;
-}
-
-static void set_incoming_stream_compression_algorithm(
- grpc_call* call, grpc_stream_compression_algorithm algo) {
- GPR_ASSERT(algo < GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT);
- call->incoming_stream_compression_algorithm = algo;
-}
-
-grpc_compression_algorithm grpc_call_test_only_get_compression_algorithm(
- grpc_call* call) {
- grpc_compression_algorithm algorithm = GRPC_COMPRESS_NONE;
- grpc_compression_algorithm_from_message_stream_compression_algorithm(
- &algorithm, call->incoming_message_compression_algorithm,
- call->incoming_stream_compression_algorithm);
- return algorithm;
-}
-
-static grpc_compression_algorithm compression_algorithm_for_level_locked(
- grpc_call* call, grpc_compression_level level) {
- return grpc_compression_algorithm_for_level(level,
- call->encodings_accepted_by_peer);
-}
-
-uint32_t grpc_call_test_only_get_message_flags(grpc_call* call) {
- uint32_t flags;
- flags = call->test_only_last_message_flags;
- return flags;
-}
-
+ }
+ }
+ GRPC_ERROR_UNREF(error);
+ }
+}
+
+/*******************************************************************************
+ * COMPRESSION
+ */
+
+static void set_incoming_message_compression_algorithm(
+ grpc_call* call, grpc_message_compression_algorithm algo) {
+ GPR_ASSERT(algo < GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT);
+ call->incoming_message_compression_algorithm = algo;
+}
+
+static void set_incoming_stream_compression_algorithm(
+ grpc_call* call, grpc_stream_compression_algorithm algo) {
+ GPR_ASSERT(algo < GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT);
+ call->incoming_stream_compression_algorithm = algo;
+}
+
+grpc_compression_algorithm grpc_call_test_only_get_compression_algorithm(
+ grpc_call* call) {
+ grpc_compression_algorithm algorithm = GRPC_COMPRESS_NONE;
+ grpc_compression_algorithm_from_message_stream_compression_algorithm(
+ &algorithm, call->incoming_message_compression_algorithm,
+ call->incoming_stream_compression_algorithm);
+ return algorithm;
+}
+
+static grpc_compression_algorithm compression_algorithm_for_level_locked(
+ grpc_call* call, grpc_compression_level level) {
+ return grpc_compression_algorithm_for_level(level,
+ call->encodings_accepted_by_peer);
+}
+
+uint32_t grpc_call_test_only_get_message_flags(grpc_call* call) {
+ uint32_t flags;
+ flags = call->test_only_last_message_flags;
+ return flags;
+}
+
static void destroy_encodings_accepted_by_peer(void* /*p*/) { return; }
-
+
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;
- uint32_t algorithm;
- grpc_slice_buffer accept_encoding_parts;
- grpc_slice accept_encoding_slice;
- void* accepted_user_data;
-
- accepted_user_data =
- grpc_mdelem_get_user_data(mdel, destroy_encodings_accepted_by_peer);
- if (accepted_user_data != nullptr) {
- *encodings_accepted_by_peer =
- static_cast<uint32_t>(((uintptr_t)accepted_user_data) - 1);
- return;
- }
-
- *encodings_accepted_by_peer = 0;
-
- accept_encoding_slice = GRPC_MDVALUE(mdel);
- grpc_slice_buffer_init(&accept_encoding_parts);
- grpc_slice_split_without_space(accept_encoding_slice, ",",
- &accept_encoding_parts);
-
- GPR_BITSET(encodings_accepted_by_peer, GRPC_COMPRESS_NONE);
- for (i = 0; i < accept_encoding_parts.count; i++) {
- int r;
- grpc_slice accept_encoding_entry_slice = accept_encoding_parts.slices[i];
- if (!stream_encoding) {
- r = grpc_message_compression_algorithm_parse(
- accept_encoding_entry_slice,
- reinterpret_cast<grpc_message_compression_algorithm*>(&algorithm));
- } else {
- r = grpc_stream_compression_algorithm_parse(
- accept_encoding_entry_slice,
- reinterpret_cast<grpc_stream_compression_algorithm*>(&algorithm));
- }
- if (r) {
- GPR_BITSET(encodings_accepted_by_peer, algorithm);
- } else {
- char* accept_encoding_entry_str =
- grpc_slice_to_c_string(accept_encoding_entry_slice);
- gpr_log(GPR_DEBUG,
- "Unknown entry in accept encoding metadata: '%s'. Ignoring.",
- accept_encoding_entry_str);
- gpr_free(accept_encoding_entry_str);
- }
- }
-
- grpc_slice_buffer_destroy_internal(&accept_encoding_parts);
-
- grpc_mdelem_set_user_data(
- mdel, destroy_encodings_accepted_by_peer,
- (void*)((static_cast<uintptr_t>(*encodings_accepted_by_peer)) + 1));
-}
-
-uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call* call) {
- uint32_t encodings_accepted_by_peer;
- encodings_accepted_by_peer = call->encodings_accepted_by_peer;
- return encodings_accepted_by_peer;
-}
-
-grpc_stream_compression_algorithm
-grpc_call_test_only_get_incoming_stream_encodings(grpc_call* call) {
- return call->incoming_stream_compression_algorithm;
-}
-
-static grpc_linked_mdelem* linked_from_md(const grpc_metadata* md) {
- return (grpc_linked_mdelem*)&md->internal_data;
-}
-
-static grpc_metadata* get_md_elem(grpc_metadata* metadata,
- grpc_metadata* additional_metadata, int i,
- int count) {
- grpc_metadata* res =
- i < count ? &metadata[i] : &additional_metadata[i - count];
- GPR_ASSERT(res);
- return res;
-}
-
-static int prepare_application_metadata(grpc_call* call, int count,
- grpc_metadata* metadata,
- int is_trailing,
- int prepend_extra_metadata,
- grpc_metadata* additional_metadata,
- int additional_metadata_count) {
- int total_count = count + additional_metadata_count;
- int i;
- grpc_metadata_batch* batch =
- &call->metadata_batch[0 /* is_receiving */][is_trailing];
- for (i = 0; i < total_count; i++) {
- const grpc_metadata* md =
- get_md_elem(metadata, additional_metadata, i, count);
- grpc_linked_mdelem* l = linked_from_md(md);
- GPR_ASSERT(sizeof(grpc_linked_mdelem) == sizeof(md->internal_data));
- if (!GRPC_LOG_IF_ERROR("validate_metadata",
- grpc_validate_header_key_is_legal(md->key))) {
- break;
+ uint32_t* encodings_accepted_by_peer,
+ bool stream_encoding) {
+ size_t i;
+ uint32_t algorithm;
+ grpc_slice_buffer accept_encoding_parts;
+ grpc_slice accept_encoding_slice;
+ void* accepted_user_data;
+
+ accepted_user_data =
+ grpc_mdelem_get_user_data(mdel, destroy_encodings_accepted_by_peer);
+ if (accepted_user_data != nullptr) {
+ *encodings_accepted_by_peer =
+ static_cast<uint32_t>(((uintptr_t)accepted_user_data) - 1);
+ return;
+ }
+
+ *encodings_accepted_by_peer = 0;
+
+ accept_encoding_slice = GRPC_MDVALUE(mdel);
+ grpc_slice_buffer_init(&accept_encoding_parts);
+ grpc_slice_split_without_space(accept_encoding_slice, ",",
+ &accept_encoding_parts);
+
+ GPR_BITSET(encodings_accepted_by_peer, GRPC_COMPRESS_NONE);
+ for (i = 0; i < accept_encoding_parts.count; i++) {
+ int r;
+ grpc_slice accept_encoding_entry_slice = accept_encoding_parts.slices[i];
+ if (!stream_encoding) {
+ r = grpc_message_compression_algorithm_parse(
+ accept_encoding_entry_slice,
+ reinterpret_cast<grpc_message_compression_algorithm*>(&algorithm));
+ } else {
+ r = grpc_stream_compression_algorithm_parse(
+ accept_encoding_entry_slice,
+ reinterpret_cast<grpc_stream_compression_algorithm*>(&algorithm));
+ }
+ if (r) {
+ GPR_BITSET(encodings_accepted_by_peer, algorithm);
+ } else {
+ char* accept_encoding_entry_str =
+ grpc_slice_to_c_string(accept_encoding_entry_slice);
+ gpr_log(GPR_DEBUG,
+ "Unknown entry in accept encoding metadata: '%s'. Ignoring.",
+ accept_encoding_entry_str);
+ gpr_free(accept_encoding_entry_str);
+ }
+ }
+
+ grpc_slice_buffer_destroy_internal(&accept_encoding_parts);
+
+ grpc_mdelem_set_user_data(
+ mdel, destroy_encodings_accepted_by_peer,
+ (void*)((static_cast<uintptr_t>(*encodings_accepted_by_peer)) + 1));
+}
+
+uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call* call) {
+ uint32_t encodings_accepted_by_peer;
+ encodings_accepted_by_peer = call->encodings_accepted_by_peer;
+ return encodings_accepted_by_peer;
+}
+
+grpc_stream_compression_algorithm
+grpc_call_test_only_get_incoming_stream_encodings(grpc_call* call) {
+ return call->incoming_stream_compression_algorithm;
+}
+
+static grpc_linked_mdelem* linked_from_md(const grpc_metadata* md) {
+ return (grpc_linked_mdelem*)&md->internal_data;
+}
+
+static grpc_metadata* get_md_elem(grpc_metadata* metadata,
+ grpc_metadata* additional_metadata, int i,
+ int count) {
+ grpc_metadata* res =
+ i < count ? &metadata[i] : &additional_metadata[i - count];
+ GPR_ASSERT(res);
+ return res;
+}
+
+static int prepare_application_metadata(grpc_call* call, int count,
+ grpc_metadata* metadata,
+ int is_trailing,
+ int prepend_extra_metadata,
+ grpc_metadata* additional_metadata,
+ int additional_metadata_count) {
+ int total_count = count + additional_metadata_count;
+ int i;
+ grpc_metadata_batch* batch =
+ &call->metadata_batch[0 /* is_receiving */][is_trailing];
+ for (i = 0; i < total_count; i++) {
+ const grpc_metadata* md =
+ get_md_elem(metadata, additional_metadata, i, count);
+ grpc_linked_mdelem* l = linked_from_md(md);
+ GPR_ASSERT(sizeof(grpc_linked_mdelem) == sizeof(md->internal_data));
+ 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) &&
- !GRPC_LOG_IF_ERROR(
- "validate_metadata",
- grpc_validate_header_nonbin_value_is_legal(md->value))) {
- break;
+ !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;
- }
- l->md = grpc_mdelem_from_grpc_metadata(const_cast<grpc_metadata*>(md));
- }
- if (i != total_count) {
- for (int j = 0; j < i; j++) {
- const grpc_metadata* md =
- get_md_elem(metadata, additional_metadata, j, count);
- grpc_linked_mdelem* l = linked_from_md(md);
- GRPC_MDELEM_UNREF(l->md);
- }
- return 0;
- }
- if (prepend_extra_metadata) {
- if (call->send_extra_metadata_count == 0) {
- prepend_extra_metadata = 0;
- } else {
- for (i = 0; i < call->send_extra_metadata_count; i++) {
- GRPC_LOG_IF_ERROR("prepare_application_metadata",
- grpc_metadata_batch_link_tail(
- batch, &call->send_extra_metadata[i]));
- }
- }
- }
- for (i = 0; i < total_count; i++) {
- grpc_metadata* md = get_md_elem(metadata, additional_metadata, i, count);
- grpc_linked_mdelem* l = linked_from_md(md);
- grpc_error* error = grpc_metadata_batch_link_tail(batch, l);
- if (error != GRPC_ERROR_NONE) {
- GRPC_MDELEM_UNREF(l->md);
- }
- GRPC_LOG_IF_ERROR("prepare_application_metadata", error);
- }
- call->send_extra_metadata_count = 0;
-
- return 1;
-}
-
-static grpc_message_compression_algorithm decode_message_compression(
- grpc_mdelem md) {
- grpc_message_compression_algorithm algorithm =
- grpc_message_compression_algorithm_from_slice(GRPC_MDVALUE(md));
- if (algorithm == GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) {
- char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md));
- gpr_log(GPR_ERROR,
- "Invalid incoming message compression algorithm: '%s'. "
- "Interpreting incoming data as uncompressed.",
- md_c_str);
- gpr_free(md_c_str);
- return GRPC_MESSAGE_COMPRESS_NONE;
- }
- return algorithm;
-}
-
-static grpc_stream_compression_algorithm decode_stream_compression(
- grpc_mdelem md) {
- grpc_stream_compression_algorithm algorithm =
- grpc_stream_compression_algorithm_from_slice(GRPC_MDVALUE(md));
- if (algorithm == GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT) {
- char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md));
- gpr_log(GPR_ERROR,
- "Invalid incoming stream compression algorithm: '%s'. Interpreting "
- "incoming data as uncompressed.",
- md_c_str);
- gpr_free(md_c_str);
- return GRPC_STREAM_COMPRESS_NONE;
- }
- return algorithm;
-}
-
-static void publish_app_metadata(grpc_call* call, grpc_metadata_batch* b,
- int is_trailing) {
- if (b->list.count == 0) return;
+ }
+ l->md = grpc_mdelem_from_grpc_metadata(const_cast<grpc_metadata*>(md));
+ }
+ if (i != total_count) {
+ for (int j = 0; j < i; j++) {
+ const grpc_metadata* md =
+ get_md_elem(metadata, additional_metadata, j, count);
+ grpc_linked_mdelem* l = linked_from_md(md);
+ GRPC_MDELEM_UNREF(l->md);
+ }
+ return 0;
+ }
+ if (prepend_extra_metadata) {
+ if (call->send_extra_metadata_count == 0) {
+ prepend_extra_metadata = 0;
+ } else {
+ for (i = 0; i < call->send_extra_metadata_count; i++) {
+ GRPC_LOG_IF_ERROR("prepare_application_metadata",
+ grpc_metadata_batch_link_tail(
+ batch, &call->send_extra_metadata[i]));
+ }
+ }
+ }
+ for (i = 0; i < total_count; i++) {
+ grpc_metadata* md = get_md_elem(metadata, additional_metadata, i, count);
+ grpc_linked_mdelem* l = linked_from_md(md);
+ grpc_error* error = grpc_metadata_batch_link_tail(batch, l);
+ if (error != GRPC_ERROR_NONE) {
+ GRPC_MDELEM_UNREF(l->md);
+ }
+ GRPC_LOG_IF_ERROR("prepare_application_metadata", error);
+ }
+ call->send_extra_metadata_count = 0;
+
+ return 1;
+}
+
+static grpc_message_compression_algorithm decode_message_compression(
+ grpc_mdelem md) {
+ grpc_message_compression_algorithm algorithm =
+ grpc_message_compression_algorithm_from_slice(GRPC_MDVALUE(md));
+ if (algorithm == GRPC_MESSAGE_COMPRESS_ALGORITHMS_COUNT) {
+ char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md));
+ gpr_log(GPR_ERROR,
+ "Invalid incoming message compression algorithm: '%s'. "
+ "Interpreting incoming data as uncompressed.",
+ md_c_str);
+ gpr_free(md_c_str);
+ return GRPC_MESSAGE_COMPRESS_NONE;
+ }
+ return algorithm;
+}
+
+static grpc_stream_compression_algorithm decode_stream_compression(
+ grpc_mdelem md) {
+ grpc_stream_compression_algorithm algorithm =
+ grpc_stream_compression_algorithm_from_slice(GRPC_MDVALUE(md));
+ if (algorithm == GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT) {
+ char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md));
+ gpr_log(GPR_ERROR,
+ "Invalid incoming stream compression algorithm: '%s'. Interpreting "
+ "incoming data as uncompressed.",
+ md_c_str);
+ gpr_free(md_c_str);
+ return GRPC_STREAM_COMPRESS_NONE;
+ }
+ return algorithm;
+}
+
+static void publish_app_metadata(grpc_call* call, grpc_metadata_batch* b,
+ int is_trailing) {
+ if (b->list.count == 0) return;
if (!call->is_client && is_trailing) return;
- if (is_trailing && call->buffered_metadata[1] == nullptr) return;
- GPR_TIMER_SCOPE("publish_app_metadata", 0);
- grpc_metadata_array* dest;
- grpc_metadata* mdusr;
- dest = call->buffered_metadata[is_trailing];
- if (dest->count + b->list.count > dest->capacity) {
- dest->capacity =
- GPR_MAX(dest->capacity + b->list.count, dest->capacity * 3 / 2);
- dest->metadata = static_cast<grpc_metadata*>(
- gpr_realloc(dest->metadata, sizeof(grpc_metadata) * dest->capacity));
- }
- for (grpc_linked_mdelem* l = b->list.head; l != nullptr; l = l->next) {
- mdusr = &dest->metadata[dest->count++];
- /* we pass back borrowed slices that are valid whilst the call is valid */
- mdusr->key = GRPC_MDKEY(l->md);
- mdusr->value = GRPC_MDVALUE(l->md);
- }
-}
-
-static void recv_initial_filter(grpc_call* call, grpc_metadata_batch* b) {
- if (b->idx.named.content_encoding != nullptr) {
- GPR_TIMER_SCOPE("incoming_stream_compression_algorithm", 0);
- set_incoming_stream_compression_algorithm(
- call, decode_stream_compression(b->idx.named.content_encoding->md));
+ if (is_trailing && call->buffered_metadata[1] == nullptr) return;
+ GPR_TIMER_SCOPE("publish_app_metadata", 0);
+ grpc_metadata_array* dest;
+ grpc_metadata* mdusr;
+ dest = call->buffered_metadata[is_trailing];
+ if (dest->count + b->list.count > dest->capacity) {
+ dest->capacity =
+ GPR_MAX(dest->capacity + b->list.count, dest->capacity * 3 / 2);
+ dest->metadata = static_cast<grpc_metadata*>(
+ gpr_realloc(dest->metadata, sizeof(grpc_metadata) * dest->capacity));
+ }
+ for (grpc_linked_mdelem* l = b->list.head; l != nullptr; l = l->next) {
+ mdusr = &dest->metadata[dest->count++];
+ /* we pass back borrowed slices that are valid whilst the call is valid */
+ mdusr->key = GRPC_MDKEY(l->md);
+ mdusr->value = GRPC_MDVALUE(l->md);
+ }
+}
+
+static void recv_initial_filter(grpc_call* call, grpc_metadata_batch* b) {
+ if (b->idx.named.content_encoding != nullptr) {
+ 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);
- }
- 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));
+ }
+ 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);
- }
- uint32_t message_encodings_accepted_by_peer = 1u;
- uint32_t stream_encodings_accepted_by_peer = 1u;
- if (b->idx.named.grpc_accept_encoding != nullptr) {
- 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);
+ }
+ uint32_t message_encodings_accepted_by_peer = 1u;
+ uint32_t stream_encodings_accepted_by_peer = 1u;
+ if (b->idx.named.grpc_accept_encoding != nullptr) {
+ 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);
- }
- 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);
+ }
+ 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);
- }
- call->encodings_accepted_by_peer =
- grpc_compression_bitset_from_message_stream_compression_bitset(
- message_encodings_accepted_by_peer,
- stream_encodings_accepted_by_peer);
- publish_app_metadata(call, b, false);
-}
-
+ }
+ call->encodings_accepted_by_peer =
+ grpc_compression_bitset_from_message_stream_compression_bitset(
+ message_encodings_accepted_by_peer,
+ stream_encodings_accepted_by_peer);
+ publish_app_metadata(call, b, false);
+}
+
static void recv_trailing_filter(void* args, grpc_metadata_batch* b,
grpc_error* batch_error) {
- grpc_call* call = static_cast<grpc_call*>(args);
+ grpc_call* call = static_cast<grpc_call*>(args);
if (batch_error != GRPC_ERROR_NONE) {
set_final_status(call, batch_error);
} else if (b->idx.named.grpc_status != nullptr) {
- grpc_status_code status_code =
- grpc_get_status_code_from_metadata(b->idx.named.grpc_status->md);
+ grpc_status_code status_code =
+ 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);
@@ -1065,15 +1065,15 @@ static void recv_trailing_filter(void* args, grpc_metadata_batch* b,
GRPC_ERROR_INT_GRPC_STATUS, static_cast<intptr_t>(status_code));
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)));
+ 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);
- } else if (error != GRPC_ERROR_NONE) {
- error = grpc_error_set_str(error, GRPC_ERROR_STR_GRPC_MESSAGE,
- grpc_empty_slice());
- }
+ } 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_ERROR_UNREF(error);
@@ -1086,57 +1086,57 @@ static void recv_trailing_filter(void* args, grpc_metadata_batch* b,
call, grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("No status received"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNKNOWN));
- }
- publish_app_metadata(call, b, true);
-}
-
+ }
+ publish_app_metadata(call, b, true);
+}
+
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);
-}
-
-/*******************************************************************************
- * BATCH API IMPLEMENTATION
- */
-
-static bool are_write_flags_valid(uint32_t flags) {
- /* check that only bits in GRPC_WRITE_(INTERNAL?)_USED_MASK are set */
- const uint32_t allowed_write_positions =
- (GRPC_WRITE_USED_MASK | GRPC_WRITE_INTERNAL_USED_MASK);
- const uint32_t invalid_positions = ~allowed_write_positions;
- return !(flags & invalid_positions);
-}
-
-static bool are_initial_metadata_flags_valid(uint32_t flags, bool is_client) {
- /* check that only bits in GRPC_WRITE_(INTERNAL?)_USED_MASK are set */
- uint32_t invalid_positions = ~GRPC_INITIAL_METADATA_USED_MASK;
- if (!is_client) {
- invalid_positions |= GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
- }
- return !(flags & invalid_positions);
-}
-
+grpc_call_stack* grpc_call_get_call_stack(grpc_call* call) {
+ return CALL_STACK_FROM_CALL(call);
+}
+
+/*******************************************************************************
+ * BATCH API IMPLEMENTATION
+ */
+
+static bool are_write_flags_valid(uint32_t flags) {
+ /* check that only bits in GRPC_WRITE_(INTERNAL?)_USED_MASK are set */
+ const uint32_t allowed_write_positions =
+ (GRPC_WRITE_USED_MASK | GRPC_WRITE_INTERNAL_USED_MASK);
+ const uint32_t invalid_positions = ~allowed_write_positions;
+ return !(flags & invalid_positions);
+}
+
+static bool are_initial_metadata_flags_valid(uint32_t flags, bool is_client) {
+ /* check that only bits in GRPC_WRITE_(INTERNAL?)_USED_MASK are set */
+ uint32_t invalid_positions = ~GRPC_INITIAL_METADATA_USED_MASK;
+ if (!is_client) {
+ invalid_positions |= GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
+ }
+ return !(flags & invalid_positions);
+}
+
static size_t batch_slot_for_op(grpc_op_type type) {
- switch (type) {
- case GRPC_OP_SEND_INITIAL_METADATA:
- return 0;
- case GRPC_OP_SEND_MESSAGE:
- return 1;
- case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
- case GRPC_OP_SEND_STATUS_FROM_SERVER:
- return 2;
- case GRPC_OP_RECV_INITIAL_METADATA:
- return 3;
- case GRPC_OP_RECV_MESSAGE:
- return 4;
- case GRPC_OP_RECV_CLOSE_ON_SERVER:
- case GRPC_OP_RECV_STATUS_ON_CLIENT:
- return 5;
- }
- GPR_UNREACHABLE_CODE(return 123456789);
-}
-
+ switch (type) {
+ case GRPC_OP_SEND_INITIAL_METADATA:
+ return 0;
+ case GRPC_OP_SEND_MESSAGE:
+ return 1;
+ case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
+ case GRPC_OP_SEND_STATUS_FROM_SERVER:
+ return 2;
+ case GRPC_OP_RECV_INITIAL_METADATA:
+ return 3;
+ case GRPC_OP_RECV_MESSAGE:
+ return 4;
+ case GRPC_OP_RECV_CLOSE_ON_SERVER:
+ case GRPC_OP_RECV_STATUS_ON_CLIENT:
+ return 5;
+ }
+ GPR_UNREACHABLE_CODE(return 123456789);
+}
+
static batch_control* reuse_or_allocate_batch_control(grpc_call* call,
const grpc_op* ops) {
size_t slot_idx = batch_slot_for_op(ops[0].op);
@@ -1152,226 +1152,226 @@ static batch_control* reuse_or_allocate_batch_control(grpc_call* call,
} else {
bctl = call->arena->New<batch_control>();
*pslot = bctl;
- }
- bctl->call = call;
- bctl->op.payload = &call->stream_op_payload;
- return bctl;
-}
-
-static void finish_batch_completion(void* user_data,
+ }
+ bctl->call = call;
+ bctl->op.payload = &call->stream_op_payload;
+ return bctl;
+}
+
+static void finish_batch_completion(void* user_data,
grpc_cq_completion* /*storage*/) {
- batch_control* bctl = static_cast<batch_control*>(user_data);
- grpc_call* call = bctl->call;
- bctl->call = nullptr;
- GRPC_CALL_INTERNAL_UNREF(call, "completion");
-}
-
+ batch_control* bctl = static_cast<batch_control*>(user_data);
+ grpc_call* call = bctl->call;
+ bctl->call = nullptr;
+ GRPC_CALL_INTERNAL_UNREF(call, "completion");
+}
+
static void reset_batch_errors(batch_control* bctl) {
GRPC_ERROR_UNREF(
reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)));
gpr_atm_rel_store(&bctl->batch_error,
reinterpret_cast<gpr_atm>(GRPC_ERROR_NONE));
-}
-
-static void post_batch_completion(batch_control* bctl) {
- grpc_call* next_child_call;
- grpc_call* call = bctl->call;
+}
+
+static void post_batch_completion(batch_control* bctl) {
+ grpc_call* next_child_call;
+ grpc_call* call = bctl->call;
grpc_error* error = GRPC_ERROR_REF(
reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)));
-
- if (bctl->op.send_initial_metadata) {
- grpc_metadata_batch_destroy(
- &call->metadata_batch[0 /* is_receiving */][0 /* is_trailing */]);
- }
- if (bctl->op.send_message) {
+
+ if (bctl->op.send_initial_metadata) {
+ grpc_metadata_batch_destroy(
+ &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."));
}
- call->sending_message = false;
- }
- if (bctl->op.send_trailing_metadata) {
- grpc_metadata_batch_destroy(
- &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */]);
- }
- if (bctl->op.recv_trailing_metadata) {
- /* propagate cancellation to any interested children */
- gpr_atm_rel_store(&call->received_final_op_atm, 1);
- parent_call* pc = get_parent_call(call);
- if (pc != nullptr) {
- grpc_call* child;
- gpr_mu_lock(&pc->child_list_mu);
- child = pc->first_child;
- if (child != nullptr) {
- do {
- next_child_call = child->child->sibling_next;
- if (child->cancellation_is_inherited) {
- GRPC_CALL_INTERNAL_REF(child, "propagate_cancel");
+ call->sending_message = false;
+ }
+ if (bctl->op.send_trailing_metadata) {
+ grpc_metadata_batch_destroy(
+ &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */]);
+ }
+ if (bctl->op.recv_trailing_metadata) {
+ /* propagate cancellation to any interested children */
+ gpr_atm_rel_store(&call->received_final_op_atm, 1);
+ parent_call* pc = get_parent_call(call);
+ if (pc != nullptr) {
+ grpc_call* child;
+ gpr_mu_lock(&pc->child_list_mu);
+ child = pc->first_child;
+ if (child != nullptr) {
+ do {
+ next_child_call = child->child->sibling_next;
+ if (child->cancellation_is_inherited) {
+ GRPC_CALL_INTERNAL_REF(child, "propagate_cancel");
cancel_with_error(child, GRPC_ERROR_CANCELLED);
- GRPC_CALL_INTERNAL_UNREF(child, "propagate_cancel");
- }
- child = next_child_call;
- } while (child != pc->first_child);
- }
- gpr_mu_unlock(&pc->child_list_mu);
- }
- GRPC_ERROR_UNREF(error);
- error = GRPC_ERROR_NONE;
- }
- if (error != GRPC_ERROR_NONE && bctl->op.recv_message &&
- *call->receiving_buffer != nullptr) {
- grpc_byte_buffer_destroy(*call->receiving_buffer);
- *call->receiving_buffer = nullptr;
- }
+ GRPC_CALL_INTERNAL_UNREF(child, "propagate_cancel");
+ }
+ child = next_child_call;
+ } while (child != pc->first_child);
+ }
+ gpr_mu_unlock(&pc->child_list_mu);
+ }
+ GRPC_ERROR_UNREF(error);
+ error = GRPC_ERROR_NONE;
+ }
+ if (error != GRPC_ERROR_NONE && bctl->op.recv_message &&
+ *call->receiving_buffer != nullptr) {
+ grpc_byte_buffer_destroy(*call->receiving_buffer);
+ *call->receiving_buffer = nullptr;
+ }
reset_batch_errors(bctl);
-
- if (bctl->completion_data.notify_tag.is_closure) {
+
+ if (bctl->completion_data.notify_tag.is_closure) {
/* unrefs error */
- bctl->call = nullptr;
+ bctl->call = nullptr;
grpc_core::Closure::Run(DEBUG_LOCATION,
(grpc_closure*)bctl->completion_data.notify_tag.tag,
error);
- GRPC_CALL_INTERNAL_UNREF(call, "completion");
- } else {
+ GRPC_CALL_INTERNAL_UNREF(call, "completion");
+ } else {
/* unrefs error */
- grpc_cq_end_op(bctl->call->cq, bctl->completion_data.notify_tag.tag, error,
- finish_batch_completion, bctl,
- &bctl->completion_data.cq_completion);
- }
-}
-
-static void finish_batch_step(batch_control* bctl) {
+ grpc_cq_end_op(bctl->call->cq, bctl->completion_data.notify_tag.tag, error,
+ finish_batch_completion, bctl,
+ &bctl->completion_data.cq_completion);
+ }
+}
+
+static void finish_batch_step(batch_control* bctl) {
if (GPR_UNLIKELY(bctl->completed_batch_step())) {
- post_batch_completion(bctl);
- }
-}
-
-static void continue_receiving_slices(batch_control* bctl) {
- grpc_error* error;
- grpc_call* call = bctl->call;
- for (;;) {
- size_t remaining = call->receiving_stream->length() -
- (*call->receiving_buffer)->data.raw.slice_buffer.length;
- if (remaining == 0) {
- call->receiving_message = 0;
- call->receiving_stream.reset();
- finish_batch_step(bctl);
- return;
- }
- if (call->receiving_stream->Next(remaining, &call->receiving_slice_ready)) {
- error = call->receiving_stream->Pull(&call->receiving_slice);
- if (error == GRPC_ERROR_NONE) {
- grpc_slice_buffer_add(&(*call->receiving_buffer)->data.raw.slice_buffer,
- call->receiving_slice);
- } else {
- call->receiving_stream.reset();
- grpc_byte_buffer_destroy(*call->receiving_buffer);
- *call->receiving_buffer = nullptr;
- call->receiving_message = 0;
- finish_batch_step(bctl);
+ post_batch_completion(bctl);
+ }
+}
+
+static void continue_receiving_slices(batch_control* bctl) {
+ grpc_error* error;
+ grpc_call* call = bctl->call;
+ for (;;) {
+ size_t remaining = call->receiving_stream->length() -
+ (*call->receiving_buffer)->data.raw.slice_buffer.length;
+ if (remaining == 0) {
+ call->receiving_message = 0;
+ call->receiving_stream.reset();
+ finish_batch_step(bctl);
+ return;
+ }
+ if (call->receiving_stream->Next(remaining, &call->receiving_slice_ready)) {
+ error = call->receiving_stream->Pull(&call->receiving_slice);
+ if (error == GRPC_ERROR_NONE) {
+ grpc_slice_buffer_add(&(*call->receiving_buffer)->data.raw.slice_buffer,
+ call->receiving_slice);
+ } else {
+ call->receiving_stream.reset();
+ grpc_byte_buffer_destroy(*call->receiving_buffer);
+ *call->receiving_buffer = nullptr;
+ call->receiving_message = 0;
+ finish_batch_step(bctl);
GRPC_ERROR_UNREF(error);
- return;
- }
- } else {
- return;
- }
- }
-}
-
-static void receiving_slice_ready(void* bctlp, grpc_error* error) {
- batch_control* bctl = static_cast<batch_control*>(bctlp);
- grpc_call* call = bctl->call;
- bool release_error = false;
-
- if (error == GRPC_ERROR_NONE) {
- grpc_slice slice;
- error = call->receiving_stream->Pull(&slice);
- if (error == GRPC_ERROR_NONE) {
- grpc_slice_buffer_add(&(*call->receiving_buffer)->data.raw.slice_buffer,
- slice);
- continue_receiving_slices(bctl);
- } else {
- /* Error returned by ByteStream::Pull() needs to be released manually */
- release_error = true;
- }
- }
-
- if (error != GRPC_ERROR_NONE) {
+ return;
+ }
+ } else {
+ return;
+ }
+ }
+}
+
+static void receiving_slice_ready(void* bctlp, grpc_error* error) {
+ batch_control* bctl = static_cast<batch_control*>(bctlp);
+ grpc_call* call = bctl->call;
+ bool release_error = false;
+
+ if (error == GRPC_ERROR_NONE) {
+ grpc_slice slice;
+ error = call->receiving_stream->Pull(&slice);
+ if (error == GRPC_ERROR_NONE) {
+ grpc_slice_buffer_add(&(*call->receiving_buffer)->data.raw.slice_buffer,
+ slice);
+ continue_receiving_slices(bctl);
+ } else {
+ /* Error returned by ByteStream::Pull() needs to be released manually */
+ release_error = true;
+ }
+ }
+
+ if (error != GRPC_ERROR_NONE) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures)) {
- GRPC_LOG_IF_ERROR("receiving_slice_ready", GRPC_ERROR_REF(error));
- }
- call->receiving_stream.reset();
- grpc_byte_buffer_destroy(*call->receiving_buffer);
- *call->receiving_buffer = nullptr;
- call->receiving_message = 0;
- finish_batch_step(bctl);
- if (release_error) {
- GRPC_ERROR_UNREF(error);
- }
- }
-}
-
-static void process_data_after_md(batch_control* bctl) {
- grpc_call* call = bctl->call;
- if (call->receiving_stream == nullptr) {
- *call->receiving_buffer = nullptr;
- call->receiving_message = 0;
- finish_batch_step(bctl);
- } else {
- call->test_only_last_message_flags = call->receiving_stream->flags();
- if ((call->receiving_stream->flags() & GRPC_WRITE_INTERNAL_COMPRESS) &&
- (call->incoming_message_compression_algorithm >
- GRPC_MESSAGE_COMPRESS_NONE)) {
- grpc_compression_algorithm algo;
- GPR_ASSERT(
- grpc_compression_algorithm_from_message_stream_compression_algorithm(
- &algo, call->incoming_message_compression_algorithm,
- (grpc_stream_compression_algorithm)0));
- *call->receiving_buffer =
- grpc_raw_compressed_byte_buffer_create(nullptr, 0, algo);
- } else {
- *call->receiving_buffer = grpc_raw_byte_buffer_create(nullptr, 0);
- }
- GRPC_CLOSURE_INIT(&call->receiving_slice_ready, receiving_slice_ready, bctl,
- grpc_schedule_on_exec_ctx);
- continue_receiving_slices(bctl);
- }
-}
-
-static void receiving_stream_ready(void* bctlp, grpc_error* error) {
- batch_control* bctl = static_cast<batch_control*>(bctlp);
- grpc_call* call = bctl->call;
- if (error != GRPC_ERROR_NONE) {
- call->receiving_stream.reset();
+ GRPC_LOG_IF_ERROR("receiving_slice_ready", GRPC_ERROR_REF(error));
+ }
+ call->receiving_stream.reset();
+ grpc_byte_buffer_destroy(*call->receiving_buffer);
+ *call->receiving_buffer = nullptr;
+ call->receiving_message = 0;
+ finish_batch_step(bctl);
+ if (release_error) {
+ GRPC_ERROR_UNREF(error);
+ }
+ }
+}
+
+static void process_data_after_md(batch_control* bctl) {
+ grpc_call* call = bctl->call;
+ if (call->receiving_stream == nullptr) {
+ *call->receiving_buffer = nullptr;
+ call->receiving_message = 0;
+ finish_batch_step(bctl);
+ } else {
+ call->test_only_last_message_flags = call->receiving_stream->flags();
+ if ((call->receiving_stream->flags() & GRPC_WRITE_INTERNAL_COMPRESS) &&
+ (call->incoming_message_compression_algorithm >
+ GRPC_MESSAGE_COMPRESS_NONE)) {
+ grpc_compression_algorithm algo;
+ GPR_ASSERT(
+ grpc_compression_algorithm_from_message_stream_compression_algorithm(
+ &algo, call->incoming_message_compression_algorithm,
+ (grpc_stream_compression_algorithm)0));
+ *call->receiving_buffer =
+ grpc_raw_compressed_byte_buffer_create(nullptr, 0, algo);
+ } else {
+ *call->receiving_buffer = grpc_raw_byte_buffer_create(nullptr, 0);
+ }
+ GRPC_CLOSURE_INIT(&call->receiving_slice_ready, receiving_slice_ready, bctl,
+ grpc_schedule_on_exec_ctx);
+ continue_receiving_slices(bctl);
+ }
+}
+
+static void receiving_stream_ready(void* bctlp, grpc_error* error) {
+ batch_control* bctl = static_cast<batch_control*>(bctlp);
+ grpc_call* call = bctl->call;
+ if (error != GRPC_ERROR_NONE) {
+ call->receiving_stream.reset();
if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) ==
GRPC_ERROR_NONE) {
gpr_atm_rel_store(&bctl->batch_error,
reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error)));
}
cancel_with_error(call, GRPC_ERROR_REF(error));
- }
- /* If recv_state is RECV_NONE, we will save the batch_control
- * object with rel_cas, and will not use it after the cas. Its corresponding
- * acq_load is in receiving_initial_metadata_ready() */
- if (error != GRPC_ERROR_NONE || call->receiving_stream == nullptr ||
- !gpr_atm_rel_cas(&call->recv_state, RECV_NONE, (gpr_atm)bctlp)) {
- process_data_after_md(bctl);
- }
-}
-
-// The recv_message_ready callback used when sending a batch containing
-// a recv_message op down the filter stack. Yields the call combiner
-// before processing the received message.
-static void receiving_stream_ready_in_call_combiner(void* bctlp,
- grpc_error* error) {
- batch_control* bctl = static_cast<batch_control*>(bctlp);
- grpc_call* call = bctl->call;
- GRPC_CALL_COMBINER_STOP(&call->call_combiner, "recv_message_ready");
- receiving_stream_ready(bctlp, error);
-}
-
+ }
+ /* If recv_state is RECV_NONE, we will save the batch_control
+ * object with rel_cas, and will not use it after the cas. Its corresponding
+ * acq_load is in receiving_initial_metadata_ready() */
+ if (error != GRPC_ERROR_NONE || call->receiving_stream == nullptr ||
+ !gpr_atm_rel_cas(&call->recv_state, RECV_NONE, (gpr_atm)bctlp)) {
+ process_data_after_md(bctl);
+ }
+}
+
+// The recv_message_ready callback used when sending a batch containing
+// a recv_message op down the filter stack. Yields the call combiner
+// before processing the received message.
+static void receiving_stream_ready_in_call_combiner(void* bctlp,
+ grpc_error* error) {
+ batch_control* bctl = static_cast<batch_control*>(bctlp);
+ grpc_call* call = bctl->call;
+ GRPC_CALL_COMBINER_STOP(&call->call_combiner, "recv_message_ready");
+ receiving_stream_ready(bctlp, error);
+}
+
static void GPR_ATTRIBUTE_NOINLINE
handle_both_stream_and_msg_compression_set(grpc_call* call) {
TString error_msg = y_absl::StrFormat(
@@ -1421,61 +1421,61 @@ static void GPR_ATTRIBUTE_NOINLINE handle_compression_algorithm_not_accepted(
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;
+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);
- } else if (
+ } 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);
- } else {
- const grpc_compression_options compression_options =
- grpc_channel_compression_options(call->channel);
+ } 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)) {
- /* check if algorithm is supported by current channel config */
+ /* check if algorithm is supported by current channel config */
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);
- }
- }
- }
-}
-
-static void receiving_initial_metadata_ready(void* bctlp, grpc_error* error) {
- batch_control* bctl = static_cast<batch_control*>(bctlp);
- grpc_call* call = bctl->call;
-
- GRPC_CALL_COMBINER_STOP(&call->call_combiner, "recv_initial_metadata_ready");
-
- if (error == GRPC_ERROR_NONE) {
- grpc_metadata_batch* md =
- &call->metadata_batch[1 /* is_receiving */][0 /* is_trailing */];
- recv_initial_filter(call, md);
-
- /* TODO(ctiller): this could be moved into recv_initial_filter now */
- GPR_TIMER_SCOPE("validate_filtered_metadata", 0);
- validate_filtered_metadata(bctl);
-
- if (md->deadline != GRPC_MILLIS_INF_FUTURE && !call->is_client) {
- call->send_deadline = md->deadline;
- }
+ }
+ }
+ }
+}
+
+static void receiving_initial_metadata_ready(void* bctlp, grpc_error* error) {
+ batch_control* bctl = static_cast<batch_control*>(bctlp);
+ grpc_call* call = bctl->call;
+
+ GRPC_CALL_COMBINER_STOP(&call->call_combiner, "recv_initial_metadata_ready");
+
+ if (error == GRPC_ERROR_NONE) {
+ grpc_metadata_batch* md =
+ &call->metadata_batch[1 /* is_receiving */][0 /* is_trailing */];
+ recv_initial_filter(call, md);
+
+ /* TODO(ctiller): this could be moved into recv_initial_filter now */
+ GPR_TIMER_SCOPE("validate_filtered_metadata", 0);
+ validate_filtered_metadata(bctl);
+
+ if (md->deadline != GRPC_MILLIS_INF_FUTURE && !call->is_client) {
+ call->send_deadline = md->deadline;
+ }
} else {
if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) ==
GRPC_ERROR_NONE) {
@@ -1483,40 +1483,40 @@ static void receiving_initial_metadata_ready(void* bctlp, grpc_error* error) {
reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error)));
}
cancel_with_error(call, GRPC_ERROR_REF(error));
- }
-
- grpc_closure* saved_rsr_closure = nullptr;
- while (true) {
- gpr_atm rsr_bctlp = gpr_atm_acq_load(&call->recv_state);
- /* Should only receive initial metadata once */
- GPR_ASSERT(rsr_bctlp != 1);
- if (rsr_bctlp == 0) {
- /* We haven't seen initial metadata and messages before, thus initial
- * metadata is received first.
- * no_barrier_cas is used, as this function won't access the batch_control
- * object saved by receiving_stream_ready() if the initial metadata is
- * received first. */
- if (gpr_atm_no_barrier_cas(&call->recv_state, RECV_NONE,
- RECV_INITIAL_METADATA_FIRST)) {
- break;
- }
- } else {
- /* Already received messages */
- saved_rsr_closure =
- GRPC_CLOSURE_CREATE(receiving_stream_ready, (batch_control*)rsr_bctlp,
- grpc_schedule_on_exec_ctx);
- /* No need to modify recv_state */
- break;
- }
- }
- if (saved_rsr_closure != nullptr) {
+ }
+
+ grpc_closure* saved_rsr_closure = nullptr;
+ while (true) {
+ gpr_atm rsr_bctlp = gpr_atm_acq_load(&call->recv_state);
+ /* Should only receive initial metadata once */
+ GPR_ASSERT(rsr_bctlp != 1);
+ if (rsr_bctlp == 0) {
+ /* We haven't seen initial metadata and messages before, thus initial
+ * metadata is received first.
+ * no_barrier_cas is used, as this function won't access the batch_control
+ * object saved by receiving_stream_ready() if the initial metadata is
+ * received first. */
+ if (gpr_atm_no_barrier_cas(&call->recv_state, RECV_NONE,
+ RECV_INITIAL_METADATA_FIRST)) {
+ break;
+ }
+ } else {
+ /* Already received messages */
+ saved_rsr_closure =
+ GRPC_CLOSURE_CREATE(receiving_stream_ready, (batch_control*)rsr_bctlp,
+ grpc_schedule_on_exec_ctx);
+ /* No need to modify recv_state */
+ break;
+ }
+ }
+ if (saved_rsr_closure != nullptr) {
grpc_core::Closure::Run(DEBUG_LOCATION, saved_rsr_closure,
GRPC_ERROR_REF(error));
- }
-
- finish_batch_step(bctl);
-}
-
+ }
+
+ finish_batch_step(bctl);
+}
+
static void receiving_trailing_metadata_ready(void* bctlp, grpc_error* error) {
batch_control* bctl = static_cast<batch_control*>(bctlp);
grpc_call* call = bctl->call;
@@ -1527,10 +1527,10 @@ static void receiving_trailing_metadata_ready(void* bctlp, grpc_error* error) {
finish_batch_step(bctl);
}
-static void finish_batch(void* bctlp, grpc_error* error) {
- batch_control* bctl = static_cast<batch_control*>(bctlp);
- grpc_call* call = bctl->call;
- GRPC_CALL_COMBINER_STOP(&call->call_combiner, "on_complete");
+static void finish_batch(void* bctlp, grpc_error* error) {
+ batch_control* bctl = static_cast<batch_control*>(bctlp);
+ grpc_call* call = bctl->call;
+ GRPC_CALL_COMBINER_STOP(&call->call_combiner, "on_complete");
if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) ==
GRPC_ERROR_NONE) {
gpr_atm_rel_store(&bctl->batch_error,
@@ -1539,213 +1539,213 @@ static void finish_batch(void* bctlp, grpc_error* error) {
if (error != GRPC_ERROR_NONE) {
cancel_with_error(call, GRPC_ERROR_REF(error));
}
- finish_batch_step(bctl);
-}
-
+ finish_batch_step(bctl);
+}
+
static void free_no_op_completion(void* /*p*/, grpc_cq_completion* completion) {
- gpr_free(completion);
-}
-
-static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
- size_t nops, void* notify_tag,
- int is_notify_tag_closure) {
- GPR_TIMER_SCOPE("call_start_batch", 0);
-
- size_t i;
- const grpc_op* op;
- batch_control* bctl;
+ gpr_free(completion);
+}
+
+static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
+ size_t nops, void* notify_tag,
+ int is_notify_tag_closure) {
+ GPR_TIMER_SCOPE("call_start_batch", 0);
+
+ size_t i;
+ const grpc_op* op;
+ batch_control* bctl;
bool has_send_ops = false;
int num_recv_ops = 0;
- grpc_call_error error = GRPC_CALL_OK;
- grpc_transport_stream_op_batch* stream_op;
- grpc_transport_stream_op_batch_payload* stream_op_payload;
-
+ grpc_call_error error = GRPC_CALL_OK;
+ grpc_transport_stream_op_batch* stream_op;
+ grpc_transport_stream_op_batch_payload* stream_op_payload;
+
GRPC_CALL_LOG_BATCH(GPR_INFO, ops, nops);
-
- if (nops == 0) {
- if (!is_notify_tag_closure) {
- GPR_ASSERT(grpc_cq_begin_op(call->cq, notify_tag));
- grpc_cq_end_op(call->cq, notify_tag, GRPC_ERROR_NONE,
- free_no_op_completion, nullptr,
- static_cast<grpc_cq_completion*>(
- gpr_malloc(sizeof(grpc_cq_completion))));
- } else {
+
+ if (nops == 0) {
+ if (!is_notify_tag_closure) {
+ GPR_ASSERT(grpc_cq_begin_op(call->cq, notify_tag));
+ grpc_cq_end_op(call->cq, notify_tag, GRPC_ERROR_NONE,
+ free_no_op_completion, nullptr,
+ 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);
- }
- error = GRPC_CALL_OK;
- goto done;
- }
-
+ }
+ error = GRPC_CALL_OK;
+ goto done;
+ }
+
bctl = reuse_or_allocate_batch_control(call, ops);
- if (bctl == nullptr) {
- return GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- }
- bctl->completion_data.notify_tag.tag = notify_tag;
- bctl->completion_data.notify_tag.is_closure =
- static_cast<uint8_t>(is_notify_tag_closure != 0);
-
- stream_op = &bctl->op;
- stream_op_payload = &call->stream_op_payload;
-
- /* rewrite batch ops into a transport op */
- for (i = 0; i < nops; i++) {
- op = &ops[i];
- if (op->reserved != nullptr) {
- error = GRPC_CALL_ERROR;
- goto done_with_error;
- }
- switch (op->op) {
- case GRPC_OP_SEND_INITIAL_METADATA: {
- /* Flag validation: currently allow no flags */
- if (!are_initial_metadata_flags_valid(op->flags, call->is_client)) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (call->sent_initial_metadata) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
+ if (bctl == nullptr) {
+ return GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ }
+ bctl->completion_data.notify_tag.tag = notify_tag;
+ bctl->completion_data.notify_tag.is_closure =
+ static_cast<uint8_t>(is_notify_tag_closure != 0);
+
+ stream_op = &bctl->op;
+ stream_op_payload = &call->stream_op_payload;
+
+ /* rewrite batch ops into a transport op */
+ for (i = 0; i < nops; i++) {
+ op = &ops[i];
+ if (op->reserved != nullptr) {
+ error = GRPC_CALL_ERROR;
+ goto done_with_error;
+ }
+ switch (op->op) {
+ case GRPC_OP_SEND_INITIAL_METADATA: {
+ /* Flag validation: currently allow no flags */
+ if (!are_initial_metadata_flags_valid(op->flags, call->is_client)) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (call->sent_initial_metadata) {
+ 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.
- /* process 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;
- size_t additional_metadata_count = 0;
- grpc_compression_level effective_compression_level =
- GRPC_COMPRESS_LEVEL_NONE;
- bool level_set = false;
- if (op->data.send_initial_metadata.maybe_compression_level.is_set) {
- effective_compression_level =
- op->data.send_initial_metadata.maybe_compression_level.level;
- level_set = true;
- } else {
- const grpc_compression_options copts =
- grpc_channel_compression_options(call->channel);
- if (copts.default_level.is_set) {
- level_set = true;
- effective_compression_level = copts.default_level.level;
- }
- }
+ size_t additional_metadata_count = 0;
+ grpc_compression_level effective_compression_level =
+ GRPC_COMPRESS_LEVEL_NONE;
+ bool level_set = false;
+ if (op->data.send_initial_metadata.maybe_compression_level.is_set) {
+ effective_compression_level =
+ op->data.send_initial_metadata.maybe_compression_level.level;
+ level_set = true;
+ } else {
+ const grpc_compression_options copts =
+ grpc_channel_compression_options(call->channel);
+ if (copts.default_level.is_set) {
+ level_set = true;
+ effective_compression_level = copts.default_level.level;
+ }
+ }
// 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);
+ 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);
- additional_metadata_count++;
- }
- if (op->data.send_initial_metadata.count + additional_metadata_count >
- INT_MAX) {
- error = GRPC_CALL_ERROR_INVALID_METADATA;
- goto done_with_error;
- }
- stream_op->send_initial_metadata = true;
- call->sent_initial_metadata = true;
- if (!prepare_application_metadata(
- call, static_cast<int>(op->data.send_initial_metadata.count),
- op->data.send_initial_metadata.metadata, 0, call->is_client,
+ additional_metadata_count++;
+ }
+ if (op->data.send_initial_metadata.count + additional_metadata_count >
+ INT_MAX) {
+ error = GRPC_CALL_ERROR_INVALID_METADATA;
+ goto done_with_error;
+ }
+ stream_op->send_initial_metadata = true;
+ call->sent_initial_metadata = true;
+ 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))) {
- error = GRPC_CALL_ERROR_INVALID_METADATA;
- goto done_with_error;
- }
- /* TODO(ctiller): just make these the same variable? */
- if (call->is_client) {
- call->metadata_batch[0][0].deadline = call->send_deadline;
- }
- stream_op_payload->send_initial_metadata.send_initial_metadata =
- &call->metadata_batch[0 /* is_receiving */][0 /* is_trailing */];
- stream_op_payload->send_initial_metadata.send_initial_metadata_flags =
- op->flags;
- if (call->is_client) {
- stream_op_payload->send_initial_metadata.peer_string =
- &call->peer_string;
- }
+ error = GRPC_CALL_ERROR_INVALID_METADATA;
+ goto done_with_error;
+ }
+ /* TODO(ctiller): just make these the same variable? */
+ if (call->is_client) {
+ call->metadata_batch[0][0].deadline = call->send_deadline;
+ }
+ stream_op_payload->send_initial_metadata.send_initial_metadata =
+ &call->metadata_batch[0 /* is_receiving */][0 /* is_trailing */];
+ stream_op_payload->send_initial_metadata.send_initial_metadata_flags =
+ op->flags;
+ if (call->is_client) {
+ stream_op_payload->send_initial_metadata.peer_string =
+ &call->peer_string;
+ }
has_send_ops = true;
- break;
- }
- case GRPC_OP_SEND_MESSAGE: {
- if (!are_write_flags_valid(op->flags)) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (op->data.send_message.send_message == nullptr) {
- error = GRPC_CALL_ERROR_INVALID_MESSAGE;
- goto done_with_error;
- }
- if (call->sending_message) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
- uint32_t flags = op->flags;
- /* If the outgoing buffer is already compressed, mark it as so in the
- flags. These will be picked up by the compression filter and further
- (wasteful) attempts at compression skipped. */
- if (op->data.send_message.send_message->data.raw.compression >
- GRPC_COMPRESS_NONE) {
- flags |= GRPC_WRITE_INTERNAL_COMPRESS;
- }
- stream_op->send_message = true;
- call->sending_message = true;
- call->sending_stream.Init(
- &op->data.send_message.send_message->data.raw.slice_buffer, flags);
- stream_op_payload->send_message.send_message.reset(
- call->sending_stream.get());
+ break;
+ }
+ case GRPC_OP_SEND_MESSAGE: {
+ if (!are_write_flags_valid(op->flags)) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (op->data.send_message.send_message == nullptr) {
+ error = GRPC_CALL_ERROR_INVALID_MESSAGE;
+ goto done_with_error;
+ }
+ if (call->sending_message) {
+ error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ goto done_with_error;
+ }
+ uint32_t flags = op->flags;
+ /* If the outgoing buffer is already compressed, mark it as so in the
+ flags. These will be picked up by the compression filter and further
+ (wasteful) attempts at compression skipped. */
+ if (op->data.send_message.send_message->data.raw.compression >
+ GRPC_COMPRESS_NONE) {
+ flags |= GRPC_WRITE_INTERNAL_COMPRESS;
+ }
+ stream_op->send_message = true;
+ call->sending_message = true;
+ call->sending_stream.Init(
+ &op->data.send_message.send_message->data.raw.slice_buffer, flags);
+ stream_op_payload->send_message.send_message.reset(
+ call->sending_stream.get());
has_send_ops = true;
- break;
- }
- case GRPC_OP_SEND_CLOSE_FROM_CLIENT: {
- /* Flag validation: currently allow no flags */
- if (op->flags != 0) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (!call->is_client) {
- error = GRPC_CALL_ERROR_NOT_ON_SERVER;
- goto done_with_error;
- }
- if (call->sent_final_op) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
- stream_op->send_trailing_metadata = true;
- call->sent_final_op = true;
- stream_op_payload->send_trailing_metadata.send_trailing_metadata =
- &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */];
+ break;
+ }
+ case GRPC_OP_SEND_CLOSE_FROM_CLIENT: {
+ /* Flag validation: currently allow no flags */
+ if (op->flags != 0) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (!call->is_client) {
+ error = GRPC_CALL_ERROR_NOT_ON_SERVER;
+ goto done_with_error;
+ }
+ if (call->sent_final_op) {
+ error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ goto done_with_error;
+ }
+ stream_op->send_trailing_metadata = true;
+ call->sent_final_op = true;
+ stream_op_payload->send_trailing_metadata.send_trailing_metadata =
+ &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */];
has_send_ops = true;
- break;
- }
- case GRPC_OP_SEND_STATUS_FROM_SERVER: {
- /* Flag validation: currently allow no flags */
- if (op->flags != 0) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (call->is_client) {
- error = GRPC_CALL_ERROR_NOT_ON_CLIENT;
- goto done_with_error;
- }
- if (call->sent_final_op) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
- if (op->data.send_status_from_server.trailing_metadata_count >
- INT_MAX) {
- error = GRPC_CALL_ERROR_INVALID_METADATA;
- goto done_with_error;
- }
- stream_op->send_trailing_metadata = true;
- call->sent_final_op = true;
- GPR_ASSERT(call->send_extra_metadata_count == 0);
- call->send_extra_metadata_count = 1;
+ break;
+ }
+ case GRPC_OP_SEND_STATUS_FROM_SERVER: {
+ /* Flag validation: currently allow no flags */
+ if (op->flags != 0) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (call->is_client) {
+ error = GRPC_CALL_ERROR_NOT_ON_CLIENT;
+ goto done_with_error;
+ }
+ if (call->sent_final_op) {
+ error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ goto done_with_error;
+ }
+ if (op->data.send_status_from_server.trailing_metadata_count >
+ INT_MAX) {
+ error = GRPC_CALL_ERROR_INVALID_METADATA;
+ goto done_with_error;
+ }
+ stream_op->send_trailing_metadata = true;
+ 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);
grpc_error* status_error =
@@ -1764,282 +1764,282 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops,
*op->data.send_status_from_server.status_details));
call->send_extra_metadata_count++;
if (status_error != GRPC_ERROR_NONE) {
- char* msg = grpc_slice_to_c_string(
- GRPC_MDVALUE(call->send_extra_metadata[1].md));
+ char* msg = grpc_slice_to_c_string(
+ GRPC_MDVALUE(call->send_extra_metadata[1].md));
status_error =
grpc_error_set_str(status_error, GRPC_ERROR_STR_GRPC_MESSAGE,
- grpc_slice_from_copied_string(msg));
- gpr_free(msg);
- }
- }
+ grpc_slice_from_copied_string(msg));
+ gpr_free(msg);
+ }
+ }
gpr_atm_rel_store(&call->status_error,
reinterpret_cast<gpr_atm>(status_error));
- if (!prepare_application_metadata(
- call,
- static_cast<int>(
- op->data.send_status_from_server.trailing_metadata_count),
- op->data.send_status_from_server.trailing_metadata, 1, 1,
- nullptr, 0)) {
- for (int n = 0; n < call->send_extra_metadata_count; n++) {
- GRPC_MDELEM_UNREF(call->send_extra_metadata[n].md);
- }
- call->send_extra_metadata_count = 0;
- error = GRPC_CALL_ERROR_INVALID_METADATA;
- goto done_with_error;
- }
- stream_op_payload->send_trailing_metadata.send_trailing_metadata =
- &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */];
+ if (!prepare_application_metadata(
+ call,
+ static_cast<int>(
+ op->data.send_status_from_server.trailing_metadata_count),
+ op->data.send_status_from_server.trailing_metadata, 1, 1,
+ nullptr, 0)) {
+ for (int n = 0; n < call->send_extra_metadata_count; n++) {
+ GRPC_MDELEM_UNREF(call->send_extra_metadata[n].md);
+ }
+ call->send_extra_metadata_count = 0;
+ error = GRPC_CALL_ERROR_INVALID_METADATA;
+ goto done_with_error;
+ }
+ stream_op_payload->send_trailing_metadata.send_trailing_metadata =
+ &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */];
stream_op_payload->send_trailing_metadata.sent =
&call->sent_server_trailing_metadata;
has_send_ops = true;
- break;
- }
- case GRPC_OP_RECV_INITIAL_METADATA: {
- /* Flag validation: currently allow no flags */
- if (op->flags != 0) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (call->received_initial_metadata) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
- call->received_initial_metadata = true;
- call->buffered_metadata[0] =
- op->data.recv_initial_metadata.recv_initial_metadata;
- GRPC_CLOSURE_INIT(&call->receiving_initial_metadata_ready,
- receiving_initial_metadata_ready, bctl,
- grpc_schedule_on_exec_ctx);
- stream_op->recv_initial_metadata = true;
- stream_op_payload->recv_initial_metadata.recv_initial_metadata =
- &call->metadata_batch[1 /* is_receiving */][0 /* is_trailing */];
- stream_op_payload->recv_initial_metadata.recv_initial_metadata_ready =
- &call->receiving_initial_metadata_ready;
- if (!call->is_client) {
- stream_op_payload->recv_initial_metadata.peer_string =
- &call->peer_string;
- }
+ break;
+ }
+ case GRPC_OP_RECV_INITIAL_METADATA: {
+ /* Flag validation: currently allow no flags */
+ if (op->flags != 0) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (call->received_initial_metadata) {
+ error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ goto done_with_error;
+ }
+ call->received_initial_metadata = true;
+ call->buffered_metadata[0] =
+ op->data.recv_initial_metadata.recv_initial_metadata;
+ GRPC_CLOSURE_INIT(&call->receiving_initial_metadata_ready,
+ receiving_initial_metadata_ready, bctl,
+ grpc_schedule_on_exec_ctx);
+ stream_op->recv_initial_metadata = true;
+ stream_op_payload->recv_initial_metadata.recv_initial_metadata =
+ &call->metadata_batch[1 /* is_receiving */][0 /* is_trailing */];
+ stream_op_payload->recv_initial_metadata.recv_initial_metadata_ready =
+ &call->receiving_initial_metadata_ready;
+ if (!call->is_client) {
+ stream_op_payload->recv_initial_metadata.peer_string =
+ &call->peer_string;
+ }
++num_recv_ops;
- break;
- }
- case GRPC_OP_RECV_MESSAGE: {
- /* Flag validation: currently allow no flags */
- if (op->flags != 0) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (call->receiving_message) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
- call->receiving_message = true;
- stream_op->recv_message = true;
- call->receiving_buffer = op->data.recv_message.recv_message;
- stream_op_payload->recv_message.recv_message = &call->receiving_stream;
- GRPC_CLOSURE_INIT(&call->receiving_stream_ready,
- receiving_stream_ready_in_call_combiner, bctl,
- grpc_schedule_on_exec_ctx);
- stream_op_payload->recv_message.recv_message_ready =
- &call->receiving_stream_ready;
+ break;
+ }
+ case GRPC_OP_RECV_MESSAGE: {
+ /* Flag validation: currently allow no flags */
+ if (op->flags != 0) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (call->receiving_message) {
+ error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ goto done_with_error;
+ }
+ call->receiving_message = true;
+ stream_op->recv_message = true;
+ call->receiving_buffer = op->data.recv_message.recv_message;
+ stream_op_payload->recv_message.recv_message = &call->receiving_stream;
+ GRPC_CLOSURE_INIT(&call->receiving_stream_ready,
+ receiving_stream_ready_in_call_combiner, bctl,
+ grpc_schedule_on_exec_ctx);
+ stream_op_payload->recv_message.recv_message_ready =
+ &call->receiving_stream_ready;
++num_recv_ops;
- break;
- }
- case GRPC_OP_RECV_STATUS_ON_CLIENT: {
- /* Flag validation: currently allow no flags */
- if (op->flags != 0) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (!call->is_client) {
- error = GRPC_CALL_ERROR_NOT_ON_SERVER;
- goto done_with_error;
- }
- if (call->requested_final_op) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
- call->requested_final_op = true;
- call->buffered_metadata[1] =
- op->data.recv_status_on_client.trailing_metadata;
- call->final_op.client.status = op->data.recv_status_on_client.status;
- call->final_op.client.status_details =
- op->data.recv_status_on_client.status_details;
- call->final_op.client.error_string =
- op->data.recv_status_on_client.error_string;
- stream_op->recv_trailing_metadata = true;
- stream_op_payload->recv_trailing_metadata.recv_trailing_metadata =
- &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */];
+ break;
+ }
+ case GRPC_OP_RECV_STATUS_ON_CLIENT: {
+ /* Flag validation: currently allow no flags */
+ if (op->flags != 0) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (!call->is_client) {
+ error = GRPC_CALL_ERROR_NOT_ON_SERVER;
+ goto done_with_error;
+ }
+ if (call->requested_final_op) {
+ error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ goto done_with_error;
+ }
+ call->requested_final_op = true;
+ call->buffered_metadata[1] =
+ op->data.recv_status_on_client.trailing_metadata;
+ call->final_op.client.status = op->data.recv_status_on_client.status;
+ call->final_op.client.status_details =
+ op->data.recv_status_on_client.status_details;
+ call->final_op.client.error_string =
+ op->data.recv_status_on_client.error_string;
+ stream_op->recv_trailing_metadata = true;
+ stream_op_payload->recv_trailing_metadata.recv_trailing_metadata =
+ &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */];
stream_op_payload->recv_trailing_metadata.collect_stats =
- &call->final_info.stats.transport_stream_stats;
+ &call->final_info.stats.transport_stream_stats;
GRPC_CLOSURE_INIT(&call->receiving_trailing_metadata_ready,
receiving_trailing_metadata_ready, bctl,
grpc_schedule_on_exec_ctx);
stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&call->receiving_trailing_metadata_ready;
++num_recv_ops;
- break;
- }
- case GRPC_OP_RECV_CLOSE_ON_SERVER: {
- /* Flag validation: currently allow no flags */
- if (op->flags != 0) {
- error = GRPC_CALL_ERROR_INVALID_FLAGS;
- goto done_with_error;
- }
- if (call->is_client) {
- error = GRPC_CALL_ERROR_NOT_ON_CLIENT;
- goto done_with_error;
- }
- if (call->requested_final_op) {
- error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
- goto done_with_error;
- }
- call->requested_final_op = true;
- call->final_op.server.cancelled =
- op->data.recv_close_on_server.cancelled;
- stream_op->recv_trailing_metadata = true;
- stream_op_payload->recv_trailing_metadata.recv_trailing_metadata =
- &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */];
+ break;
+ }
+ case GRPC_OP_RECV_CLOSE_ON_SERVER: {
+ /* Flag validation: currently allow no flags */
+ if (op->flags != 0) {
+ error = GRPC_CALL_ERROR_INVALID_FLAGS;
+ goto done_with_error;
+ }
+ if (call->is_client) {
+ error = GRPC_CALL_ERROR_NOT_ON_CLIENT;
+ goto done_with_error;
+ }
+ if (call->requested_final_op) {
+ error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS;
+ goto done_with_error;
+ }
+ call->requested_final_op = true;
+ call->final_op.server.cancelled =
+ op->data.recv_close_on_server.cancelled;
+ stream_op->recv_trailing_metadata = true;
+ stream_op_payload->recv_trailing_metadata.recv_trailing_metadata =
+ &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */];
stream_op_payload->recv_trailing_metadata.collect_stats =
- &call->final_info.stats.transport_stream_stats;
+ &call->final_info.stats.transport_stream_stats;
GRPC_CLOSURE_INIT(&call->receiving_trailing_metadata_ready,
receiving_trailing_metadata_ready, bctl,
grpc_schedule_on_exec_ctx);
stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&call->receiving_trailing_metadata_ready;
++num_recv_ops;
- break;
- }
- }
- }
-
- GRPC_CALL_INTERNAL_REF(call, "completion");
- if (!is_notify_tag_closure) {
+ break;
+ }
+ }
+ }
+
+ GRPC_CALL_INTERNAL_REF(call, "completion");
+ 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);
-
+
if (has_send_ops) {
GRPC_CLOSURE_INIT(&bctl->finish_batch, finish_batch, bctl,
grpc_schedule_on_exec_ctx);
stream_op->on_complete = &bctl->finish_batch;
}
- gpr_atm_rel_store(&call->any_ops_sent_atm, 1);
- execute_batch(call, stream_op, &bctl->start_batch);
-
-done:
- return error;
-
-done_with_error:
+ gpr_atm_rel_store(&call->any_ops_sent_atm, 1);
+ execute_batch(call, stream_op, &bctl->start_batch);
+
+done:
+ return error;
+
+done_with_error:
/* reverse any mutations that occurred */
- if (stream_op->send_initial_metadata) {
- call->sent_initial_metadata = false;
- grpc_metadata_batch_clear(&call->metadata_batch[0][0]);
- }
- if (stream_op->send_message) {
- call->sending_message = false;
- call->sending_stream->Orphan();
- }
- if (stream_op->send_trailing_metadata) {
- call->sent_final_op = false;
- grpc_metadata_batch_clear(&call->metadata_batch[0][1]);
- }
- if (stream_op->recv_initial_metadata) {
- call->received_initial_metadata = false;
- }
- if (stream_op->recv_message) {
- call->receiving_message = false;
- }
- if (stream_op->recv_trailing_metadata) {
- call->requested_final_op = false;
- }
- goto done;
-}
-
-grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops,
- size_t nops, void* tag, void* reserved) {
- grpc_call_error err;
-
- GRPC_API_TRACE(
- "grpc_call_start_batch(call=%p, ops=%p, nops=%lu, tag=%p, "
- "reserved=%p)",
- 5, (call, ops, (unsigned long)nops, tag, reserved));
-
- if (reserved != nullptr) {
- err = GRPC_CALL_ERROR;
- } else {
+ if (stream_op->send_initial_metadata) {
+ call->sent_initial_metadata = false;
+ grpc_metadata_batch_clear(&call->metadata_batch[0][0]);
+ }
+ if (stream_op->send_message) {
+ call->sending_message = false;
+ call->sending_stream->Orphan();
+ }
+ if (stream_op->send_trailing_metadata) {
+ call->sent_final_op = false;
+ grpc_metadata_batch_clear(&call->metadata_batch[0][1]);
+ }
+ if (stream_op->recv_initial_metadata) {
+ call->received_initial_metadata = false;
+ }
+ if (stream_op->recv_message) {
+ call->receiving_message = false;
+ }
+ if (stream_op->recv_trailing_metadata) {
+ call->requested_final_op = false;
+ }
+ goto done;
+}
+
+grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops,
+ size_t nops, void* tag, void* reserved) {
+ grpc_call_error err;
+
+ GRPC_API_TRACE(
+ "grpc_call_start_batch(call=%p, ops=%p, nops=%lu, tag=%p, "
+ "reserved=%p)",
+ 5, (call, ops, (unsigned long)nops, tag, reserved));
+
+ if (reserved != nullptr) {
+ err = GRPC_CALL_ERROR;
+ } else {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
- err = call_start_batch(call, ops, nops, tag, 0);
- }
-
- return err;
-}
-
-grpc_call_error grpc_call_start_batch_and_execute(grpc_call* call,
- const grpc_op* ops,
- size_t nops,
- grpc_closure* closure) {
- return call_start_batch(call, ops, nops, closure, 1);
-}
-
-void grpc_call_context_set(grpc_call* call, grpc_context_index elem,
- void* value, void (*destroy)(void* value)) {
- if (call->context[elem].destroy) {
- call->context[elem].destroy(call->context[elem].value);
- }
- call->context[elem].value = value;
- call->context[elem].destroy = destroy;
-}
-
-void* grpc_call_context_get(grpc_call* call, grpc_context_index elem) {
- return call->context[elem].value;
-}
-
-uint8_t grpc_call_is_client(grpc_call* call) { return call->is_client; }
-
-grpc_compression_algorithm grpc_call_compression_for_level(
- grpc_call* call, grpc_compression_level level) {
- grpc_compression_algorithm algo =
- compression_algorithm_for_level_locked(call, level);
- return algo;
-}
-
-const char* grpc_call_error_to_string(grpc_call_error error) {
- switch (error) {
- case GRPC_CALL_ERROR:
- return "GRPC_CALL_ERROR";
- case GRPC_CALL_ERROR_ALREADY_ACCEPTED:
- return "GRPC_CALL_ERROR_ALREADY_ACCEPTED";
- case GRPC_CALL_ERROR_ALREADY_FINISHED:
- return "GRPC_CALL_ERROR_ALREADY_FINISHED";
- case GRPC_CALL_ERROR_ALREADY_INVOKED:
- return "GRPC_CALL_ERROR_ALREADY_INVOKED";
- case GRPC_CALL_ERROR_BATCH_TOO_BIG:
- return "GRPC_CALL_ERROR_BATCH_TOO_BIG";
- case GRPC_CALL_ERROR_INVALID_FLAGS:
- return "GRPC_CALL_ERROR_INVALID_FLAGS";
- case GRPC_CALL_ERROR_INVALID_MESSAGE:
- return "GRPC_CALL_ERROR_INVALID_MESSAGE";
- case GRPC_CALL_ERROR_INVALID_METADATA:
- return "GRPC_CALL_ERROR_INVALID_METADATA";
- case GRPC_CALL_ERROR_NOT_INVOKED:
- return "GRPC_CALL_ERROR_NOT_INVOKED";
- case GRPC_CALL_ERROR_NOT_ON_CLIENT:
- return "GRPC_CALL_ERROR_NOT_ON_CLIENT";
- case GRPC_CALL_ERROR_NOT_ON_SERVER:
- return "GRPC_CALL_ERROR_NOT_ON_SERVER";
- case GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE:
- return "GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE";
- case GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH:
- return "GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH";
- case GRPC_CALL_ERROR_TOO_MANY_OPERATIONS:
- return "GRPC_CALL_ERROR_TOO_MANY_OPERATIONS";
- case GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN:
- return "GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN";
- case GRPC_CALL_OK:
- return "GRPC_CALL_OK";
- }
- GPR_UNREACHABLE_CODE(return "GRPC_CALL_ERROR_UNKNOW");
-}
+ err = call_start_batch(call, ops, nops, tag, 0);
+ }
+
+ return err;
+}
+
+grpc_call_error grpc_call_start_batch_and_execute(grpc_call* call,
+ const grpc_op* ops,
+ size_t nops,
+ grpc_closure* closure) {
+ return call_start_batch(call, ops, nops, closure, 1);
+}
+
+void grpc_call_context_set(grpc_call* call, grpc_context_index elem,
+ void* value, void (*destroy)(void* value)) {
+ if (call->context[elem].destroy) {
+ call->context[elem].destroy(call->context[elem].value);
+ }
+ call->context[elem].value = value;
+ call->context[elem].destroy = destroy;
+}
+
+void* grpc_call_context_get(grpc_call* call, grpc_context_index elem) {
+ return call->context[elem].value;
+}
+
+uint8_t grpc_call_is_client(grpc_call* call) { return call->is_client; }
+
+grpc_compression_algorithm grpc_call_compression_for_level(
+ grpc_call* call, grpc_compression_level level) {
+ grpc_compression_algorithm algo =
+ compression_algorithm_for_level_locked(call, level);
+ return algo;
+}
+
+const char* grpc_call_error_to_string(grpc_call_error error) {
+ switch (error) {
+ case GRPC_CALL_ERROR:
+ return "GRPC_CALL_ERROR";
+ case GRPC_CALL_ERROR_ALREADY_ACCEPTED:
+ return "GRPC_CALL_ERROR_ALREADY_ACCEPTED";
+ case GRPC_CALL_ERROR_ALREADY_FINISHED:
+ return "GRPC_CALL_ERROR_ALREADY_FINISHED";
+ case GRPC_CALL_ERROR_ALREADY_INVOKED:
+ return "GRPC_CALL_ERROR_ALREADY_INVOKED";
+ case GRPC_CALL_ERROR_BATCH_TOO_BIG:
+ return "GRPC_CALL_ERROR_BATCH_TOO_BIG";
+ case GRPC_CALL_ERROR_INVALID_FLAGS:
+ return "GRPC_CALL_ERROR_INVALID_FLAGS";
+ case GRPC_CALL_ERROR_INVALID_MESSAGE:
+ return "GRPC_CALL_ERROR_INVALID_MESSAGE";
+ case GRPC_CALL_ERROR_INVALID_METADATA:
+ return "GRPC_CALL_ERROR_INVALID_METADATA";
+ case GRPC_CALL_ERROR_NOT_INVOKED:
+ return "GRPC_CALL_ERROR_NOT_INVOKED";
+ case GRPC_CALL_ERROR_NOT_ON_CLIENT:
+ return "GRPC_CALL_ERROR_NOT_ON_CLIENT";
+ case GRPC_CALL_ERROR_NOT_ON_SERVER:
+ return "GRPC_CALL_ERROR_NOT_ON_SERVER";
+ case GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE:
+ return "GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE";
+ case GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH:
+ return "GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH";
+ case GRPC_CALL_ERROR_TOO_MANY_OPERATIONS:
+ return "GRPC_CALL_ERROR_TOO_MANY_OPERATIONS";
+ case GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN:
+ return "GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN";
+ case GRPC_CALL_OK:
+ return "GRPC_CALL_OK";
+ }
+ GPR_UNREACHABLE_CODE(return "GRPC_CALL_ERROR_UNKNOW");
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/call.h b/contrib/libs/grpc/src/core/lib/surface/call.h
index 34d01db9029..91e0ceee104 100644
--- a/contrib/libs/grpc/src/core/lib/surface/call.h
+++ b/contrib/libs/grpc/src/core/lib/surface/call.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_CALL_H
#define GRPC_CORE_LIB_SURFACE_CALL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/context.h"
#include "src/core/lib/gprpp/arena.h"
@@ -30,76 +30,76 @@
#include <grpc/grpc.h>
#include <grpc/impl/codegen/compression_types.h>
-typedef void (*grpc_ioreq_completion_func)(grpc_call* call, int success,
- void* user_data);
+typedef void (*grpc_ioreq_completion_func)(grpc_call* call, int success,
+ void* user_data);
typedef struct grpc_call_create_args {
- grpc_channel* channel;
+ grpc_channel* channel;
grpc_core::Server* server;
- grpc_call* parent;
+ grpc_call* parent;
uint32_t propagation_mask;
- grpc_completion_queue* cq;
+ grpc_completion_queue* cq;
/* if not NULL, it'll be used in lieu of cq */
- grpc_pollset_set* pollset_set_alternative;
+ grpc_pollset_set* pollset_set_alternative;
- const void* server_transport_data;
+ const void* server_transport_data;
- grpc_mdelem* add_initial_metadata;
+ grpc_mdelem* add_initial_metadata;
size_t add_initial_metadata_count;
- grpc_millis send_deadline;
+ grpc_millis send_deadline;
} grpc_call_create_args;
/* Create a new call based on \a args.
Regardless of success or failure, always returns a valid new call into *call
*/
-grpc_error* grpc_call_create(const grpc_call_create_args* args,
- grpc_call** call);
+grpc_error* grpc_call_create(const grpc_call_create_args* args,
+ grpc_call** call);
-void grpc_call_set_completion_queue(grpc_call* call, grpc_completion_queue* cq);
+void grpc_call_set_completion_queue(grpc_call* call, grpc_completion_queue* cq);
-#ifndef NDEBUG
-void grpc_call_internal_ref(grpc_call* call, const char* reason);
-void grpc_call_internal_unref(grpc_call* call, const char* reason);
+#ifndef NDEBUG
+void grpc_call_internal_ref(grpc_call* call, const char* reason);
+void grpc_call_internal_unref(grpc_call* call, const char* reason);
#define GRPC_CALL_INTERNAL_REF(call, reason) \
grpc_call_internal_ref(call, reason)
-#define GRPC_CALL_INTERNAL_UNREF(call, reason) \
- grpc_call_internal_unref(call, reason)
+#define GRPC_CALL_INTERNAL_UNREF(call, reason) \
+ grpc_call_internal_unref(call, reason)
#else
-void grpc_call_internal_ref(grpc_call* call);
-void grpc_call_internal_unref(grpc_call* call);
+void grpc_call_internal_ref(grpc_call* call);
+void grpc_call_internal_unref(grpc_call* call);
#define GRPC_CALL_INTERNAL_REF(call, reason) grpc_call_internal_ref(call)
-#define GRPC_CALL_INTERNAL_UNREF(call, reason) grpc_call_internal_unref(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_call_stack* grpc_call_get_call_stack(grpc_call* call);
+grpc_call_stack* grpc_call_get_call_stack(grpc_call* call);
-grpc_call_error grpc_call_start_batch_and_execute(grpc_call* call,
- const grpc_op* ops,
+grpc_call_error grpc_call_start_batch_and_execute(grpc_call* call,
+ const grpc_op* ops,
size_t nops,
- grpc_closure* closure);
+ grpc_closure* closure);
/* gRPC core internal version of grpc_call_cancel that does not create
* exec_ctx. */
void grpc_call_cancel_internal(grpc_call* call);
/* Given the top call_element, get the call object. */
-grpc_call* grpc_call_from_top_element(grpc_call_element* surface_element);
+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,
+void grpc_call_log_batch(const char* file, int line, gpr_log_severity severity,
const grpc_op* ops, size_t nops);
/* Set a context pointer.
No thread safety guarantees are made wrt this value. */
-/* TODO(#9731): add exec_ctx to destroy */
-void grpc_call_context_set(grpc_call* call, grpc_context_index elem,
- void* value, void (*destroy)(void* value));
+/* TODO(#9731): add exec_ctx to destroy */
+void grpc_call_context_set(grpc_call* call, grpc_context_index elem,
+ void* value, void (*destroy)(void* value));
/* Get a context pointer. */
-void* grpc_call_context_get(grpc_call* call, grpc_context_index elem);
+void* grpc_call_context_get(grpc_call* call, grpc_context_index elem);
#define GRPC_CALL_LOG_BATCH(sev, ops, nops) \
do { \
@@ -108,7 +108,7 @@ void* grpc_call_context_get(grpc_call* call, grpc_context_index elem);
} \
} while (0)
-uint8_t grpc_call_is_client(grpc_call* call);
+uint8_t grpc_call_is_client(grpc_call* call);
/* Get the estimated memory size for a call BESIDES the call stack. Combined
* with the size of the call stack, it helps estimate the arena size for the
@@ -118,9 +118,9 @@ size_t grpc_call_get_initial_size_estimate();
/* Return an appropriate compression algorithm for the requested compression \a
* level in the context of \a call. */
grpc_compression_algorithm grpc_call_compression_for_level(
- grpc_call* call, grpc_compression_level level);
+ grpc_call* call, grpc_compression_level level);
-extern grpc_core::TraceFlag grpc_call_error_trace;
-extern grpc_core::TraceFlag grpc_compression_trace;
+extern grpc_core::TraceFlag grpc_call_error_trace;
+extern grpc_core::TraceFlag grpc_compression_trace;
#endif /* GRPC_CORE_LIB_SURFACE_CALL_H */
diff --git a/contrib/libs/grpc/src/core/lib/surface/call_details.cc b/contrib/libs/grpc/src/core/lib/surface/call_details.cc
index 55e9e3425f2..55fe5548227 100644
--- a/contrib/libs/grpc/src/core/lib/surface/call_details.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/call_details.cc
@@ -1,41 +1,41 @@
-/*
- *
- * 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 <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-
-#include <string.h>
-
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.h"
-
-void grpc_call_details_init(grpc_call_details* cd) {
- GRPC_API_TRACE("grpc_call_details_init(cd=%p)", 1, (cd));
- cd->method = grpc_empty_slice();
- cd->host = grpc_empty_slice();
-}
-
-void grpc_call_details_destroy(grpc_call_details* cd) {
- GRPC_API_TRACE("grpc_call_details_destroy(cd=%p)", 1, (cd));
- grpc_core::ExecCtx exec_ctx;
- grpc_slice_unref_internal(cd->method);
- grpc_slice_unref_internal(cd->host);
-}
+/*
+ *
+ * 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 <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+
+#include <string.h>
+
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/api_trace.h"
+
+void grpc_call_details_init(grpc_call_details* cd) {
+ GRPC_API_TRACE("grpc_call_details_init(cd=%p)", 1, (cd));
+ cd->method = grpc_empty_slice();
+ cd->host = grpc_empty_slice();
+}
+
+void grpc_call_details_destroy(grpc_call_details* cd) {
+ GRPC_API_TRACE("grpc_call_details_destroy(cd=%p)", 1, (cd));
+ grpc_core::ExecCtx exec_ctx;
+ grpc_slice_unref_internal(cd->method);
+ grpc_slice_unref_internal(cd->host);
+}
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 c4f78821ab0..1988a508e70 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/surface/call.h"
-
-#include <inttypes.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/surface/call.h"
+
+#include <inttypes.h>
+
#include <vector>
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+
static void add_metadata(const grpc_metadata* md, size_t count,
std::vector<TString>* b) {
- if (md == nullptr) {
+ if (md == nullptr) {
b->push_back("(nil)");
- return;
- }
+ return;
+ }
for (size_t i = 0; i < count; i++) {
b->push_back("\nkey=");
b->push_back(TString(grpc_core::StringViewFromSlice(md[i].key)));
@@ -45,67 +45,67 @@ static void add_metadata(const grpc_metadata* md, size_t count,
char* dump = grpc_dump_slice(md[i].value, GPR_DUMP_HEX | GPR_DUMP_ASCII);
b->push_back(dump);
gpr_free(dump);
- }
-}
-
+ }
+}
+
static TString grpc_op_string(const grpc_op* op) {
std::vector<TString> parts;
- switch (op->op) {
- case GRPC_OP_SEND_INITIAL_METADATA:
+ switch (op->op) {
+ case GRPC_OP_SEND_INITIAL_METADATA:
parts.push_back("SEND_INITIAL_METADATA");
add_metadata(op->data.send_initial_metadata.metadata,
op->data.send_initial_metadata.count, &parts);
- break;
- case GRPC_OP_SEND_MESSAGE:
+ break;
+ case GRPC_OP_SEND_MESSAGE:
parts.push_back(y_absl::StrFormat("SEND_MESSAGE ptr=%p",
op->data.send_message.send_message));
- break;
- case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
+ break;
+ case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
parts.push_back("SEND_CLOSE_FROM_CLIENT");
- break;
- case GRPC_OP_SEND_STATUS_FROM_SERVER:
+ break;
+ case GRPC_OP_SEND_STATUS_FROM_SERVER:
parts.push_back(
y_absl::StrFormat("SEND_STATUS_FROM_SERVER status=%d details=",
op->data.send_status_from_server.status));
- if (op->data.send_status_from_server.status_details != nullptr) {
+ if (op->data.send_status_from_server.status_details != nullptr) {
char* dump = grpc_dump_slice(
*op->data.send_status_from_server.status_details, GPR_DUMP_ASCII);
parts.push_back(dump);
gpr_free(dump);
- } else {
+ } else {
parts.push_back("(null)");
- }
+ }
add_metadata(op->data.send_status_from_server.trailing_metadata,
op->data.send_status_from_server.trailing_metadata_count,
&parts);
- break;
- case GRPC_OP_RECV_INITIAL_METADATA:
+ break;
+ case GRPC_OP_RECV_INITIAL_METADATA:
parts.push_back(y_absl::StrFormat(
"RECV_INITIAL_METADATA ptr=%p",
op->data.recv_initial_metadata.recv_initial_metadata));
- break;
- case GRPC_OP_RECV_MESSAGE:
+ break;
+ case GRPC_OP_RECV_MESSAGE:
parts.push_back(y_absl::StrFormat("RECV_MESSAGE ptr=%p",
op->data.recv_message.recv_message));
- break;
- case GRPC_OP_RECV_STATUS_ON_CLIENT:
+ break;
+ case GRPC_OP_RECV_STATUS_ON_CLIENT:
parts.push_back(y_absl::StrFormat(
"RECV_STATUS_ON_CLIENT metadata=%p status=%p details=%p",
op->data.recv_status_on_client.trailing_metadata,
op->data.recv_status_on_client.status,
op->data.recv_status_on_client.status_details));
- break;
- case GRPC_OP_RECV_CLOSE_ON_SERVER:
+ break;
+ case GRPC_OP_RECV_CLOSE_ON_SERVER:
parts.push_back(y_absl::StrFormat("RECV_CLOSE_ON_SERVER cancelled=%p",
op->data.recv_close_on_server.cancelled));
- }
+ }
return y_absl::StrJoin(parts, "");
-}
-
-void grpc_call_log_batch(const char* file, int line, gpr_log_severity severity,
+}
+
+void grpc_call_log_batch(const char* file, int line, gpr_log_severity severity,
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/call_test_only.h b/contrib/libs/grpc/src/core/lib/surface/call_test_only.h
index dbd1a866cae..7e8fff8634a 100644
--- a/contrib/libs/grpc/src/core/lib/surface/call_test_only.h
+++ b/contrib/libs/grpc/src/core/lib/surface/call_test_only.h
@@ -1,43 +1,43 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_CALL_TEST_ONLY_H
#define GRPC_CORE_LIB_SURFACE_CALL_TEST_ONLY_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/grpc.h>
-/** Return the message compression algorithm from \a call.
+/** Return the message compression algorithm from \a call.
*
* \warning This function should \b only be used in test code. */
grpc_compression_algorithm grpc_call_test_only_get_compression_algorithm(
- grpc_call* call);
+ grpc_call* call);
/** Return the message flags from \a call.
*
* \warning This function should \b only be used in test code. */
-uint32_t grpc_call_test_only_get_message_flags(grpc_call* call);
+uint32_t grpc_call_test_only_get_message_flags(grpc_call* call);
/** Returns a bitset for the encodings (compression algorithms) supported by \a
* call's peer.
*
* To be indexed by grpc_compression_algorithm enum values. */
-uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call* call);
+uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call* call);
#endif /* GRPC_CORE_LIB_SURFACE_CALL_TEST_ONLY_H */
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel.cc b/contrib/libs/grpc/src/core/lib/surface/channel.cc
index 28df8e61ee6..000128e8ad7 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/channel.cc
@@ -1,119 +1,119 @@
-/*
- *
- * 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/surface/channel.h"
-
-#include <inttypes.h>
-#include <limits.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/compression.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/channel/channel_trace.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/surface/channel.h"
+
+#include <inttypes.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/compression.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/channel/channel_trace.h"
#include "src/core/lib/channel/channelz.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"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/debug/stats.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/gprpp/manual_constructor.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/ref_counted_ptr.h"
+#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/resource_quota.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-/** Cache grpc-status: X mdelems for X = 0..NUM_CACHED_STATUS_ELEMS.
- * Avoids needing to take a metadata context lock for sending status
- * if the status code is <= NUM_CACHED_STATUS_ELEMS.
- * Sized to allow the most commonly used codes to fit in
- * (OK, Cancelled, Unknown). */
-#define NUM_CACHED_STATUS_ELEMS 3
-
-static void destroy_channel(void* arg, grpc_error* error);
-
-grpc_channel* grpc_channel_create_with_builder(
- grpc_channel_stack_builder* builder,
- grpc_channel_stack_type channel_stack_type) {
- char* target = gpr_strdup(grpc_channel_stack_builder_get_target(builder));
- grpc_channel_args* args = grpc_channel_args_copy(
- grpc_channel_stack_builder_get_channel_arguments(builder));
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+/** Cache grpc-status: X mdelems for X = 0..NUM_CACHED_STATUS_ELEMS.
+ * Avoids needing to take a metadata context lock for sending status
+ * if the status code is <= NUM_CACHED_STATUS_ELEMS.
+ * Sized to allow the most commonly used codes to fit in
+ * (OK, Cancelled, Unknown). */
+#define NUM_CACHED_STATUS_ELEMS 3
+
+static void destroy_channel(void* arg, grpc_error* error);
+
+grpc_channel* grpc_channel_create_with_builder(
+ grpc_channel_stack_builder* builder,
+ grpc_channel_stack_type channel_stack_type) {
+ char* target = gpr_strdup(grpc_channel_stack_builder_get_target(builder));
+ grpc_channel_args* args = grpc_channel_args_copy(
+ grpc_channel_stack_builder_get_channel_arguments(builder));
grpc_resource_user* resource_user =
grpc_channel_stack_builder_get_resource_user(builder);
- grpc_channel* channel;
- if (channel_stack_type == GRPC_SERVER_CHANNEL) {
- GRPC_STATS_INC_SERVER_CHANNELS_CREATED();
- } else {
- GRPC_STATS_INC_CLIENT_CHANNELS_CREATED();
- }
- grpc_error* error = grpc_channel_stack_builder_finish(
- builder, sizeof(grpc_channel), 1, destroy_channel, nullptr,
- reinterpret_cast<void**>(&channel));
- if (error != GRPC_ERROR_NONE) {
- gpr_log(GPR_ERROR, "channel stack builder failed: %s",
- grpc_error_string(error));
- GRPC_ERROR_UNREF(error);
- gpr_free(target);
- grpc_channel_args_destroy(args);
- return channel;
- }
- channel->target = target;
+ grpc_channel* channel;
+ if (channel_stack_type == GRPC_SERVER_CHANNEL) {
+ GRPC_STATS_INC_SERVER_CHANNELS_CREATED();
+ } else {
+ GRPC_STATS_INC_CLIENT_CHANNELS_CREATED();
+ }
+ grpc_error* error = grpc_channel_stack_builder_finish(
+ builder, sizeof(grpc_channel), 1, destroy_channel, nullptr,
+ reinterpret_cast<void**>(&channel));
+ if (error != GRPC_ERROR_NONE) {
+ gpr_log(GPR_ERROR, "channel stack builder failed: %s",
+ grpc_error_string(error));
+ GRPC_ERROR_UNREF(error);
+ gpr_free(target);
+ grpc_channel_args_destroy(args);
+ return channel;
+ }
+ channel->target = target;
channel->resource_user = resource_user;
- channel->is_client = grpc_channel_stack_type_is_client(channel_stack_type);
+ channel->is_client = grpc_channel_stack_type_is_client(channel_stack_type);
channel->registration_table.Init();
-
- gpr_atm_no_barrier_store(
- &channel->call_size_estimate,
+
+ gpr_atm_no_barrier_store(
+ &channel->call_size_estimate,
(gpr_atm)CHANNEL_STACK_FROM_CHANNEL(channel)->call_stack_size +
grpc_call_get_initial_size_estimate());
-
- grpc_compression_options_init(&channel->compression_options);
- for (size_t i = 0; i < args->num_args; i++) {
- if (0 ==
- strcmp(args->args[i].key, GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL)) {
- channel->compression_options.default_level.is_set = true;
- channel->compression_options.default_level.level =
- static_cast<grpc_compression_level>(grpc_channel_arg_get_integer(
- &args->args[i],
- {GRPC_COMPRESS_LEVEL_NONE, GRPC_COMPRESS_LEVEL_NONE,
- GRPC_COMPRESS_LEVEL_COUNT - 1}));
- } else if (0 == strcmp(args->args[i].key,
- GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM)) {
- channel->compression_options.default_algorithm.is_set = true;
- channel->compression_options.default_algorithm.algorithm =
- static_cast<grpc_compression_algorithm>(grpc_channel_arg_get_integer(
- &args->args[i], {GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE,
- GRPC_COMPRESS_ALGORITHMS_COUNT - 1}));
- } else if (0 ==
- strcmp(args->args[i].key,
- GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET)) {
- channel->compression_options.enabled_algorithms_bitset =
- static_cast<uint32_t>(args->args[i].value.integer) |
- 0x1; /* always support no compression */
+
+ grpc_compression_options_init(&channel->compression_options);
+ for (size_t i = 0; i < args->num_args; i++) {
+ if (0 ==
+ strcmp(args->args[i].key, GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL)) {
+ channel->compression_options.default_level.is_set = true;
+ channel->compression_options.default_level.level =
+ static_cast<grpc_compression_level>(grpc_channel_arg_get_integer(
+ &args->args[i],
+ {GRPC_COMPRESS_LEVEL_NONE, GRPC_COMPRESS_LEVEL_NONE,
+ GRPC_COMPRESS_LEVEL_COUNT - 1}));
+ } else if (0 == strcmp(args->args[i].key,
+ GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM)) {
+ channel->compression_options.default_algorithm.is_set = true;
+ channel->compression_options.default_algorithm.algorithm =
+ static_cast<grpc_compression_algorithm>(grpc_channel_arg_get_integer(
+ &args->args[i], {GRPC_COMPRESS_NONE, GRPC_COMPRESS_NONE,
+ GRPC_COMPRESS_ALGORITHMS_COUNT - 1}));
+ } else if (0 ==
+ strcmp(args->args[i].key,
+ GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET)) {
+ 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);
@@ -124,44 +124,44 @@ grpc_channel* grpc_channel_create_with_builder(
gpr_log(GPR_DEBUG,
GRPC_ARG_CHANNELZ_CHANNEL_NODE " should be a pointer");
}
- }
- }
-
- grpc_channel_args_destroy(args);
- return channel;
-}
-
-static grpc_core::UniquePtr<char> get_default_authority(
- const grpc_channel_args* input_args) {
- bool has_default_authority = false;
- char* ssl_override = nullptr;
- grpc_core::UniquePtr<char> default_authority;
- const size_t num_args = input_args != nullptr ? input_args->num_args : 0;
- for (size_t i = 0; i < num_args; ++i) {
- if (0 == strcmp(input_args->args[i].key, GRPC_ARG_DEFAULT_AUTHORITY)) {
- has_default_authority = true;
- } else if (0 == strcmp(input_args->args[i].key,
- GRPC_SSL_TARGET_NAME_OVERRIDE_ARG)) {
- ssl_override = grpc_channel_arg_get_string(&input_args->args[i]);
- }
- }
- if (!has_default_authority && ssl_override != nullptr) {
- default_authority.reset(gpr_strdup(ssl_override));
- }
- return default_authority;
-}
-
-static grpc_channel_args* build_channel_args(
- const grpc_channel_args* input_args, char* default_authority) {
- grpc_arg new_args[1];
- size_t num_new_args = 0;
- if (default_authority != nullptr) {
- new_args[num_new_args++] = grpc_channel_arg_string_create(
- const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY), default_authority);
- }
- return grpc_channel_args_copy_and_add(input_args, new_args, num_new_args);
-}
-
+ }
+ }
+
+ grpc_channel_args_destroy(args);
+ return channel;
+}
+
+static grpc_core::UniquePtr<char> get_default_authority(
+ const grpc_channel_args* input_args) {
+ bool has_default_authority = false;
+ char* ssl_override = nullptr;
+ grpc_core::UniquePtr<char> default_authority;
+ const size_t num_args = input_args != nullptr ? input_args->num_args : 0;
+ for (size_t i = 0; i < num_args; ++i) {
+ if (0 == strcmp(input_args->args[i].key, GRPC_ARG_DEFAULT_AUTHORITY)) {
+ has_default_authority = true;
+ } else if (0 == strcmp(input_args->args[i].key,
+ GRPC_SSL_TARGET_NAME_OVERRIDE_ARG)) {
+ ssl_override = grpc_channel_arg_get_string(&input_args->args[i]);
+ }
+ }
+ if (!has_default_authority && ssl_override != nullptr) {
+ default_authority.reset(gpr_strdup(ssl_override));
+ }
+ return default_authority;
+}
+
+static grpc_channel_args* build_channel_args(
+ const grpc_channel_args* input_args, char* default_authority) {
+ grpc_arg new_args[1];
+ size_t num_new_args = 0;
+ if (default_authority != nullptr) {
+ new_args[num_new_args++] = grpc_channel_arg_string_create(
+ const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY), default_authority);
+ }
+ return grpc_channel_args_copy_and_add(input_args, new_args, num_new_args);
+}
+
namespace {
void* channelz_node_copy(void* p) {
@@ -169,7 +169,7 @@ void* channelz_node_copy(void* p) {
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);
@@ -178,7 +178,7 @@ void channelz_node_destroy(void* 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);
@@ -215,9 +215,9 @@ void CreateChannelzNode(grpc_channel_stack_builder* builder) {
} // namespace
-grpc_channel* grpc_channel_create(const char* target,
- const grpc_channel_args* input_args,
- grpc_channel_stack_type channel_stack_type,
+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
@@ -237,11 +237,11 @@ grpc_channel* grpc_channel_create(const char* target,
// 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());
+ 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();
@@ -249,19 +249,19 @@ grpc_channel* grpc_channel_create(const char* target,
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);
- grpc_channel_stack_builder_set_transport(builder, optional_transport);
+ grpc_channel_stack_builder_set_channel_arguments(builder, args);
+ grpc_channel_args_destroy(args);
+ grpc_channel_stack_builder_set_target(builder, target);
+ grpc_channel_stack_builder_set_transport(builder, optional_transport);
grpc_channel_stack_builder_set_resource_user(builder, resource_user);
- if (!grpc_channel_init_create_stack(builder, channel_stack_type)) {
- grpc_channel_stack_builder_destroy(builder);
+ if (!grpc_channel_init_create_stack(builder, channel_stack_type)) {
+ grpc_channel_stack_builder_destroy(builder);
if (resource_user != nullptr) {
grpc_resource_user_free(resource_user, GRPC_RESOURCE_QUOTA_CHANNEL_SIZE);
}
grpc_shutdown(); // Since we won't call destroy_channel().
- return nullptr;
- }
+ 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)) {
@@ -273,57 +273,57 @@ grpc_channel* grpc_channel_create(const char* target,
grpc_shutdown(); // Since we won't call destroy_channel().
}
return channel;
-}
-
-size_t grpc_channel_get_call_size_estimate(grpc_channel* channel) {
-#define ROUND_UP_SIZE 256
- /* We round up our current estimate to the NEXT value of ROUND_UP_SIZE.
- This ensures:
- 1. a consistent size allocation when our estimate is drifting slowly
- (which is common) - which tends to help most allocators reuse memory
- 2. a small amount of allowed growth over the estimate without hitting
- the arena size doubling case, reducing overall memory usage */
- return (static_cast<size_t>(
- gpr_atm_no_barrier_load(&channel->call_size_estimate)) +
- 2 * ROUND_UP_SIZE) &
- ~static_cast<size_t>(ROUND_UP_SIZE - 1);
-}
-
-void grpc_channel_update_call_size_estimate(grpc_channel* channel,
- size_t size) {
- size_t cur = static_cast<size_t>(
- gpr_atm_no_barrier_load(&channel->call_size_estimate));
- if (cur < size) {
- /* size grew: update estimate */
- gpr_atm_no_barrier_cas(&channel->call_size_estimate,
- static_cast<gpr_atm>(cur),
- static_cast<gpr_atm>(size));
- /* if we lose: never mind, something else will likely update soon enough */
- } else if (cur == size) {
- /* no change: holding pattern */
- } else if (cur > 0) {
- /* size shrank: decrease estimate */
- gpr_atm_no_barrier_cas(
- &channel->call_size_estimate, static_cast<gpr_atm>(cur),
- static_cast<gpr_atm>(GPR_MIN(cur - 1, (255 * cur + size) / 256)));
- /* if we lose: never mind, something else will likely update soon enough */
- }
-}
-
-char* grpc_channel_get_target(grpc_channel* channel) {
- GRPC_API_TRACE("grpc_channel_get_target(channel=%p)", 1, (channel));
- return gpr_strdup(channel->target);
-}
-
-void grpc_channel_get_info(grpc_channel* channel,
- const grpc_channel_info* channel_info) {
+}
+
+size_t grpc_channel_get_call_size_estimate(grpc_channel* channel) {
+#define ROUND_UP_SIZE 256
+ /* We round up our current estimate to the NEXT value of ROUND_UP_SIZE.
+ This ensures:
+ 1. a consistent size allocation when our estimate is drifting slowly
+ (which is common) - which tends to help most allocators reuse memory
+ 2. a small amount of allowed growth over the estimate without hitting
+ the arena size doubling case, reducing overall memory usage */
+ return (static_cast<size_t>(
+ gpr_atm_no_barrier_load(&channel->call_size_estimate)) +
+ 2 * ROUND_UP_SIZE) &
+ ~static_cast<size_t>(ROUND_UP_SIZE - 1);
+}
+
+void grpc_channel_update_call_size_estimate(grpc_channel* channel,
+ size_t size) {
+ size_t cur = static_cast<size_t>(
+ gpr_atm_no_barrier_load(&channel->call_size_estimate));
+ if (cur < size) {
+ /* size grew: update estimate */
+ gpr_atm_no_barrier_cas(&channel->call_size_estimate,
+ static_cast<gpr_atm>(cur),
+ static_cast<gpr_atm>(size));
+ /* if we lose: never mind, something else will likely update soon enough */
+ } else if (cur == size) {
+ /* no change: holding pattern */
+ } else if (cur > 0) {
+ /* size shrank: decrease estimate */
+ gpr_atm_no_barrier_cas(
+ &channel->call_size_estimate, static_cast<gpr_atm>(cur),
+ static_cast<gpr_atm>(GPR_MIN(cur - 1, (255 * cur + size) / 256)));
+ /* if we lose: never mind, something else will likely update soon enough */
+ }
+}
+
+char* grpc_channel_get_target(grpc_channel* channel) {
+ GRPC_API_TRACE("grpc_channel_get_target(channel=%p)", 1, (channel));
+ return gpr_strdup(channel->target);
+}
+
+void grpc_channel_get_info(grpc_channel* channel,
+ const grpc_channel_info* channel_info) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_channel_element* elem =
- grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0);
- elem->filter->get_channel_info(elem, channel_info);
-}
-
+ grpc_core::ExecCtx exec_ctx;
+ grpc_channel_element* elem =
+ grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0);
+ elem->filter->get_channel_info(elem, channel_info);
+}
+
void grpc_channel_reset_connect_backoff(grpc_channel* channel) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
grpc_core::ExecCtx exec_ctx;
@@ -336,71 +336,71 @@ void grpc_channel_reset_connect_backoff(grpc_channel* channel) {
elem->filter->start_transport_op(elem, op);
}
-static grpc_call* grpc_channel_create_call_internal(
- grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
- grpc_completion_queue* cq, grpc_pollset_set* pollset_set_alternative,
- grpc_mdelem path_mdelem, grpc_mdelem authority_mdelem,
- grpc_millis deadline) {
- grpc_mdelem send_metadata[2];
- size_t num_metadata = 0;
-
- GPR_ASSERT(channel->is_client);
- GPR_ASSERT(!(cq != nullptr && pollset_set_alternative != nullptr));
-
- send_metadata[num_metadata++] = path_mdelem;
- if (!GRPC_MDISNULL(authority_mdelem)) {
- send_metadata[num_metadata++] = authority_mdelem;
- }
-
- grpc_call_create_args args;
- args.channel = channel;
+static grpc_call* grpc_channel_create_call_internal(
+ grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
+ grpc_completion_queue* cq, grpc_pollset_set* pollset_set_alternative,
+ grpc_mdelem path_mdelem, grpc_mdelem authority_mdelem,
+ grpc_millis deadline) {
+ grpc_mdelem send_metadata[2];
+ size_t num_metadata = 0;
+
+ GPR_ASSERT(channel->is_client);
+ GPR_ASSERT(!(cq != nullptr && pollset_set_alternative != nullptr));
+
+ send_metadata[num_metadata++] = path_mdelem;
+ if (!GRPC_MDISNULL(authority_mdelem)) {
+ send_metadata[num_metadata++] = authority_mdelem;
+ }
+
+ grpc_call_create_args args;
+ args.channel = channel;
args.server = nullptr;
- args.parent = parent_call;
- args.propagation_mask = propagation_mask;
- args.cq = cq;
- args.pollset_set_alternative = pollset_set_alternative;
- args.server_transport_data = nullptr;
- args.add_initial_metadata = send_metadata;
- args.add_initial_metadata_count = num_metadata;
- args.send_deadline = deadline;
-
- grpc_call* call;
- GRPC_LOG_IF_ERROR("call_create", grpc_call_create(&args, &call));
- return call;
-}
-
-grpc_call* grpc_channel_create_call(grpc_channel* channel,
- grpc_call* parent_call,
- uint32_t propagation_mask,
- grpc_completion_queue* cq,
- grpc_slice method, const grpc_slice* host,
- gpr_timespec deadline, void* reserved) {
- GPR_ASSERT(!reserved);
+ args.parent = parent_call;
+ args.propagation_mask = propagation_mask;
+ args.cq = cq;
+ args.pollset_set_alternative = pollset_set_alternative;
+ args.server_transport_data = nullptr;
+ args.add_initial_metadata = send_metadata;
+ args.add_initial_metadata_count = num_metadata;
+ args.send_deadline = deadline;
+
+ grpc_call* call;
+ GRPC_LOG_IF_ERROR("call_create", grpc_call_create(&args, &call));
+ return call;
+}
+
+grpc_call* grpc_channel_create_call(grpc_channel* channel,
+ grpc_call* parent_call,
+ uint32_t propagation_mask,
+ grpc_completion_queue* cq,
+ grpc_slice method, const grpc_slice* host,
+ gpr_timespec deadline, void* reserved) {
+ GPR_ASSERT(!reserved);
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_call* call = grpc_channel_create_call_internal(
- channel, parent_call, propagation_mask, cq, nullptr,
+ grpc_core::ExecCtx exec_ctx;
+ grpc_call* call = grpc_channel_create_call_internal(
+ channel, parent_call, propagation_mask, cq, nullptr,
grpc_mdelem_create(GRPC_MDSTR_PATH, method, nullptr),
host != nullptr ? grpc_mdelem_create(GRPC_MDSTR_AUTHORITY, *host, nullptr)
- : GRPC_MDNULL,
- grpc_timespec_to_millis_round_up(deadline));
-
- return call;
-}
-
-grpc_call* grpc_channel_create_pollset_set_call(
- grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
+ : GRPC_MDNULL,
+ grpc_timespec_to_millis_round_up(deadline));
+
+ return call;
+}
+
+grpc_call* grpc_channel_create_pollset_set_call(
+ grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
grpc_pollset_set* pollset_set, const grpc_slice& method,
const grpc_slice* host, grpc_millis deadline, void* reserved) {
- GPR_ASSERT(!reserved);
- return grpc_channel_create_call_internal(
- channel, parent_call, propagation_mask, nullptr, pollset_set,
+ GPR_ASSERT(!reserved);
+ return grpc_channel_create_call_internal(
+ channel, parent_call, propagation_mask, nullptr, pollset_set,
grpc_mdelem_create(GRPC_MDSTR_PATH, method, nullptr),
host != nullptr ? grpc_mdelem_create(GRPC_MDSTR_AUTHORITY, *host, nullptr)
- : GRPC_MDNULL,
- deadline);
-}
-
+ : GRPC_MDNULL,
+ deadline);
+}
+
namespace grpc_core {
RegisteredCall::RegisteredCall(const char* method_arg, const char* host_arg)
@@ -441,15 +441,15 @@ RegisteredCall::~RegisteredCall() {
} // namespace grpc_core
-void* grpc_channel_register_call(grpc_channel* channel, const char* method,
- const char* host, void* reserved) {
- GRPC_API_TRACE(
- "grpc_channel_register_call(channel=%p, method=%s, host=%s, reserved=%p)",
- 4, (channel, method, host, reserved));
- GPR_ASSERT(!reserved);
+void* grpc_channel_register_call(grpc_channel* channel, const char* method,
+ const char* host, void* reserved) {
+ GRPC_API_TRACE(
+ "grpc_channel_register_call(channel=%p, method=%s, host=%s, reserved=%p)",
+ 4, (channel, method, host, reserved));
+ GPR_ASSERT(!reserved);
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
-
+ grpc_core::ExecCtx exec_ctx;
+
grpc_core::MutexLock lock(&channel->registration_table->mu);
channel->registration_table->method_registration_attempts++;
auto key = std::make_pair(TString(host != nullptr ? host : ""),
@@ -461,69 +461,69 @@ void* grpc_channel_register_call(grpc_channel* channel, const char* method,
auto insertion_result = channel->registration_table->map.insert(
{std::move(key), grpc_core::RegisteredCall(method, host)});
return &insertion_result.first->second;
-}
-
-grpc_call* grpc_channel_create_registered_call(
- grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
- grpc_completion_queue* completion_queue, void* registered_call_handle,
- gpr_timespec deadline, void* reserved) {
+}
+
+grpc_call* grpc_channel_create_registered_call(
+ grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
+ grpc_completion_queue* completion_queue, void* registered_call_handle,
+ gpr_timespec deadline, void* reserved) {
grpc_core::RegisteredCall* rc =
static_cast<grpc_core::RegisteredCall*>(registered_call_handle);
- GRPC_API_TRACE(
- "grpc_channel_create_registered_call("
- "channel=%p, parent_call=%p, propagation_mask=%x, completion_queue=%p, "
- "registered_call_handle=%p, "
- "deadline=gpr_timespec { tv_sec: %" PRId64
- ", tv_nsec: %d, clock_type: %d }, "
- "reserved=%p)",
- 9,
- (channel, parent_call, (unsigned)propagation_mask, completion_queue,
- registered_call_handle, deadline.tv_sec, deadline.tv_nsec,
- (int)deadline.clock_type, reserved));
- GPR_ASSERT(!reserved);
+ GRPC_API_TRACE(
+ "grpc_channel_create_registered_call("
+ "channel=%p, parent_call=%p, propagation_mask=%x, completion_queue=%p, "
+ "registered_call_handle=%p, "
+ "deadline=gpr_timespec { tv_sec: %" PRId64
+ ", tv_nsec: %d, clock_type: %d }, "
+ "reserved=%p)",
+ 9,
+ (channel, parent_call, (unsigned)propagation_mask, completion_queue,
+ registered_call_handle, deadline.tv_sec, deadline.tv_nsec,
+ (int)deadline.clock_type, reserved));
+ GPR_ASSERT(!reserved);
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_call* call = grpc_channel_create_call_internal(
- channel, parent_call, propagation_mask, completion_queue, nullptr,
- GRPC_MDELEM_REF(rc->path), GRPC_MDELEM_REF(rc->authority),
- grpc_timespec_to_millis_round_up(deadline));
-
- return call;
-}
-
+ grpc_core::ExecCtx exec_ctx;
+ grpc_call* call = grpc_channel_create_call_internal(
+ channel, parent_call, propagation_mask, completion_queue, nullptr,
+ GRPC_MDELEM_REF(rc->path), GRPC_MDELEM_REF(rc->authority),
+ grpc_timespec_to_millis_round_up(deadline));
+
+ return call;
+}
+
static void destroy_channel(void* arg, grpc_error* /*error*/) {
- grpc_channel* channel = static_cast<grpc_channel*>(arg);
+ grpc_channel* channel = static_cast<grpc_channel*>(arg);
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();
}
- grpc_channel_stack_destroy(CHANNEL_STACK_FROM_CHANNEL(channel));
+ grpc_channel_stack_destroy(CHANNEL_STACK_FROM_CHANNEL(channel));
channel->registration_table.Destroy();
if (channel->resource_user != nullptr) {
grpc_resource_user_free(channel->resource_user,
GRPC_RESOURCE_QUOTA_CHANNEL_SIZE);
}
- gpr_free(channel->target);
- gpr_free(channel);
+ gpr_free(channel->target);
+ gpr_free(channel);
// See comment in grpc_channel_create() for why we do this.
grpc_shutdown();
-}
-
+}
+
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));
- op->disconnect_with_error =
- GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel Destroyed");
- elem = grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0);
- elem->filter->start_transport_op(elem, op);
- GRPC_CHANNEL_INTERNAL_UNREF(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));
+ op->disconnect_with_error =
+ GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel Destroyed");
+ elem = grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0);
+ elem->filter->start_transport_op(elem, op);
+ GRPC_CHANNEL_INTERNAL_UNREF(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);
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel.h b/contrib/libs/grpc/src/core/lib/surface/channel.h
index e49b9261f71..c175fca80a3 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel.h
+++ b/contrib/libs/grpc/src/core/lib/surface/channel.h
@@ -1,37 +1,37 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_CHANNEL_H
#define GRPC_CORE_LIB_SURFACE_CHANNEL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <map>
#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/channel/channel_stack_builder.h"
+#include "src/core/lib/channel/channel_stack_builder.h"
#include "src/core/lib/channel/channelz.h"
#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/surface/channel_stack_type.h"
#include "src/core/lib/transport/metadata.h"
-grpc_channel* grpc_channel_create(const char* target,
- const grpc_channel_args* args,
+grpc_channel* grpc_channel_create(const char* target,
+ const grpc_channel_args* args,
grpc_channel_stack_type channel_stack_type,
grpc_transport* optional_transport,
grpc_resource_user* resource_user = nullptr);
@@ -40,10 +40,10 @@ grpc_channel* grpc_channel_create(const char* target,
* 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);
-
+grpc_channel* grpc_channel_create_with_builder(
+ grpc_channel_stack_builder* builder,
+ grpc_channel_stack_type channel_stack_type);
+
/** Create a call given a grpc_channel, in order to call \a method.
Progress is tied to activity on \a pollset_set. The returned call object is
meant to be used with \a grpc_call_start_batch_and_execute, which relies on
@@ -52,20 +52,20 @@ grpc_channel* grpc_channel_create_with_builder(
non-NULL, it must be a server-side call. It will be used to propagate
properties from the server call to this new client call, depending on the
value of \a propagation_mask (see propagation_bits.h for possible values) */
-grpc_call* grpc_channel_create_pollset_set_call(
- grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
+grpc_call* grpc_channel_create_pollset_set_call(
+ grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask,
grpc_pollset_set* pollset_set, const grpc_slice& method,
const grpc_slice* host, grpc_millis deadline, void* reserved);
/** Get a (borrowed) pointer to this channels underlying channel stack */
-grpc_channel_stack* grpc_channel_get_channel_stack(grpc_channel* channel);
+grpc_channel_stack* grpc_channel_get_channel_stack(grpc_channel* channel);
grpc_core::channelz::ChannelNode* grpc_channel_get_channelz_node(
grpc_channel* channel);
-size_t grpc_channel_get_call_size_estimate(grpc_channel* channel);
-void grpc_channel_update_call_size_estimate(grpc_channel* channel, size_t size);
-
+size_t grpc_channel_get_call_size_estimate(grpc_channel* channel);
+void grpc_channel_update_call_size_estimate(grpc_channel* channel, size_t size);
+
namespace grpc_core {
struct RegisteredCall {
@@ -135,7 +135,7 @@ inline grpc_core::channelz::ChannelNode* grpc_channel_get_channelz_node(
return channel->channelz_node.get();
}
-#ifndef NDEBUG
+#ifndef NDEBUG
inline void grpc_channel_internal_ref(grpc_channel* channel,
const char* reason) {
GRPC_CHANNEL_STACK_REF(CHANNEL_STACK_FROM_CHANNEL(channel), reason);
@@ -146,8 +146,8 @@ inline void grpc_channel_internal_unref(grpc_channel* channel,
}
#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)
+#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");
@@ -157,13 +157,13 @@ inline void grpc_channel_internal_unref(grpc_channel* channel) {
}
#define GRPC_CHANNEL_INTERNAL_REF(channel, reason) \
grpc_channel_internal_ref(channel)
-#define GRPC_CHANNEL_INTERNAL_UNREF(channel, reason) \
- grpc_channel_internal_unref(channel)
+#define GRPC_CHANNEL_INTERNAL_UNREF(channel, reason) \
+ grpc_channel_internal_unref(channel)
#endif
// Return the channel's compression options.
grpc_compression_options grpc_channel_compression_options(
- const grpc_channel* channel);
+ const grpc_channel* channel);
// Ping the channels peer (load balanced channels will select one sub-channel to
// ping); if the channel is not connected, posts a failed.
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel_init.cc b/contrib/libs/grpc/src/core/lib/surface/channel_init.cc
index 62eb1c3f9d6..e065d561942 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel_init.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/channel_init.cc
@@ -1,109 +1,109 @@
-/*
- *
- * 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/surface/channel_init.h"
-
-#include <grpc/support/alloc.h>
-
-typedef struct stage_slot {
- grpc_channel_init_stage fn;
- void* arg;
- int priority;
- size_t insertion_order;
-} stage_slot;
-
-typedef struct stage_slots {
- stage_slot* slots;
- size_t num_slots;
- size_t cap_slots;
-} stage_slots;
-
-static stage_slots g_slots[GRPC_NUM_CHANNEL_STACK_TYPES];
-static bool g_finalized;
-
-void grpc_channel_init_init(void) {
- for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) {
- g_slots[i].slots = nullptr;
- g_slots[i].num_slots = 0;
- g_slots[i].cap_slots = 0;
- }
- g_finalized = false;
-}
-
-void grpc_channel_init_register_stage(grpc_channel_stack_type type,
- int priority,
- grpc_channel_init_stage stage,
- void* stage_arg) {
- GPR_ASSERT(!g_finalized);
- if (g_slots[type].cap_slots == g_slots[type].num_slots) {
- g_slots[type].cap_slots = GPR_MAX(8, 3 * g_slots[type].cap_slots / 2);
- g_slots[type].slots = static_cast<stage_slot*>(
- gpr_realloc(g_slots[type].slots,
- g_slots[type].cap_slots * sizeof(*g_slots[type].slots)));
- }
- stage_slot* s = &g_slots[type].slots[g_slots[type].num_slots++];
- s->insertion_order = g_slots[type].num_slots;
- s->priority = priority;
- s->fn = stage;
- s->arg = stage_arg;
-}
-
-static int compare_slots(const void* a, const void* b) {
- const stage_slot* sa = static_cast<const stage_slot*>(a);
- const stage_slot* sb = static_cast<const stage_slot*>(b);
-
- int c = GPR_ICMP(sa->priority, sb->priority);
- if (c != 0) return c;
- return GPR_ICMP(sa->insertion_order, sb->insertion_order);
-}
-
-void grpc_channel_init_finalize(void) {
- GPR_ASSERT(!g_finalized);
- for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) {
- qsort(g_slots[i].slots, g_slots[i].num_slots, sizeof(*g_slots[i].slots),
- compare_slots);
- }
- g_finalized = true;
-}
-
-void grpc_channel_init_shutdown(void) {
- for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) {
- gpr_free(g_slots[i].slots);
- g_slots[i].slots =
- static_cast<stage_slot*>((void*)static_cast<uintptr_t>(0xdeadbeef));
- }
-}
-
-bool grpc_channel_init_create_stack(grpc_channel_stack_builder* builder,
- grpc_channel_stack_type type) {
- GPR_ASSERT(g_finalized);
-
- grpc_channel_stack_builder_set_name(builder,
- grpc_channel_stack_type_string(type));
-
- for (size_t i = 0; i < g_slots[type].num_slots; i++) {
- const stage_slot* slot = &g_slots[type].slots[i];
- if (!slot->fn(builder, slot->arg)) {
- return false;
- }
- }
-
- return true;
-}
+/*
+ *
+ * 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/surface/channel_init.h"
+
+#include <grpc/support/alloc.h>
+
+typedef struct stage_slot {
+ grpc_channel_init_stage fn;
+ void* arg;
+ int priority;
+ size_t insertion_order;
+} stage_slot;
+
+typedef struct stage_slots {
+ stage_slot* slots;
+ size_t num_slots;
+ size_t cap_slots;
+} stage_slots;
+
+static stage_slots g_slots[GRPC_NUM_CHANNEL_STACK_TYPES];
+static bool g_finalized;
+
+void grpc_channel_init_init(void) {
+ for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) {
+ g_slots[i].slots = nullptr;
+ g_slots[i].num_slots = 0;
+ g_slots[i].cap_slots = 0;
+ }
+ g_finalized = false;
+}
+
+void grpc_channel_init_register_stage(grpc_channel_stack_type type,
+ int priority,
+ grpc_channel_init_stage stage,
+ void* stage_arg) {
+ GPR_ASSERT(!g_finalized);
+ if (g_slots[type].cap_slots == g_slots[type].num_slots) {
+ g_slots[type].cap_slots = GPR_MAX(8, 3 * g_slots[type].cap_slots / 2);
+ g_slots[type].slots = static_cast<stage_slot*>(
+ gpr_realloc(g_slots[type].slots,
+ g_slots[type].cap_slots * sizeof(*g_slots[type].slots)));
+ }
+ stage_slot* s = &g_slots[type].slots[g_slots[type].num_slots++];
+ s->insertion_order = g_slots[type].num_slots;
+ s->priority = priority;
+ s->fn = stage;
+ s->arg = stage_arg;
+}
+
+static int compare_slots(const void* a, const void* b) {
+ const stage_slot* sa = static_cast<const stage_slot*>(a);
+ const stage_slot* sb = static_cast<const stage_slot*>(b);
+
+ int c = GPR_ICMP(sa->priority, sb->priority);
+ if (c != 0) return c;
+ return GPR_ICMP(sa->insertion_order, sb->insertion_order);
+}
+
+void grpc_channel_init_finalize(void) {
+ GPR_ASSERT(!g_finalized);
+ for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) {
+ qsort(g_slots[i].slots, g_slots[i].num_slots, sizeof(*g_slots[i].slots),
+ compare_slots);
+ }
+ g_finalized = true;
+}
+
+void grpc_channel_init_shutdown(void) {
+ for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) {
+ gpr_free(g_slots[i].slots);
+ g_slots[i].slots =
+ static_cast<stage_slot*>((void*)static_cast<uintptr_t>(0xdeadbeef));
+ }
+}
+
+bool grpc_channel_init_create_stack(grpc_channel_stack_builder* builder,
+ grpc_channel_stack_type type) {
+ GPR_ASSERT(g_finalized);
+
+ grpc_channel_stack_builder_set_name(builder,
+ grpc_channel_stack_type_string(type));
+
+ for (size_t i = 0; i < g_slots[type].num_slots; i++) {
+ const stage_slot* slot = &g_slots[type].slots[i];
+ if (!slot->fn(builder, slot->arg)) {
+ return false;
+ }
+ }
+
+ return true;
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel_init.h b/contrib/libs/grpc/src/core/lib/surface/channel_init.h
index d17a721606d..e989d1ad2ae 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel_init.h
+++ b/contrib/libs/grpc/src/core/lib/surface/channel_init.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_CHANNEL_INIT_H
#define GRPC_CORE_LIB_SURFACE_CHANNEL_INIT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/channel/channel_stack_builder.h"
#include "src/core/lib/surface/channel_stack_type.h"
#include "src/core/lib/transport/transport.h"
@@ -34,8 +34,8 @@
/// One stage of mutation: call functions against \a builder to influence the
/// finally constructed channel stack
-typedef bool (*grpc_channel_init_stage)(grpc_channel_stack_builder* builder,
- void* arg);
+typedef bool (*grpc_channel_init_stage)(grpc_channel_stack_builder* builder,
+ void* arg);
/// Global initialization of the system
void grpc_channel_init_init(void);
@@ -53,7 +53,7 @@ void grpc_channel_init_init(void);
void grpc_channel_init_register_stage(grpc_channel_stack_type type,
int priority,
grpc_channel_init_stage stage_fn,
- void* stage_arg);
+ void* stage_arg);
/// Finalize registration. No more calls to grpc_channel_init_register_stage are
/// allowed.
@@ -72,7 +72,7 @@ void grpc_channel_init_shutdown(void);
/// \a optional_transport is either NULL or a constructed transport object
/// Returns a pointer to the base of the memory allocated (the actual channel
/// stack object will be prefix_bytes past that pointer)
-bool grpc_channel_init_create_stack(grpc_channel_stack_builder* builder,
+bool grpc_channel_init_create_stack(grpc_channel_stack_builder* builder,
grpc_channel_stack_type type);
#endif /* GRPC_CORE_LIB_SURFACE_CHANNEL_INIT_H */
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 82e552194b8..246a23f7722 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel_ping.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/channel_ping.cc
@@ -1,64 +1,64 @@
-/*
- *
- * 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/surface/channel.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/completion_queue.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/surface/channel.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/completion_queue.h"
+
struct ping_result {
- grpc_closure closure;
- void* tag;
- grpc_completion_queue* cq;
- grpc_cq_completion completion_storage;
+ grpc_closure closure;
+ void* tag;
+ grpc_completion_queue* cq;
+ grpc_cq_completion completion_storage;
};
static void ping_destroy(void* arg, grpc_cq_completion* /*storage*/) {
- gpr_free(arg);
-}
-
-static void ping_done(void* arg, grpc_error* error) {
- ping_result* pr = static_cast<ping_result*>(arg);
- grpc_cq_end_op(pr->cq, pr->tag, GRPC_ERROR_REF(error), ping_destroy, pr,
- &pr->completion_storage);
-}
-
-void grpc_channel_ping(grpc_channel* channel, grpc_completion_queue* cq,
- void* tag, void* reserved) {
- GRPC_API_TRACE("grpc_channel_ping(channel=%p, cq=%p, tag=%p, reserved=%p)", 4,
- (channel, cq, tag, reserved));
- grpc_transport_op* op = grpc_make_transport_op(nullptr);
- ping_result* pr = static_cast<ping_result*>(gpr_malloc(sizeof(*pr)));
- grpc_channel_element* top_elem =
- grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0);
- grpc_core::ExecCtx exec_ctx;
- GPR_ASSERT(reserved == nullptr);
- pr->tag = tag;
- pr->cq = cq;
- GRPC_CLOSURE_INIT(&pr->closure, ping_done, pr, grpc_schedule_on_exec_ctx);
- op->send_ping.on_ack = &pr->closure;
- op->bind_pollset = grpc_cq_pollset(cq);
- GPR_ASSERT(grpc_cq_begin_op(cq, tag));
- top_elem->filter->start_transport_op(top_elem, op);
-}
+ gpr_free(arg);
+}
+
+static void ping_done(void* arg, grpc_error* error) {
+ ping_result* pr = static_cast<ping_result*>(arg);
+ grpc_cq_end_op(pr->cq, pr->tag, GRPC_ERROR_REF(error), ping_destroy, pr,
+ &pr->completion_storage);
+}
+
+void grpc_channel_ping(grpc_channel* channel, grpc_completion_queue* cq,
+ void* tag, void* reserved) {
+ GRPC_API_TRACE("grpc_channel_ping(channel=%p, cq=%p, tag=%p, reserved=%p)", 4,
+ (channel, cq, tag, reserved));
+ grpc_transport_op* op = grpc_make_transport_op(nullptr);
+ ping_result* pr = static_cast<ping_result*>(gpr_malloc(sizeof(*pr)));
+ grpc_channel_element* top_elem =
+ grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0);
+ grpc_core::ExecCtx exec_ctx;
+ GPR_ASSERT(reserved == nullptr);
+ pr->tag = tag;
+ pr->cq = cq;
+ GRPC_CLOSURE_INIT(&pr->closure, ping_done, pr, grpc_schedule_on_exec_ctx);
+ op->send_ping.on_ack = &pr->closure;
+ op->bind_pollset = grpc_cq_pollset(cq);
+ GPR_ASSERT(grpc_cq_begin_op(cq, tag));
+ top_elem->filter->start_transport_op(top_elem, op);
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.cc b/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.cc
index fcf96ddc9fb..ffd222f5be5 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/log.h>
-#include "src/core/lib/surface/channel_stack_type.h"
-
-bool grpc_channel_stack_type_is_client(grpc_channel_stack_type type) {
- switch (type) {
- case GRPC_CLIENT_CHANNEL:
- return true;
- case GRPC_CLIENT_SUBCHANNEL:
- return true;
- case GRPC_CLIENT_LAME_CHANNEL:
- return true;
- case GRPC_CLIENT_DIRECT_CHANNEL:
- return true;
- case GRPC_SERVER_CHANNEL:
- return false;
- case GRPC_NUM_CHANNEL_STACK_TYPES:
- break;
- }
- GPR_UNREACHABLE_CODE(return true;);
-}
-
-const char* grpc_channel_stack_type_string(grpc_channel_stack_type type) {
- switch (type) {
- case GRPC_CLIENT_CHANNEL:
- return "CLIENT_CHANNEL";
- case GRPC_CLIENT_SUBCHANNEL:
- return "CLIENT_SUBCHANNEL";
- case GRPC_SERVER_CHANNEL:
- return "SERVER_CHANNEL";
- case GRPC_CLIENT_LAME_CHANNEL:
- return "CLIENT_LAME_CHANNEL";
- case GRPC_CLIENT_DIRECT_CHANNEL:
- return "CLIENT_DIRECT_CHANNEL";
- case GRPC_NUM_CHANNEL_STACK_TYPES:
- break;
- }
- GPR_UNREACHABLE_CODE(return "UNKNOWN");
-}
+/*
+ *
+ * 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 <grpc/support/log.h>
+#include "src/core/lib/surface/channel_stack_type.h"
+
+bool grpc_channel_stack_type_is_client(grpc_channel_stack_type type) {
+ switch (type) {
+ case GRPC_CLIENT_CHANNEL:
+ return true;
+ case GRPC_CLIENT_SUBCHANNEL:
+ return true;
+ case GRPC_CLIENT_LAME_CHANNEL:
+ return true;
+ case GRPC_CLIENT_DIRECT_CHANNEL:
+ return true;
+ case GRPC_SERVER_CHANNEL:
+ return false;
+ case GRPC_NUM_CHANNEL_STACK_TYPES:
+ break;
+ }
+ GPR_UNREACHABLE_CODE(return true;);
+}
+
+const char* grpc_channel_stack_type_string(grpc_channel_stack_type type) {
+ switch (type) {
+ case GRPC_CLIENT_CHANNEL:
+ return "CLIENT_CHANNEL";
+ case GRPC_CLIENT_SUBCHANNEL:
+ return "CLIENT_SUBCHANNEL";
+ case GRPC_SERVER_CHANNEL:
+ return "SERVER_CHANNEL";
+ case GRPC_CLIENT_LAME_CHANNEL:
+ return "CLIENT_LAME_CHANNEL";
+ case GRPC_CLIENT_DIRECT_CHANNEL:
+ return "CLIENT_DIRECT_CHANNEL";
+ case GRPC_NUM_CHANNEL_STACK_TYPES:
+ break;
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.h b/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.h
index 8a3c08e1cce..ed76a92156a 100644
--- a/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.h
+++ b/contrib/libs/grpc/src/core/lib/surface/channel_stack_type.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_CHANNEL_STACK_TYPE_H
#define GRPC_CORE_LIB_SURFACE_CHANNEL_STACK_TYPE_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdbool.h>
typedef enum {
@@ -42,6 +42,6 @@ typedef enum {
bool grpc_channel_stack_type_is_client(grpc_channel_stack_type type);
-const char* grpc_channel_stack_type_string(grpc_channel_stack_type type);
-
+const char* grpc_channel_stack_type_string(grpc_channel_stack_type type);
+
#endif /* GRPC_CORE_LIB_SURFACE_CHANNEL_STACK_TYPE_H */
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 0f50906734b..1fecf8dc98a 100644
--- a/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc
@@ -1,221 +1,221 @@
-/*
- *
- * 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.
- *
- */
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/surface/completion_queue.h"
-
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-
+/*
+ *
+ * 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.
+ *
+ */
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/surface/completion_queue.h"
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+
#include <vector>
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/support/alloc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.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/gpr/tls.h"
+#include <grpc/support/alloc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.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/gpr/tls.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"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/surface/event_string.h"
-
-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");
-
+#include "src/core/lib/iomgr/pollset.h"
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/event_string.h"
+
+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 {
-// Specifies a cq thread local cache.
-// The first event that occurs on a thread
-// with a cq cache will go into that cache, and
-// will only be returned on the thread that initialized the cache.
-// NOTE: Only one event will ever be cached.
-GPR_TLS_DECL(g_cached_event);
-GPR_TLS_DECL(g_cached_cq);
-
+// Specifies a cq thread local cache.
+// The first event that occurs on a thread
+// with a cq cache will go into that cache, and
+// will only be returned on the thread that initialized the cache.
+// NOTE: Only one event will ever be cached.
+GPR_TLS_DECL(g_cached_event);
+GPR_TLS_DECL(g_cached_cq);
+
struct plucker {
- grpc_pollset_worker** worker;
- void* tag;
+ grpc_pollset_worker** worker;
+ void* tag;
};
struct cq_poller_vtable {
- bool can_get_pollset;
- bool can_listen;
- size_t (*size)(void);
- void (*init)(grpc_pollset* pollset, gpr_mu** mu);
- grpc_error* (*kick)(grpc_pollset* pollset,
- grpc_pollset_worker* specific_worker);
- grpc_error* (*work)(grpc_pollset* pollset, grpc_pollset_worker** worker,
- grpc_millis deadline);
- void (*shutdown)(grpc_pollset* pollset, grpc_closure* closure);
- void (*destroy)(grpc_pollset* pollset);
+ bool can_get_pollset;
+ bool can_listen;
+ size_t (*size)(void);
+ void (*init)(grpc_pollset* pollset, gpr_mu** mu);
+ grpc_error* (*kick)(grpc_pollset* pollset,
+ grpc_pollset_worker* specific_worker);
+ grpc_error* (*work)(grpc_pollset* pollset, grpc_pollset_worker** worker,
+ grpc_millis deadline);
+ void (*shutdown)(grpc_pollset* pollset, grpc_closure* closure);
+ void (*destroy)(grpc_pollset* pollset);
};
-typedef struct non_polling_worker {
- gpr_cv cv;
- bool kicked;
- struct non_polling_worker* next;
- struct non_polling_worker* prev;
-} non_polling_worker;
-
+typedef struct non_polling_worker {
+ gpr_cv cv;
+ bool kicked;
+ struct non_polling_worker* next;
+ struct non_polling_worker* prev;
+} non_polling_worker;
+
struct non_polling_poller {
- gpr_mu mu;
+ gpr_mu mu;
bool kicked_without_poller;
- non_polling_worker* root;
- grpc_closure* shutdown;
+ non_polling_worker* root;
+ grpc_closure* shutdown;
};
size_t non_polling_poller_size(void) { return sizeof(non_polling_poller); }
-
+
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;
-}
-
+ 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) {
- non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
- gpr_mu_destroy(&npp->mu);
-}
-
+ 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) {
- non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
- if (npp->shutdown) return GRPC_ERROR_NONE;
+ non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
+ if (npp->shutdown) return GRPC_ERROR_NONE;
if (npp->kicked_without_poller) {
npp->kicked_without_poller = false;
return GRPC_ERROR_NONE;
}
- non_polling_worker w;
- gpr_cv_init(&w.cv);
- if (worker != nullptr) *worker = reinterpret_cast<grpc_pollset_worker*>(&w);
- if (npp->root == nullptr) {
- npp->root = w.next = w.prev = &w;
- } else {
- w.next = npp->root;
- w.prev = w.next->prev;
- w.next->prev = w.prev->next = &w;
- }
- w.kicked = false;
- gpr_timespec deadline_ts =
- grpc_millis_to_timespec(deadline, GPR_CLOCK_MONOTONIC);
- while (!npp->shutdown && !w.kicked &&
- !gpr_cv_wait(&w.cv, &npp->mu, deadline_ts))
- ;
- grpc_core::ExecCtx::Get()->InvalidateNow();
- if (&w == npp->root) {
- npp->root = w.next;
- if (&w == npp->root) {
- if (npp->shutdown) {
+ non_polling_worker w;
+ gpr_cv_init(&w.cv);
+ if (worker != nullptr) *worker = reinterpret_cast<grpc_pollset_worker*>(&w);
+ if (npp->root == nullptr) {
+ npp->root = w.next = w.prev = &w;
+ } else {
+ w.next = npp->root;
+ w.prev = w.next->prev;
+ w.next->prev = w.prev->next = &w;
+ }
+ w.kicked = false;
+ gpr_timespec deadline_ts =
+ grpc_millis_to_timespec(deadline, GPR_CLOCK_MONOTONIC);
+ while (!npp->shutdown && !w.kicked &&
+ !gpr_cv_wait(&w.cv, &npp->mu, deadline_ts))
+ ;
+ grpc_core::ExecCtx::Get()->InvalidateNow();
+ if (&w == npp->root) {
+ npp->root = w.next;
+ if (&w == npp->root) {
+ if (npp->shutdown) {
grpc_core::ExecCtx::Run(DEBUG_LOCATION, npp->shutdown, GRPC_ERROR_NONE);
- }
- npp->root = nullptr;
- }
- }
- w.next->prev = w.prev;
- w.prev->next = w.next;
- gpr_cv_destroy(&w.cv);
- if (worker != nullptr) *worker = nullptr;
- return GRPC_ERROR_NONE;
-}
-
+ }
+ npp->root = nullptr;
+ }
+ }
+ w.next->prev = w.prev;
+ w.prev->next = w.next;
+ gpr_cv_destroy(&w.cv);
+ if (worker != nullptr) *worker = nullptr;
+ return GRPC_ERROR_NONE;
+}
+
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);
- if (specific_worker != nullptr) {
- non_polling_worker* w =
- reinterpret_cast<non_polling_worker*>(specific_worker);
- if (!w->kicked) {
- w->kicked = true;
- gpr_cv_signal(&w->cv);
- }
+ non_polling_poller* p = reinterpret_cast<non_polling_poller*>(pollset);
+ if (specific_worker == nullptr)
+ specific_worker = reinterpret_cast<grpc_pollset_worker*>(p->root);
+ if (specific_worker != nullptr) {
+ non_polling_worker* w =
+ reinterpret_cast<non_polling_worker*>(specific_worker);
+ if (!w->kicked) {
+ w->kicked = true;
+ gpr_cv_signal(&w->cv);
+ }
} else {
p->kicked_without_poller = true;
- }
- return GRPC_ERROR_NONE;
-}
-
+ }
+ return GRPC_ERROR_NONE;
+}
+
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) {
+ 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);
- } else {
- non_polling_worker* w = p->root;
- do {
- gpr_cv_signal(&w->cv);
- w = w->next;
- } while (w != p->root);
- }
-}
-
+ } else {
+ non_polling_worker* w = p->root;
+ do {
+ gpr_cv_signal(&w->cv);
+ w = w->next;
+ } while (w != p->root);
+ }
+}
+
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},
- /* GRPC_CQ_NON_LISTENING */
- {true, false, grpc_pollset_size, grpc_pollset_init, grpc_pollset_kick,
- grpc_pollset_work, grpc_pollset_shutdown, grpc_pollset_destroy},
- /* GRPC_CQ_NON_POLLING */
- {false, false, non_polling_poller_size, non_polling_poller_init,
- non_polling_poller_kick, non_polling_poller_work,
- non_polling_poller_shutdown, non_polling_poller_destroy},
-};
-
+ /* GRPC_CQ_DEFAULT_POLLING */
+ {true, true, grpc_pollset_size, grpc_pollset_init, grpc_pollset_kick,
+ grpc_pollset_work, grpc_pollset_shutdown, grpc_pollset_destroy},
+ /* GRPC_CQ_NON_LISTENING */
+ {true, false, grpc_pollset_size, grpc_pollset_init, grpc_pollset_kick,
+ grpc_pollset_work, grpc_pollset_shutdown, grpc_pollset_destroy},
+ /* GRPC_CQ_NON_POLLING */
+ {false, false, non_polling_poller_size, non_polling_poller_init,
+ non_polling_poller_kick, non_polling_poller_work,
+ non_polling_poller_shutdown, non_polling_poller_destroy},
+};
+
} // namespace
struct cq_vtable {
- grpc_cq_completion_type cq_completion_type;
- size_t data_size;
+ grpc_cq_completion_type cq_completion_type;
+ size_t data_size;
void (*init)(void* data,
grpc_experimental_completion_queue_functor* shutdown_callback);
- void (*shutdown)(grpc_completion_queue* cq);
- void (*destroy)(void* data);
- 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 (*shutdown)(grpc_completion_queue* cq);
+ void (*destroy)(void* data);
+ 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);
- 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);
+ 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.
- * Only used in completion queues whose completion_type is GRPC_CQ_NEXT */
+ * Only used in completion queues whose completion_type is GRPC_CQ_NEXT */
class CqEventQueue {
public:
CqEventQueue() = default;
@@ -231,17 +231,17 @@ class CqEventQueue {
grpc_cq_completion* Pop();
private:
- /* Spinlock to serialize consumers i.e pop() operations */
+ /* Spinlock to serialize consumers i.e pop() operations */
gpr_spinlock queue_lock_ = GPR_SPINLOCK_INITIALIZER;
-
+
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 */
+
+ /* 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};
};
-
+
struct cq_next_data {
~cq_next_data() {
GPR_ASSERT(queue.num_items() == 0);
@@ -252,21 +252,21 @@ struct cq_next_data {
#endif
}
- /** Completed events for completion-queues of type GRPC_CQ_NEXT */
+ /** Completed events for completion-queues of type GRPC_CQ_NEXT */
CqEventQueue queue;
-
- /** Counter of how many things have ever been queued on this completion queue
- useful for avoiding locks to check the 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};
-
+
/** 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 */
+
+ /** 0 initially. 1 once we initiated shutdown */
bool shutdown_called = false;
};
-
+
struct cq_pluck_data {
cq_pluck_data() {
completed_tail = &completed_head;
@@ -283,31 +283,31 @@ struct cq_pluck_data {
#endif
}
- /** Completed events for completion-queues of type GRPC_CQ_PLUCK */
- grpc_cq_completion completed_head;
- grpc_cq_completion* completed_tail;
-
+ /** 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};
-
- /** Counter of how many things have ever been queued on this completion queue
- useful for avoiding locks to check the 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};
-
- /** 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 */
+
+ /** 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};
-
- /** 0 initially. 1 once we initiated shutdown */
+
+ /** 0 initially. 1 once we initiated shutdown */
bool shutdown_called = false;
-
+
int num_pluckers = 0;
- plucker pluckers[GRPC_MAX_COMPLETION_QUEUE_PLUCKERS];
+ plucker pluckers[GRPC_MAX_COMPLETION_QUEUE_PLUCKERS];
};
-
+
struct cq_callback_data {
cq_callback_data(
grpc_experimental_completion_queue_functor* shutdown_callback)
@@ -336,38 +336,38 @@ struct cq_callback_data {
} // namespace
-/* Completion queue structure */
-struct grpc_completion_queue {
- /** Once owning_refs drops to zero, we will destroy the cq */
+/* Completion queue structure */
+struct grpc_completion_queue {
+ /** Once owning_refs drops to zero, we will destroy the cq */
grpc_core::RefCount owning_refs;
-
- gpr_mu* mu;
-
- const cq_vtable* vtable;
- const cq_poller_vtable* poller_vtable;
-
-#ifndef NDEBUG
- void** outstanding_tags;
- size_t outstanding_tag_count;
- size_t outstanding_tag_capacity;
-#endif
-
- grpc_closure pollset_shutdown_done;
- int num_polls;
-};
-
-/* Forward declarations */
-static void cq_finish_shutdown_next(grpc_completion_queue* cq);
-static void cq_finish_shutdown_pluck(grpc_completion_queue* cq);
+
+ gpr_mu* mu;
+
+ const cq_vtable* vtable;
+ const cq_poller_vtable* poller_vtable;
+
+#ifndef NDEBUG
+ void** outstanding_tags;
+ size_t outstanding_tag_count;
+ size_t outstanding_tag_capacity;
+#endif
+
+ grpc_closure pollset_shutdown_done;
+ int num_polls;
+};
+
+/* Forward declarations */
+static void cq_finish_shutdown_next(grpc_completion_queue* cq);
+static void cq_finish_shutdown_pluck(grpc_completion_queue* cq);
static void cq_finish_shutdown_callback(grpc_completion_queue* cq);
-static void cq_shutdown_next(grpc_completion_queue* cq);
-static void cq_shutdown_pluck(grpc_completion_queue* cq);
+static void cq_shutdown_next(grpc_completion_queue* cq);
+static void cq_shutdown_pluck(grpc_completion_queue* cq);
static void cq_shutdown_callback(grpc_completion_queue* cq);
-
-static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* tag);
-static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* tag);
+
+static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* tag);
+static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* tag);
static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* tag);
-
+
// A cq_end_op function is called when an operation on a given CQ with
// a given tag has completed. The storage argument is a reference to the
// space reserved for this completion as it is placed into the corresponding
@@ -378,23 +378,23 @@ 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_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);
-
-static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
- gpr_timespec deadline, void* reserved);
-
+static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
+ void* reserved);
+
+static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
+ gpr_timespec deadline, void* reserved);
+
// Note that cq_init_next and cq_init_pluck do not use the shutdown_callback
static void cq_init_next(
void* data, grpc_experimental_completion_queue_functor* shutdown_callback);
@@ -402,32 +402,32 @@ static void cq_init_pluck(
void* data, grpc_experimental_completion_queue_functor* shutdown_callback);
static void cq_init_callback(
void* data, grpc_experimental_completion_queue_functor* shutdown_callback);
-static void cq_destroy_next(void* data);
-static void cq_destroy_pluck(void* data);
+static void cq_destroy_next(void* data);
+static void cq_destroy_pluck(void* data);
static void cq_destroy_callback(void* data);
-
-/* Completion queue vtables based on the completion-type */
-static const cq_vtable g_cq_vtable[] = {
- /* GRPC_CQ_NEXT */
- {GRPC_CQ_NEXT, sizeof(cq_next_data), cq_init_next, cq_shutdown_next,
- cq_destroy_next, cq_begin_op_for_next, cq_end_op_for_next, cq_next,
- nullptr},
- /* GRPC_CQ_PLUCK */
- {GRPC_CQ_PLUCK, sizeof(cq_pluck_data), cq_init_pluck, cq_shutdown_pluck,
- cq_destroy_pluck, cq_begin_op_for_pluck, cq_end_op_for_pluck, nullptr,
- cq_pluck},
+
+/* Completion queue vtables based on the completion-type */
+static const cq_vtable g_cq_vtable[] = {
+ /* GRPC_CQ_NEXT */
+ {GRPC_CQ_NEXT, sizeof(cq_next_data), cq_init_next, cq_shutdown_next,
+ cq_destroy_next, cq_begin_op_for_next, cq_end_op_for_next, cq_next,
+ nullptr},
+ /* GRPC_CQ_PLUCK */
+ {GRPC_CQ_PLUCK, sizeof(cq_pluck_data), cq_init_pluck, cq_shutdown_pluck,
+ cq_destroy_pluck, cq_begin_op_for_pluck, cq_end_op_for_pluck, nullptr,
+ cq_pluck},
/* GRPC_CQ_CALLBACK */
{GRPC_CQ_CALLBACK, sizeof(cq_callback_data), cq_init_callback,
cq_shutdown_callback, cq_destroy_callback, cq_begin_op_for_callback,
cq_end_op_for_callback, nullptr, nullptr},
-};
-
-#define DATA_FROM_CQ(cq) ((void*)(cq + 1))
-#define POLLSET_FROM_CQ(cq) \
- ((grpc_pollset*)(cq->vtable->data_size + (char*)DATA_FROM_CQ(cq)))
-
+};
+
+#define DATA_FROM_CQ(cq) ((void*)(cq + 1))
+#define POLLSET_FROM_CQ(cq) \
+ ((grpc_pollset*)(cq->vtable->data_size + (char*)DATA_FROM_CQ(cq)))
+
grpc_core::TraceFlag grpc_cq_pluck_trace(false, "queue_pluck");
-
+
#define GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, event) \
do { \
if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) && \
@@ -437,137 +437,137 @@ grpc_core::TraceFlag grpc_cq_pluck_trace(false, "queue_pluck");
grpc_event_string(event).c_str()); \
} \
} while (0)
-
-static void on_pollset_shutdown_done(void* cq, grpc_error* error);
-
-void grpc_cq_global_init() {
- gpr_tls_init(&g_cached_event);
- gpr_tls_init(&g_cached_cq);
-}
-
-void grpc_completion_queue_thread_local_cache_init(grpc_completion_queue* cq) {
- if ((grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == nullptr) {
- gpr_tls_set(&g_cached_event, (intptr_t)0);
- gpr_tls_set(&g_cached_cq, (intptr_t)cq);
- }
-}
-
-int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue* cq,
- void** tag, int* ok) {
- grpc_cq_completion* storage =
- (grpc_cq_completion*)gpr_tls_get(&g_cached_event);
- int ret = 0;
- if (storage != nullptr &&
- (grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == cq) {
- *tag = storage->tag;
- grpc_core::ExecCtx exec_ctx;
- *ok = (storage->next & static_cast<uintptr_t>(1)) == 1;
- storage->done(storage->done_arg, storage);
- ret = 1;
- cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
+
+static void on_pollset_shutdown_done(void* cq, grpc_error* error);
+
+void grpc_cq_global_init() {
+ gpr_tls_init(&g_cached_event);
+ gpr_tls_init(&g_cached_cq);
+}
+
+void grpc_completion_queue_thread_local_cache_init(grpc_completion_queue* cq) {
+ if ((grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == nullptr) {
+ gpr_tls_set(&g_cached_event, (intptr_t)0);
+ gpr_tls_set(&g_cached_cq, (intptr_t)cq);
+ }
+}
+
+int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue* cq,
+ void** tag, int* ok) {
+ grpc_cq_completion* storage =
+ (grpc_cq_completion*)gpr_tls_get(&g_cached_event);
+ int ret = 0;
+ if (storage != nullptr &&
+ (grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == cq) {
+ *tag = storage->tag;
+ grpc_core::ExecCtx exec_ctx;
+ *ok = (storage->next & static_cast<uintptr_t>(1)) == 1;
+ 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) {
- GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
- gpr_mu_lock(cq->mu);
- cq_finish_shutdown_next(cq);
- gpr_mu_unlock(cq->mu);
- GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
- }
- }
- gpr_tls_set(&g_cached_event, (intptr_t)0);
- gpr_tls_set(&g_cached_cq, (intptr_t)0);
-
- return ret;
-}
-
+ GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
+ gpr_mu_lock(cq->mu);
+ cq_finish_shutdown_next(cq);
+ gpr_mu_unlock(cq->mu);
+ GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
+ }
+ }
+ gpr_tls_set(&g_cached_event, (intptr_t)0);
+ gpr_tls_set(&g_cached_cq, (intptr_t)0);
+
+ 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;
-}
-
+}
+
grpc_cq_completion* CqEventQueue::Pop() {
- grpc_cq_completion* c = nullptr;
-
+ grpc_cq_completion* c = nullptr;
+
if (gpr_spinlock_trylock(&queue_lock_)) {
- GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_SUCCESSES();
-
- bool is_empty = false;
+ 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_);
-
- if (c == nullptr && !is_empty) {
- GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES();
- }
- } else {
- GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_FAILURES();
- }
-
- if (c) {
+
+ if (c == nullptr && !is_empty) {
+ GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES();
+ }
+ } else {
+ GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_FAILURES();
+ }
+
+ if (c) {
num_queue_items_.FetchSub(1, grpc_core::MemoryOrder::RELAXED);
- }
-
- return c;
-}
-
-grpc_completion_queue* grpc_completion_queue_create_internal(
+ }
+
+ return c;
+}
+
+grpc_completion_queue* grpc_completion_queue_create_internal(
grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type,
grpc_experimental_completion_queue_functor* shutdown_callback) {
- GPR_TIMER_SCOPE("grpc_completion_queue_create_internal", 0);
-
- grpc_completion_queue* cq;
-
- GRPC_API_TRACE(
- "grpc_completion_queue_create_internal(completion_type=%d, "
- "polling_type=%d)",
- 2, (completion_type, polling_type));
-
- const cq_vtable* vtable = &g_cq_vtable[completion_type];
- const cq_poller_vtable* poller_vtable =
- &g_poller_vtable_by_poller_type[polling_type];
-
- grpc_core::ExecCtx exec_ctx;
- GRPC_STATS_INC_CQS_CREATED();
-
- cq = static_cast<grpc_completion_queue*>(
- gpr_zalloc(sizeof(grpc_completion_queue) + vtable->data_size +
- poller_vtable->size()));
-
- cq->vtable = vtable;
- cq->poller_vtable = poller_vtable;
-
- /* One for destroy(), one for pollset_shutdown */
+ GPR_TIMER_SCOPE("grpc_completion_queue_create_internal", 0);
+
+ grpc_completion_queue* cq;
+
+ GRPC_API_TRACE(
+ "grpc_completion_queue_create_internal(completion_type=%d, "
+ "polling_type=%d)",
+ 2, (completion_type, polling_type));
+
+ const cq_vtable* vtable = &g_cq_vtable[completion_type];
+ const cq_poller_vtable* poller_vtable =
+ &g_poller_vtable_by_poller_type[polling_type];
+
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_STATS_INC_CQS_CREATED();
+
+ cq = static_cast<grpc_completion_queue*>(
+ gpr_zalloc(sizeof(grpc_completion_queue) + vtable->data_size +
+ poller_vtable->size()));
+
+ cq->vtable = vtable;
+ cq->poller_vtable = poller_vtable;
+
+ /* One for destroy(), one for pollset_shutdown */
new (&cq->owning_refs) grpc_core::RefCount(2);
-
- poller_vtable->init(POLLSET_FROM_CQ(cq), &cq->mu);
+
+ poller_vtable->init(POLLSET_FROM_CQ(cq), &cq->mu);
vtable->init(DATA_FROM_CQ(cq), shutdown_callback);
-
- GRPC_CLOSURE_INIT(&cq->pollset_shutdown_done, on_pollset_shutdown_done, cq,
- grpc_schedule_on_exec_ctx);
- return cq;
-}
-
+
+ GRPC_CLOSURE_INIT(&cq->pollset_shutdown_done, on_pollset_shutdown_done, cq,
+ grpc_schedule_on_exec_ctx);
+ return cq;
+}
+
static void cq_init_next(
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();
-}
-
+}
+
static void cq_init_pluck(
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();
-}
-
+}
+
static void cq_init_callback(
void* data, grpc_experimental_completion_queue_functor* shutdown_callback) {
new (data) cq_callback_data(shutdown_callback);
@@ -578,260 +578,260 @@ static void cq_destroy_callback(void* data) {
cqd->~cq_callback_data();
}
-grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cq) {
- return cq->vtable->cq_completion_type;
-}
-
-int grpc_get_cq_poll_num(grpc_completion_queue* cq) {
- int cur_num_polls;
- gpr_mu_lock(cq->mu);
- cur_num_polls = cq->num_polls;
- gpr_mu_unlock(cq->mu);
- return cur_num_polls;
-}
-
-#ifndef NDEBUG
-void grpc_cq_internal_ref(grpc_completion_queue* cq, const char* reason,
- const char* file, int line) {
+grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cq) {
+ return cq->vtable->cq_completion_type;
+}
+
+int grpc_get_cq_poll_num(grpc_completion_queue* cq) {
+ int cur_num_polls;
+ gpr_mu_lock(cq->mu);
+ cur_num_polls = cq->num_polls;
+ gpr_mu_unlock(cq->mu);
+ return cur_num_polls;
+}
+
+#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);
-#else
-void grpc_cq_internal_ref(grpc_completion_queue* cq) {
+#else
+void grpc_cq_internal_ref(grpc_completion_queue* cq) {
grpc_core::DebugLocation debug_location;
const char* reason = nullptr;
-#endif
+#endif
cq->owning_refs.Ref(debug_location, reason);
-}
-
+}
+
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");
-}
-
-#ifndef NDEBUG
-void grpc_cq_internal_unref(grpc_completion_queue* cq, const char* reason,
- const char* file, int line) {
+ grpc_completion_queue* cq = static_cast<grpc_completion_queue*>(arg);
+ GRPC_CQ_INTERNAL_UNREF(cq, "pollset_destroy");
+}
+
+#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);
-#else
-void grpc_cq_internal_unref(grpc_completion_queue* cq) {
+#else
+void grpc_cq_internal_unref(grpc_completion_queue* cq) {
grpc_core::DebugLocation debug_location;
const char* reason = nullptr;
-#endif
+#endif
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
- gpr_free(cq->outstanding_tags);
-#endif
- gpr_free(cq);
- }
-}
-
-#ifndef NDEBUG
-static void cq_check_tag(grpc_completion_queue* cq, void* tag, bool lock_cq) {
- int found = 0;
- if (lock_cq) {
- gpr_mu_lock(cq->mu);
- }
-
- for (int i = 0; i < static_cast<int>(cq->outstanding_tag_count); i++) {
- if (cq->outstanding_tags[i] == tag) {
- cq->outstanding_tag_count--;
- GPR_SWAP(void*, cq->outstanding_tags[i],
- cq->outstanding_tags[cq->outstanding_tag_count]);
- found = 1;
- break;
- }
- }
-
- if (lock_cq) {
- gpr_mu_unlock(cq->mu);
- }
-
- GPR_ASSERT(found);
-}
-#else
+ cq->vtable->destroy(DATA_FROM_CQ(cq));
+ cq->poller_vtable->destroy(POLLSET_FROM_CQ(cq));
+#ifndef NDEBUG
+ gpr_free(cq->outstanding_tags);
+#endif
+ gpr_free(cq);
+ }
+}
+
+#ifndef NDEBUG
+static void cq_check_tag(grpc_completion_queue* cq, void* tag, bool lock_cq) {
+ int found = 0;
+ if (lock_cq) {
+ gpr_mu_lock(cq->mu);
+ }
+
+ for (int i = 0; i < static_cast<int>(cq->outstanding_tag_count); i++) {
+ if (cq->outstanding_tags[i] == tag) {
+ cq->outstanding_tag_count--;
+ GPR_SWAP(void*, cq->outstanding_tags[i],
+ cq->outstanding_tags[cq->outstanding_tag_count]);
+ found = 1;
+ break;
+ }
+ }
+
+ if (lock_cq) {
+ gpr_mu_unlock(cq->mu);
+ }
+
+ GPR_ASSERT(found);
+}
+#else
static void cq_check_tag(grpc_completion_queue* /*cq*/, void* /*tag*/,
bool /*lock_cq*/) {}
-#endif
-
+#endif
+
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);
+ cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
return cqd->pending_events.IncrementIfNonzero();
-}
-
+}
+
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);
+ cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
return cqd->pending_events.IncrementIfNonzero();
-}
-
+}
+
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();
}
-bool grpc_cq_begin_op(grpc_completion_queue* cq, void* tag) {
-#ifndef NDEBUG
- gpr_mu_lock(cq->mu);
- if (cq->outstanding_tag_count == cq->outstanding_tag_capacity) {
- cq->outstanding_tag_capacity = GPR_MAX(4, 2 * cq->outstanding_tag_capacity);
- cq->outstanding_tags = static_cast<void**>(gpr_realloc(
- cq->outstanding_tags,
- sizeof(*cq->outstanding_tags) * cq->outstanding_tag_capacity));
- }
- cq->outstanding_tags[cq->outstanding_tag_count++] = tag;
- gpr_mu_unlock(cq->mu);
-#endif
- return cq->vtable->begin_op(cq, tag);
-}
-
-/* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a
- * completion
- * type of GRPC_CQ_NEXT) */
+bool grpc_cq_begin_op(grpc_completion_queue* cq, void* tag) {
+#ifndef NDEBUG
+ gpr_mu_lock(cq->mu);
+ if (cq->outstanding_tag_count == cq->outstanding_tag_capacity) {
+ cq->outstanding_tag_capacity = GPR_MAX(4, 2 * cq->outstanding_tag_capacity);
+ cq->outstanding_tags = static_cast<void**>(gpr_realloc(
+ cq->outstanding_tags,
+ sizeof(*cq->outstanding_tags) * cq->outstanding_tag_capacity));
+ }
+ cq->outstanding_tags[cq->outstanding_tag_count++] = tag;
+ gpr_mu_unlock(cq->mu);
+#endif
+ return cq->vtable->begin_op(cq, 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*/) {
- GPR_TIMER_SCOPE("cq_end_op_for_next", 0);
-
+ 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)) {
- 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));
+ 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) {
- gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg);
- }
- }
- cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
- int is_success = (error == GRPC_ERROR_NONE);
-
- storage->tag = tag;
- storage->done = done;
- storage->done_arg = done_arg;
- storage->next = static_cast<uintptr_t>(is_success);
-
- cq_check_tag(cq, tag, true); /* Used in debug builds only */
-
- if ((grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == cq &&
- (grpc_cq_completion*)gpr_tls_get(&g_cached_event) == nullptr) {
- gpr_tls_set(&g_cached_event, (intptr_t)storage);
- } else {
- /* Add the completion to the queue */
+ gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg);
+ }
+ }
+ cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
+ int is_success = (error == GRPC_ERROR_NONE);
+
+ storage->tag = tag;
+ storage->done = done;
+ storage->done_arg = done_arg;
+ storage->next = static_cast<uintptr_t>(is_success);
+
+ cq_check_tag(cq, tag, true); /* Used in debug builds only */
+
+ if ((grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == cq &&
+ (grpc_cq_completion*)gpr_tls_get(&g_cached_event) == nullptr) {
+ 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);
- /* 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
+ /* 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
- */
+ */
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);
- grpc_error* kick_error =
- cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), nullptr);
- gpr_mu_unlock(cq->mu);
-
- if (kick_error != GRPC_ERROR_NONE) {
- const char* msg = grpc_error_string(kick_error);
- gpr_log(GPR_ERROR, "Kick failed: %s", msg);
- GRPC_ERROR_UNREF(kick_error);
- }
- }
+ /* Only kick if this is the first item queued */
+ if (is_first) {
+ gpr_mu_lock(cq->mu);
+ grpc_error* kick_error =
+ cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), nullptr);
+ gpr_mu_unlock(cq->mu);
+
+ if (kick_error != GRPC_ERROR_NONE) {
+ const char* msg = grpc_error_string(kick_error);
+ gpr_log(GPR_ERROR, "Kick failed: %s", msg);
+ GRPC_ERROR_UNREF(kick_error);
+ }
+ }
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);
- gpr_mu_unlock(cq->mu);
- GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
- }
- } else {
- GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
+ GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
+ gpr_mu_lock(cq->mu);
+ cq_finish_shutdown_next(cq);
+ gpr_mu_unlock(cq->mu);
+ GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
+ }
+ } else {
+ GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
cqd->pending_events.Store(0, grpc_core::MemoryOrder::RELEASE);
- gpr_mu_lock(cq->mu);
- cq_finish_shutdown_next(cq);
- gpr_mu_unlock(cq->mu);
- GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
- }
- }
-
- GRPC_ERROR_UNREF(error);
-}
-
-/* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a
- * completion
- * type of GRPC_CQ_PLUCK) */
+ gpr_mu_lock(cq->mu);
+ cq_finish_shutdown_next(cq);
+ gpr_mu_unlock(cq->mu);
+ GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
+ }
+ }
+
+ GRPC_ERROR_UNREF(error);
+}
+
+/* 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*/) {
- 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);
-
+ 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)) {
- 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));
+ 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) {
- gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg);
- }
- }
-
- storage->tag = tag;
- storage->done = done;
- storage->done_arg = done_arg;
- storage->next =
- ((uintptr_t)&cqd->completed_head) | (static_cast<uintptr_t>(is_success));
-
- gpr_mu_lock(cq->mu);
- cq_check_tag(cq, tag, false); /* Used in debug builds only */
-
- /* Add to the list of completions */
+ gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg);
+ }
+ }
+
+ storage->tag = tag;
+ storage->done = done;
+ storage->done_arg = done_arg;
+ storage->next =
+ ((uintptr_t)&cqd->completed_head) | (static_cast<uintptr_t>(is_success));
+
+ gpr_mu_lock(cq->mu);
+ 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->completed_tail->next =
- ((uintptr_t)storage) | (1u & cqd->completed_tail->next);
- cqd->completed_tail = storage;
-
+ 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) {
- cq_finish_shutdown_pluck(cq);
- gpr_mu_unlock(cq->mu);
- } else {
- grpc_pollset_worker* pluck_worker = nullptr;
- for (int i = 0; i < cqd->num_pluckers; i++) {
- if (cqd->pluckers[i].tag == tag) {
- pluck_worker = *cqd->pluckers[i].worker;
- break;
- }
- }
-
- grpc_error* kick_error =
- cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), pluck_worker);
-
- gpr_mu_unlock(cq->mu);
-
- if (kick_error != GRPC_ERROR_NONE) {
- const char* msg = grpc_error_string(kick_error);
- gpr_log(GPR_ERROR, "Kick failed: %s", msg);
-
- GRPC_ERROR_UNREF(kick_error);
- }
- }
-
- GRPC_ERROR_UNREF(error);
-}
-
+ cq_finish_shutdown_pluck(cq);
+ gpr_mu_unlock(cq->mu);
+ } else {
+ grpc_pollset_worker* pluck_worker = nullptr;
+ for (int i = 0; i < cqd->num_pluckers; i++) {
+ if (cqd->pluckers[i].tag == tag) {
+ pluck_worker = *cqd->pluckers[i].worker;
+ break;
+ }
+ }
+
+ grpc_error* kick_error =
+ cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), pluck_worker);
+
+ gpr_mu_unlock(cq->mu);
+
+ if (kick_error != GRPC_ERROR_NONE) {
+ const char* msg = grpc_error_string(kick_error);
+ gpr_log(GPR_ERROR, "Kick failed: %s", msg);
+
+ GRPC_ERROR_UNREF(kick_error);
+ }
+ }
+
+ 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);
@@ -892,474 +892,474 @@ static void cq_end_op_for_callback(
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 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);
-}
-
+}
+
struct cq_is_finished_arg {
- gpr_atm last_seen_things_queued_ever;
- grpc_completion_queue* cq;
- grpc_millis deadline;
- grpc_cq_completion* stolen_completion;
- void* tag; /* for pluck */
- bool first_loop;
+ gpr_atm last_seen_things_queued_ever;
+ grpc_completion_queue* cq;
+ grpc_millis deadline;
+ grpc_cq_completion* stolen_completion;
+ void* tag; /* for pluck */
+ bool first_loop;
};
-class ExecCtxNext : public grpc_core::ExecCtx {
- public:
- ExecCtxNext(void* arg) : ExecCtx(0), check_ready_to_finish_arg_(arg) {}
-
- bool CheckReadyToFinish() override {
- cq_is_finished_arg* a =
- static_cast<cq_is_finished_arg*>(check_ready_to_finish_arg_);
- grpc_completion_queue* cq = a->cq;
- cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
- GPR_ASSERT(a->stolen_completion == nullptr);
-
+class ExecCtxNext : public grpc_core::ExecCtx {
+ public:
+ ExecCtxNext(void* arg) : ExecCtx(0), check_ready_to_finish_arg_(arg) {}
+
+ bool CheckReadyToFinish() override {
+ cq_is_finished_arg* a =
+ static_cast<cq_is_finished_arg*>(check_ready_to_finish_arg_);
+ grpc_completion_queue* cq = a->cq;
+ 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);
-
- if (current_last_seen_things_queued_ever !=
- a->last_seen_things_queued_ever) {
- a->last_seen_things_queued_ever =
+
+ 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);
-
- /* 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) */
+
+ /* 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();
- if (a->stolen_completion != nullptr) {
- return true;
- }
- }
- return !a->first_loop && a->deadline < grpc_core::ExecCtx::Get()->Now();
- }
-
- private:
- void* check_ready_to_finish_arg_;
-};
-
-#ifndef NDEBUG
-static void dump_pending_tags(grpc_completion_queue* cq) {
+ if (a->stolen_completion != nullptr) {
+ return true;
+ }
+ }
+ return !a->first_loop && a->deadline < grpc_core::ExecCtx::Get()->Now();
+ }
+
+ private:
+ void* check_ready_to_finish_arg_;
+};
+
+#ifndef NDEBUG
+static void dump_pending_tags(grpc_completion_queue* cq) {
if (!GRPC_TRACE_FLAG_ENABLED(grpc_trace_pending_tags)) return;
std::vector<TString> parts;
parts.push_back("PENDING TAGS:");
- gpr_mu_lock(cq->mu);
- for (size_t i = 0; i < cq->outstanding_tag_count; i++) {
+ gpr_mu_lock(cq->mu);
+ for (size_t i = 0; i < cq->outstanding_tag_count; i++) {
parts.push_back(y_absl::StrFormat(" %p", cq->outstanding_tags[i]));
- }
- gpr_mu_unlock(cq->mu);
+ }
+ gpr_mu_unlock(cq->mu);
gpr_log(GPR_DEBUG, "%s", y_absl::StrJoin(parts, "").c_str());
-}
-#else
+}
+#else
static void dump_pending_tags(grpc_completion_queue* /*cq*/) {}
-#endif
-
-static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
- void* reserved) {
- GPR_TIMER_SCOPE("grpc_completion_queue_next", 0);
-
- grpc_event ret;
- cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
-
- GRPC_API_TRACE(
- "grpc_completion_queue_next("
- "cq=%p, "
- "deadline=gpr_timespec { tv_sec: %" PRId64
- ", tv_nsec: %d, clock_type: %d }, "
- "reserved=%p)",
- 5,
- (cq, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
- reserved));
- GPR_ASSERT(!reserved);
-
- dump_pending_tags(cq);
-
- GRPC_CQ_INTERNAL_REF(cq, "next");
-
- grpc_millis deadline_millis = grpc_timespec_to_millis_round_up(deadline);
- cq_is_finished_arg is_finished_arg = {
+#endif
+
+static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
+ void* reserved) {
+ GPR_TIMER_SCOPE("grpc_completion_queue_next", 0);
+
+ grpc_event ret;
+ cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
+
+ GRPC_API_TRACE(
+ "grpc_completion_queue_next("
+ "cq=%p, "
+ "deadline=gpr_timespec { tv_sec: %" PRId64
+ ", tv_nsec: %d, clock_type: %d }, "
+ "reserved=%p)",
+ 5,
+ (cq, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
+ reserved));
+ GPR_ASSERT(!reserved);
+
+ dump_pending_tags(cq);
+
+ GRPC_CQ_INTERNAL_REF(cq, "next");
+
+ 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),
- cq,
- deadline_millis,
- nullptr,
- nullptr,
- true};
- ExecCtxNext exec_ctx(&is_finished_arg);
- for (;;) {
- grpc_millis iteration_deadline = deadline_millis;
-
- if (is_finished_arg.stolen_completion != nullptr) {
- grpc_cq_completion* c = is_finished_arg.stolen_completion;
- is_finished_arg.stolen_completion = nullptr;
- ret.type = GRPC_OP_COMPLETE;
- ret.success = c->next & 1u;
- ret.tag = c->tag;
- c->done(c->done_arg, c);
- break;
- }
-
+ cq,
+ deadline_millis,
+ nullptr,
+ nullptr,
+ true};
+ ExecCtxNext exec_ctx(&is_finished_arg);
+ for (;;) {
+ grpc_millis iteration_deadline = deadline_millis;
+
+ if (is_finished_arg.stolen_completion != nullptr) {
+ grpc_cq_completion* c = is_finished_arg.stolen_completion;
+ is_finished_arg.stolen_completion = nullptr;
+ ret.type = GRPC_OP_COMPLETE;
+ ret.success = c->next & 1u;
+ ret.tag = c->tag;
+ c->done(c->done_arg, c);
+ break;
+ }
+
grpc_cq_completion* c = cqd->queue.Pop();
-
- if (c != nullptr) {
- ret.type = GRPC_OP_COMPLETE;
- ret.success = c->next & 1u;
- ret.tag = c->tag;
- c->done(c->done_arg, c);
- break;
- } else {
- /* If c == NULL it means either the queue is empty OR in an transient
- inconsistent state. If it is the latter, we shold do a 0-timeout poll
- 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 (c != nullptr) {
+ ret.type = GRPC_OP_COMPLETE;
+ ret.success = c->next & 1u;
+ ret.tag = c->tag;
+ c->done(c->done_arg, c);
+ break;
+ } else {
+ /* If c == NULL it means either the queue is empty OR in an transient
+ inconsistent state. If it is the latter, we shold do a 0-timeout poll
+ 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) {
- iteration_deadline = 0;
- }
- }
-
+ iteration_deadline = 0;
+ }
+ }
+
if (cqd->pending_events.Load(grpc_core::MemoryOrder::ACQUIRE) == 0) {
- /* Before returning, check if the queue has any items left over (since
+ /* 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) {
- /* 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
- events should have already been queued on this cq */
- continue;
- }
-
- ret.type = GRPC_QUEUE_SHUTDOWN;
+ /* 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
+ events should have already been queued on this cq */
+ continue;
+ }
+
+ ret.type = GRPC_QUEUE_SHUTDOWN;
ret.success = 0;
- break;
- }
-
- if (!is_finished_arg.first_loop &&
- grpc_core::ExecCtx::Get()->Now() >= deadline_millis) {
- ret.type = GRPC_QUEUE_TIMEOUT;
+ break;
+ }
+
+ if (!is_finished_arg.first_loop &&
+ grpc_core::ExecCtx::Get()->Now() >= deadline_millis) {
+ ret.type = GRPC_QUEUE_TIMEOUT;
ret.success = 0;
- dump_pending_tags(cq);
- break;
- }
-
- /* The main polling work happens in grpc_pollset_work */
- gpr_mu_lock(cq->mu);
- cq->num_polls++;
- grpc_error* err = cq->poller_vtable->work(POLLSET_FROM_CQ(cq), nullptr,
- iteration_deadline);
- gpr_mu_unlock(cq->mu);
-
- if (err != GRPC_ERROR_NONE) {
- const char* msg = grpc_error_string(err);
- gpr_log(GPR_ERROR, "Completion queue next failed: %s", msg);
-
- GRPC_ERROR_UNREF(err);
- ret.type = GRPC_QUEUE_TIMEOUT;
+ dump_pending_tags(cq);
+ break;
+ }
+
+ /* The main polling work happens in grpc_pollset_work */
+ gpr_mu_lock(cq->mu);
+ cq->num_polls++;
+ grpc_error* err = cq->poller_vtable->work(POLLSET_FROM_CQ(cq), nullptr,
+ iteration_deadline);
+ gpr_mu_unlock(cq->mu);
+
+ if (err != GRPC_ERROR_NONE) {
+ const char* msg = grpc_error_string(err);
+ gpr_log(GPR_ERROR, "Completion queue next failed: %s", msg);
+
+ GRPC_ERROR_UNREF(err);
+ ret.type = GRPC_QUEUE_TIMEOUT;
ret.success = 0;
- dump_pending_tags(cq);
- break;
- }
- is_finished_arg.first_loop = false;
- }
-
+ 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) {
- gpr_mu_lock(cq->mu);
- cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), nullptr);
- gpr_mu_unlock(cq->mu);
- }
-
- GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret);
- GRPC_CQ_INTERNAL_UNREF(cq, "next");
-
- GPR_ASSERT(is_finished_arg.stolen_completion == nullptr);
-
- return ret;
-}
-
-/* Finishes the completion queue shutdown. This means that there are no more
- completion events / tags expected from the completion queue
- - Must be called under completion queue lock
- - Must be called only once in completion queue's lifetime
- - grpc_completion_queue_shutdown() MUST have been called before calling
- this function */
-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_mu_lock(cq->mu);
+ cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), nullptr);
+ gpr_mu_unlock(cq->mu);
+ }
+
+ GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret);
+ GRPC_CQ_INTERNAL_UNREF(cq, "next");
+
+ GPR_ASSERT(is_finished_arg.stolen_completion == nullptr);
+
+ return ret;
+}
+
+/* Finishes the completion queue shutdown. This means that there are no more
+ completion events / tags expected from the completion queue
+ - Must be called under completion queue lock
+ - Must be called only once in completion queue's lifetime
+ - grpc_completion_queue_shutdown() MUST have been called before calling
+ this function */
+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);
-
- cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
-}
-
-static void cq_shutdown_next(grpc_completion_queue* cq) {
- cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
-
- /* Need an extra ref for cq here because:
- * We call cq_finish_shutdown_next() below, that would call pollset shutdown.
- * Pollset shutdown decrements the cq ref count which can potentially destroy
- * the cq (if that happens to be the last ref).
- * Creating an extra ref here prevents the cq from getting destroyed while
- * this function is still active */
- GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
- gpr_mu_lock(cq->mu);
- if (cqd->shutdown_called) {
- gpr_mu_unlock(cq->mu);
- GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
- return;
- }
- cqd->shutdown_called = true;
+
+ cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
+}
+
+static void cq_shutdown_next(grpc_completion_queue* cq) {
+ cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
+
+ /* Need an extra ref for cq here because:
+ * We call cq_finish_shutdown_next() below, that would call pollset shutdown.
+ * Pollset shutdown decrements the cq ref count which can potentially destroy
+ * the cq (if that happens to be the last ref).
+ * Creating an extra ref here prevents the cq from getting destroyed while
+ * this function is still active */
+ GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
+ gpr_mu_lock(cq->mu);
+ if (cqd->shutdown_called) {
+ gpr_mu_unlock(cq->mu);
+ GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
+ 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
- * on this counter without necessarily holding a lock on cq */
+ * on this counter without necessarily holding a lock on cq */
if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
- cq_finish_shutdown_next(cq);
- }
- gpr_mu_unlock(cq->mu);
- GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
-}
-
-grpc_event grpc_completion_queue_next(grpc_completion_queue* cq,
- gpr_timespec deadline, void* reserved) {
- return cq->vtable->next(cq, deadline, reserved);
-}
-
-static int add_plucker(grpc_completion_queue* cq, void* tag,
- grpc_pollset_worker** worker) {
- cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
- if (cqd->num_pluckers == GRPC_MAX_COMPLETION_QUEUE_PLUCKERS) {
- return 0;
- }
- cqd->pluckers[cqd->num_pluckers].tag = tag;
- cqd->pluckers[cqd->num_pluckers].worker = worker;
- cqd->num_pluckers++;
- return 1;
-}
-
-static void del_plucker(grpc_completion_queue* cq, void* tag,
- grpc_pollset_worker** worker) {
- cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
- for (int i = 0; i < cqd->num_pluckers; i++) {
- if (cqd->pluckers[i].tag == tag && cqd->pluckers[i].worker == worker) {
- cqd->num_pluckers--;
- GPR_SWAP(plucker, cqd->pluckers[i], cqd->pluckers[cqd->num_pluckers]);
- return;
- }
- }
- GPR_UNREACHABLE_CODE(return );
-}
-
-class ExecCtxPluck : public grpc_core::ExecCtx {
- public:
- ExecCtxPluck(void* arg) : ExecCtx(0), check_ready_to_finish_arg_(arg) {}
-
- bool CheckReadyToFinish() override {
- cq_is_finished_arg* a =
- static_cast<cq_is_finished_arg*>(check_ready_to_finish_arg_);
- grpc_completion_queue* cq = a->cq;
- cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
-
- GPR_ASSERT(a->stolen_completion == nullptr);
- gpr_atm current_last_seen_things_queued_ever =
+ cq_finish_shutdown_next(cq);
+ }
+ gpr_mu_unlock(cq->mu);
+ GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
+}
+
+grpc_event grpc_completion_queue_next(grpc_completion_queue* cq,
+ gpr_timespec deadline, void* reserved) {
+ return cq->vtable->next(cq, deadline, reserved);
+}
+
+static int add_plucker(grpc_completion_queue* cq, void* tag,
+ grpc_pollset_worker** worker) {
+ cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
+ if (cqd->num_pluckers == GRPC_MAX_COMPLETION_QUEUE_PLUCKERS) {
+ return 0;
+ }
+ cqd->pluckers[cqd->num_pluckers].tag = tag;
+ cqd->pluckers[cqd->num_pluckers].worker = worker;
+ cqd->num_pluckers++;
+ return 1;
+}
+
+static void del_plucker(grpc_completion_queue* cq, void* tag,
+ grpc_pollset_worker** worker) {
+ cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
+ for (int i = 0; i < cqd->num_pluckers; i++) {
+ if (cqd->pluckers[i].tag == tag && cqd->pluckers[i].worker == worker) {
+ cqd->num_pluckers--;
+ GPR_SWAP(plucker, cqd->pluckers[i], cqd->pluckers[cqd->num_pluckers]);
+ return;
+ }
+ }
+ GPR_UNREACHABLE_CODE(return );
+}
+
+class ExecCtxPluck : public grpc_core::ExecCtx {
+ public:
+ ExecCtxPluck(void* arg) : ExecCtx(0), check_ready_to_finish_arg_(arg) {}
+
+ bool CheckReadyToFinish() override {
+ cq_is_finished_arg* a =
+ static_cast<cq_is_finished_arg*>(check_ready_to_finish_arg_);
+ grpc_completion_queue* cq = a->cq;
+ cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
+
+ GPR_ASSERT(a->stolen_completion == nullptr);
+ gpr_atm 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) {
- gpr_mu_lock(cq->mu);
- a->last_seen_things_queued_ever =
+ 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);
- grpc_cq_completion* c;
- grpc_cq_completion* prev = &cqd->completed_head;
- while ((c = (grpc_cq_completion*)(prev->next &
- ~static_cast<uintptr_t>(1))) !=
- &cqd->completed_head) {
- if (c->tag == a->tag) {
- prev->next = (prev->next & static_cast<uintptr_t>(1)) |
- (c->next & ~static_cast<uintptr_t>(1));
- if (c == cqd->completed_tail) {
- cqd->completed_tail = prev;
- }
- gpr_mu_unlock(cq->mu);
- a->stolen_completion = c;
- return true;
- }
- prev = c;
- }
- gpr_mu_unlock(cq->mu);
- }
- return !a->first_loop && a->deadline < grpc_core::ExecCtx::Get()->Now();
- }
-
- private:
- void* check_ready_to_finish_arg_;
-};
-
-static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
- gpr_timespec deadline, void* reserved) {
- GPR_TIMER_SCOPE("grpc_completion_queue_pluck", 0);
-
- grpc_event ret;
- grpc_cq_completion* c;
- grpc_cq_completion* prev;
- grpc_pollset_worker* worker = nullptr;
- cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
-
+ grpc_cq_completion* c;
+ grpc_cq_completion* prev = &cqd->completed_head;
+ while ((c = (grpc_cq_completion*)(prev->next &
+ ~static_cast<uintptr_t>(1))) !=
+ &cqd->completed_head) {
+ if (c->tag == a->tag) {
+ prev->next = (prev->next & static_cast<uintptr_t>(1)) |
+ (c->next & ~static_cast<uintptr_t>(1));
+ if (c == cqd->completed_tail) {
+ cqd->completed_tail = prev;
+ }
+ gpr_mu_unlock(cq->mu);
+ a->stolen_completion = c;
+ return true;
+ }
+ prev = c;
+ }
+ gpr_mu_unlock(cq->mu);
+ }
+ return !a->first_loop && a->deadline < grpc_core::ExecCtx::Get()->Now();
+ }
+
+ private:
+ void* check_ready_to_finish_arg_;
+};
+
+static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
+ gpr_timespec deadline, void* reserved) {
+ GPR_TIMER_SCOPE("grpc_completion_queue_pluck", 0);
+
+ grpc_event ret;
+ grpc_cq_completion* c;
+ grpc_cq_completion* prev;
+ 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)) {
- GRPC_API_TRACE(
- "grpc_completion_queue_pluck("
- "cq=%p, tag=%p, "
- "deadline=gpr_timespec { tv_sec: %" PRId64
- ", tv_nsec: %d, clock_type: %d }, "
- "reserved=%p)",
- 6,
- (cq, tag, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
- reserved));
- }
- GPR_ASSERT(!reserved);
-
- dump_pending_tags(cq);
-
- GRPC_CQ_INTERNAL_REF(cq, "pluck");
- gpr_mu_lock(cq->mu);
- grpc_millis deadline_millis = grpc_timespec_to_millis_round_up(deadline);
- cq_is_finished_arg is_finished_arg = {
+ GRPC_API_TRACE(
+ "grpc_completion_queue_pluck("
+ "cq=%p, tag=%p, "
+ "deadline=gpr_timespec { tv_sec: %" PRId64
+ ", tv_nsec: %d, clock_type: %d }, "
+ "reserved=%p)",
+ 6,
+ (cq, tag, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
+ reserved));
+ }
+ GPR_ASSERT(!reserved);
+
+ dump_pending_tags(cq);
+
+ GRPC_CQ_INTERNAL_REF(cq, "pluck");
+ 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),
- cq,
- deadline_millis,
- nullptr,
- tag,
- true};
- ExecCtxPluck exec_ctx(&is_finished_arg);
- for (;;) {
- if (is_finished_arg.stolen_completion != nullptr) {
- gpr_mu_unlock(cq->mu);
- c = is_finished_arg.stolen_completion;
- is_finished_arg.stolen_completion = nullptr;
- ret.type = GRPC_OP_COMPLETE;
- ret.success = c->next & 1u;
- ret.tag = c->tag;
- c->done(c->done_arg, c);
- break;
- }
- prev = &cqd->completed_head;
- while (
- (c = (grpc_cq_completion*)(prev->next & ~static_cast<uintptr_t>(1))) !=
- &cqd->completed_head) {
- if (c->tag == tag) {
- prev->next = (prev->next & static_cast<uintptr_t>(1)) |
- (c->next & ~static_cast<uintptr_t>(1));
- if (c == cqd->completed_tail) {
- cqd->completed_tail = prev;
- }
- gpr_mu_unlock(cq->mu);
- ret.type = GRPC_OP_COMPLETE;
- ret.success = c->next & 1u;
- ret.tag = c->tag;
- c->done(c->done_arg, c);
- goto done;
- }
- prev = c;
- }
+ cq,
+ deadline_millis,
+ nullptr,
+ tag,
+ true};
+ ExecCtxPluck exec_ctx(&is_finished_arg);
+ for (;;) {
+ if (is_finished_arg.stolen_completion != nullptr) {
+ gpr_mu_unlock(cq->mu);
+ c = is_finished_arg.stolen_completion;
+ is_finished_arg.stolen_completion = nullptr;
+ ret.type = GRPC_OP_COMPLETE;
+ ret.success = c->next & 1u;
+ ret.tag = c->tag;
+ c->done(c->done_arg, c);
+ break;
+ }
+ prev = &cqd->completed_head;
+ while (
+ (c = (grpc_cq_completion*)(prev->next & ~static_cast<uintptr_t>(1))) !=
+ &cqd->completed_head) {
+ if (c->tag == tag) {
+ prev->next = (prev->next & static_cast<uintptr_t>(1)) |
+ (c->next & ~static_cast<uintptr_t>(1));
+ if (c == cqd->completed_tail) {
+ cqd->completed_tail = prev;
+ }
+ gpr_mu_unlock(cq->mu);
+ ret.type = GRPC_OP_COMPLETE;
+ ret.success = c->next & 1u;
+ ret.tag = c->tag;
+ c->done(c->done_arg, c);
+ goto done;
+ }
+ prev = c;
+ }
if (cqd->shutdown.Load(grpc_core::MemoryOrder::RELAXED)) {
- gpr_mu_unlock(cq->mu);
- ret.type = GRPC_QUEUE_SHUTDOWN;
+ gpr_mu_unlock(cq->mu);
+ ret.type = GRPC_QUEUE_SHUTDOWN;
ret.success = 0;
- break;
- }
- if (!add_plucker(cq, tag, &worker)) {
- gpr_log(GPR_DEBUG,
- "Too many outstanding grpc_completion_queue_pluck calls: maximum "
- "is %d",
- GRPC_MAX_COMPLETION_QUEUE_PLUCKERS);
- gpr_mu_unlock(cq->mu);
- /* TODO(ctiller): should we use a different result here */
- ret.type = GRPC_QUEUE_TIMEOUT;
+ break;
+ }
+ if (!add_plucker(cq, tag, &worker)) {
+ gpr_log(GPR_DEBUG,
+ "Too many outstanding grpc_completion_queue_pluck calls: maximum "
+ "is %d",
+ GRPC_MAX_COMPLETION_QUEUE_PLUCKERS);
+ gpr_mu_unlock(cq->mu);
+ /* TODO(ctiller): should we use a different result here */
+ ret.type = GRPC_QUEUE_TIMEOUT;
ret.success = 0;
- dump_pending_tags(cq);
- break;
- }
- if (!is_finished_arg.first_loop &&
- grpc_core::ExecCtx::Get()->Now() >= deadline_millis) {
- del_plucker(cq, tag, &worker);
- gpr_mu_unlock(cq->mu);
- ret.type = GRPC_QUEUE_TIMEOUT;
+ dump_pending_tags(cq);
+ break;
+ }
+ if (!is_finished_arg.first_loop &&
+ grpc_core::ExecCtx::Get()->Now() >= deadline_millis) {
+ del_plucker(cq, tag, &worker);
+ gpr_mu_unlock(cq->mu);
+ ret.type = GRPC_QUEUE_TIMEOUT;
ret.success = 0;
- dump_pending_tags(cq);
- break;
- }
- cq->num_polls++;
- grpc_error* err =
- cq->poller_vtable->work(POLLSET_FROM_CQ(cq), &worker, deadline_millis);
- if (err != GRPC_ERROR_NONE) {
- del_plucker(cq, tag, &worker);
- gpr_mu_unlock(cq->mu);
- const char* msg = grpc_error_string(err);
- gpr_log(GPR_ERROR, "Completion queue pluck failed: %s", msg);
-
- GRPC_ERROR_UNREF(err);
- ret.type = GRPC_QUEUE_TIMEOUT;
+ dump_pending_tags(cq);
+ break;
+ }
+ cq->num_polls++;
+ grpc_error* err =
+ cq->poller_vtable->work(POLLSET_FROM_CQ(cq), &worker, deadline_millis);
+ if (err != GRPC_ERROR_NONE) {
+ del_plucker(cq, tag, &worker);
+ gpr_mu_unlock(cq->mu);
+ const char* msg = grpc_error_string(err);
+ gpr_log(GPR_ERROR, "Completion queue pluck failed: %s", msg);
+
+ GRPC_ERROR_UNREF(err);
+ ret.type = GRPC_QUEUE_TIMEOUT;
ret.success = 0;
- dump_pending_tags(cq);
- break;
- }
- is_finished_arg.first_loop = false;
- del_plucker(cq, tag, &worker);
- }
-done:
- GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret);
- GRPC_CQ_INTERNAL_UNREF(cq, "pluck");
-
- GPR_ASSERT(is_finished_arg.stolen_completion == nullptr);
-
- return ret;
-}
-
-grpc_event grpc_completion_queue_pluck(grpc_completion_queue* cq, void* tag,
- gpr_timespec deadline, void* reserved) {
- return cq->vtable->pluck(cq, tag, deadline, reserved);
-}
-
-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);
+ dump_pending_tags(cq);
+ break;
+ }
+ is_finished_arg.first_loop = false;
+ del_plucker(cq, tag, &worker);
+ }
+done:
+ GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret);
+ GRPC_CQ_INTERNAL_UNREF(cq, "pluck");
+
+ GPR_ASSERT(is_finished_arg.stolen_completion == nullptr);
+
+ return ret;
+}
+
+grpc_event grpc_completion_queue_pluck(grpc_completion_queue* cq, void* tag,
+ gpr_timespec deadline, void* reserved) {
+ return cq->vtable->pluck(cq, tag, deadline, reserved);
+}
+
+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);
-
- cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
-}
-
-/* NOTE: This function is almost exactly identical to cq_shutdown_next() but
- * merging them is a bit tricky and probably not worth it */
-static void cq_shutdown_pluck(grpc_completion_queue* cq) {
- cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
-
- /* Need an extra ref for cq here because:
- * We call cq_finish_shutdown_pluck() below, that would call pollset shutdown.
- * Pollset shutdown decrements the cq ref count which can potentially destroy
- * the cq (if that happens to be the last ref).
- * Creating an extra ref here prevents the cq from getting destroyed while
- * this function is still active */
- GRPC_CQ_INTERNAL_REF(cq, "shutting_down (pluck cq)");
- gpr_mu_lock(cq->mu);
- if (cqd->shutdown_called) {
- gpr_mu_unlock(cq->mu);
- GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (pluck cq)");
- return;
- }
- cqd->shutdown_called = true;
+
+ cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
+}
+
+/* NOTE: This function is almost exactly identical to cq_shutdown_next() but
+ * merging them is a bit tricky and probably not worth it */
+static void cq_shutdown_pluck(grpc_completion_queue* cq) {
+ cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
+
+ /* Need an extra ref for cq here because:
+ * We call cq_finish_shutdown_pluck() below, that would call pollset shutdown.
+ * Pollset shutdown decrements the cq ref count which can potentially destroy
+ * the cq (if that happens to be the last ref).
+ * Creating an extra ref here prevents the cq from getting destroyed while
+ * this function is still active */
+ GRPC_CQ_INTERNAL_REF(cq, "shutting_down (pluck cq)");
+ gpr_mu_lock(cq->mu);
+ if (cqd->shutdown_called) {
+ gpr_mu_unlock(cq->mu);
+ GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (pluck cq)");
+ return;
+ }
+ cqd->shutdown_called = true;
if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) {
- cq_finish_shutdown_pluck(cq);
- }
- gpr_mu_unlock(cq->mu);
- GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (pluck cq)");
-}
-
+ cq_finish_shutdown_pluck(cq);
+ }
+ gpr_mu_unlock(cq->mu);
+ GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (pluck cq)");
+}
+
static void cq_finish_shutdown_callback(grpc_completion_queue* cq) {
cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq);
auto* callback = cqd->shutdown_callback;
@@ -1405,29 +1405,29 @@ static void cq_shutdown_callback(grpc_completion_queue* cq) {
GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (callback cq)");
}
-/* Shutdown simply drops a ref that we reserved at creation time; if we drop
- to zero here, then enter shutdown mode and wake up any waiters */
-void grpc_completion_queue_shutdown(grpc_completion_queue* cq) {
- GPR_TIMER_SCOPE("grpc_completion_queue_shutdown", 0);
+/* Shutdown simply drops a ref that we reserved at creation time; if we drop
+ to zero here, then enter shutdown mode and wake up any waiters */
+void grpc_completion_queue_shutdown(grpc_completion_queue* cq) {
+ GPR_TIMER_SCOPE("grpc_completion_queue_shutdown", 0);
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE("grpc_completion_queue_shutdown(cq=%p)", 1, (cq));
- cq->vtable->shutdown(cq);
-}
-
-void grpc_completion_queue_destroy(grpc_completion_queue* cq) {
- GPR_TIMER_SCOPE("grpc_completion_queue_destroy", 0);
- GRPC_API_TRACE("grpc_completion_queue_destroy(cq=%p)", 1, (cq));
- grpc_completion_queue_shutdown(cq);
-
- grpc_core::ExecCtx exec_ctx;
- GRPC_CQ_INTERNAL_UNREF(cq, "destroy");
-}
-
-grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cq) {
- return cq->poller_vtable->can_get_pollset ? POLLSET_FROM_CQ(cq) : nullptr;
-}
-
-bool grpc_cq_can_listen(grpc_completion_queue* cq) {
- return cq->poller_vtable->can_listen;
-}
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE("grpc_completion_queue_shutdown(cq=%p)", 1, (cq));
+ cq->vtable->shutdown(cq);
+}
+
+void grpc_completion_queue_destroy(grpc_completion_queue* cq) {
+ GPR_TIMER_SCOPE("grpc_completion_queue_destroy", 0);
+ GRPC_API_TRACE("grpc_completion_queue_destroy(cq=%p)", 1, (cq));
+ grpc_completion_queue_shutdown(cq);
+
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_CQ_INTERNAL_UNREF(cq, "destroy");
+}
+
+grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cq) {
+ return cq->poller_vtable->can_get_pollset ? POLLSET_FROM_CQ(cq) : nullptr;
+}
+
+bool grpc_cq_can_listen(grpc_completion_queue* cq) {
+ return cq->poller_vtable->can_listen;
+}
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 4a114be8285..f979143f8a9 100644
--- a/contrib/libs/grpc/src/core/lib/surface/completion_queue.h
+++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015-2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,77 +21,77 @@
/* Internal API for completion queues */
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/grpc.h>
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.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
if grpc_api_trace is also truthy */
-extern grpc_core::TraceFlag grpc_cq_pluck_trace;
-extern grpc_core::TraceFlag grpc_trace_operation_failures;
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_pending_tags;
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_cq_refcount;
+extern grpc_core::TraceFlag grpc_cq_pluck_trace;
+extern grpc_core::TraceFlag grpc_trace_operation_failures;
+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;
-
+
/** user supplied tag */
- void* tag;
+ void* tag;
/** done callback - called when this queue element is no longer
needed by the completion queue */
- void (*done)(void* done_arg, struct grpc_cq_completion* c);
- void* done_arg;
+ void (*done)(void* done_arg, struct grpc_cq_completion* c);
+ void* done_arg;
/** next pointer; low bit is used to indicate success or not */
uintptr_t next;
} grpc_cq_completion;
-#ifndef NDEBUG
-void grpc_cq_internal_ref(grpc_completion_queue* cc, const char* reason,
- const char* file, int line);
-void grpc_cq_internal_unref(grpc_completion_queue* cc, const char* reason,
- const char* file, int line);
+#ifndef NDEBUG
+void grpc_cq_internal_ref(grpc_completion_queue* cc, const char* reason,
+ const char* file, int line);
+void grpc_cq_internal_unref(grpc_completion_queue* cc, const char* reason,
+ const char* file, int line);
#define GRPC_CQ_INTERNAL_REF(cc, reason) \
grpc_cq_internal_ref(cc, reason, __FILE__, __LINE__)
#define GRPC_CQ_INTERNAL_UNREF(cc, reason) \
grpc_cq_internal_unref(cc, reason, __FILE__, __LINE__)
#else
-void grpc_cq_internal_ref(grpc_completion_queue* cc);
-void grpc_cq_internal_unref(grpc_completion_queue* cc);
+void grpc_cq_internal_ref(grpc_completion_queue* cc);
+void grpc_cq_internal_unref(grpc_completion_queue* cc);
#define GRPC_CQ_INTERNAL_REF(cc, reason) grpc_cq_internal_ref(cc)
#define GRPC_CQ_INTERNAL_UNREF(cc, reason) grpc_cq_internal_unref(cc)
#endif
-/* Initializes global variables used by completion queues */
-void grpc_cq_global_init();
-
+/* Initializes global variables used by completion queues */
+void grpc_cq_global_init();
+
/* Flag that an operation is beginning: the completion channel will not finish
shutdown until a corrensponding grpc_cq_end_* call is made.
- \a tag is currently used only in debug builds. Return true on success, and
- false if completion_queue has been shutdown. */
-bool grpc_cq_begin_op(grpc_completion_queue* cc, void* tag);
+ \a tag is currently used only in debug builds. Return true on success, and
+ false if completion_queue has been shutdown. */
+bool grpc_cq_begin_op(grpc_completion_queue* cc, void* tag);
/* Queue a GRPC_OP_COMPLETED operation; tag must correspond to the tag passed to
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 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);
-grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cc);
+grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cc);
-bool grpc_cq_can_listen(grpc_completion_queue* cc);
+bool grpc_cq_can_listen(grpc_completion_queue* cc);
-grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cc);
+grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cc);
-int grpc_get_cq_poll_num(grpc_completion_queue* cc);
-
-grpc_completion_queue* grpc_completion_queue_create_internal(
+int grpc_get_cq_poll_num(grpc_completion_queue* cc);
+
+grpc_completion_queue* grpc_completion_queue_create_internal(
grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type,
grpc_experimental_completion_queue_functor* shutdown_callback);
-
+
#endif /* GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_H */
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 72aa03adfd4..0cc56c3483e 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
@@ -1,76 +1,76 @@
-/*
- *
- * 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/surface/completion_queue.h"
-#include "src/core/lib/surface/completion_queue_factory.h"
-
-#include <grpc/support/log.h>
-
-/*
- * == Default completion queue factory implementation ==
- */
-
-static grpc_completion_queue* default_create(
+/*
+ *
+ * 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/surface/completion_queue.h"
+#include "src/core/lib/surface/completion_queue_factory.h"
+
+#include <grpc/support/log.h>
+
+/*
+ * == Default completion queue factory implementation ==
+ */
+
+static grpc_completion_queue* default_create(
const grpc_completion_queue_factory* /*factory*/,
- const grpc_completion_queue_attributes* attr) {
+ const grpc_completion_queue_attributes* attr) {
return grpc_completion_queue_create_internal(
attr->cq_completion_type, attr->cq_polling_type, attr->cq_shutdown_cb);
-}
-
-static grpc_completion_queue_factory_vtable default_vtable = {default_create};
-
-static const grpc_completion_queue_factory g_default_cq_factory = {
- "Default Factory", nullptr, &default_vtable};
-
-/*
- * == Completion queue factory APIs
- */
-
-const grpc_completion_queue_factory* grpc_completion_queue_factory_lookup(
- const grpc_completion_queue_attributes* attributes) {
- GPR_ASSERT(attributes->version >= 1 &&
- attributes->version <= GRPC_CQ_CURRENT_VERSION);
-
- /* The default factory can handle version 1 of the attributes structure. We
- may have to change this as more fields are added to the structure */
- return &g_default_cq_factory;
-}
-
-/*
- * == Completion queue creation APIs ==
- */
-
-grpc_completion_queue* grpc_completion_queue_create_for_next(void* reserved) {
- GPR_ASSERT(!reserved);
- grpc_completion_queue_attributes attr = {1, GRPC_CQ_NEXT,
+}
+
+static grpc_completion_queue_factory_vtable default_vtable = {default_create};
+
+static const grpc_completion_queue_factory g_default_cq_factory = {
+ "Default Factory", nullptr, &default_vtable};
+
+/*
+ * == Completion queue factory APIs
+ */
+
+const grpc_completion_queue_factory* grpc_completion_queue_factory_lookup(
+ const grpc_completion_queue_attributes* attributes) {
+ GPR_ASSERT(attributes->version >= 1 &&
+ attributes->version <= GRPC_CQ_CURRENT_VERSION);
+
+ /* The default factory can handle version 1 of the attributes structure. We
+ may have to change this as more fields are added to the structure */
+ return &g_default_cq_factory;
+}
+
+/*
+ * == Completion queue creation APIs ==
+ */
+
+grpc_completion_queue* grpc_completion_queue_create_for_next(void* reserved) {
+ GPR_ASSERT(!reserved);
+ grpc_completion_queue_attributes attr = {1, GRPC_CQ_NEXT,
GRPC_CQ_DEFAULT_POLLING, nullptr};
- return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr);
-}
-
-grpc_completion_queue* grpc_completion_queue_create_for_pluck(void* reserved) {
- GPR_ASSERT(!reserved);
- grpc_completion_queue_attributes attr = {1, GRPC_CQ_PLUCK,
+ return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr);
+}
+
+grpc_completion_queue* grpc_completion_queue_create_for_pluck(void* reserved) {
+ GPR_ASSERT(!reserved);
+ grpc_completion_queue_attributes attr = {1, GRPC_CQ_PLUCK,
GRPC_CQ_DEFAULT_POLLING, nullptr};
- return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr);
-}
-
+ return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr);
+}
+
grpc_completion_queue* grpc_completion_queue_create_for_callback(
grpc_experimental_completion_queue_functor* shutdown_callback,
void* reserved) {
@@ -80,9 +80,9 @@ grpc_completion_queue* grpc_completion_queue_create_for_callback(
return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr);
}
-grpc_completion_queue* grpc_completion_queue_create(
- const grpc_completion_queue_factory* factory,
- const grpc_completion_queue_attributes* attr, void* reserved) {
- GPR_ASSERT(!reserved);
- return factory->vtable->create(factory, attr);
-}
+grpc_completion_queue* grpc_completion_queue_create(
+ const grpc_completion_queue_factory* factory,
+ const grpc_completion_queue_attributes* attr, void* reserved) {
+ GPR_ASSERT(!reserved);
+ return factory->vtable->create(factory, attr);
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.h b/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.h
index d2b30a9ce19..a787fbc056c 100644
--- a/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.h
+++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.h
@@ -1,38 +1,38 @@
-/*
- *
- * 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_SURFACE_COMPLETION_QUEUE_FACTORY_H
-#define GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_FACTORY_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-#include "src/core/lib/surface/completion_queue.h"
-
-typedef struct grpc_completion_queue_factory_vtable {
- grpc_completion_queue* (*create)(const grpc_completion_queue_factory*,
- const grpc_completion_queue_attributes*);
-} grpc_completion_queue_factory_vtable;
-
-struct grpc_completion_queue_factory {
- const char* name;
- void* data; /* Factory specific data */
- grpc_completion_queue_factory_vtable* vtable;
-};
-
-#endif /* GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_FACTORY_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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_FACTORY_H
+#define GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_FACTORY_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+#include "src/core/lib/surface/completion_queue.h"
+
+typedef struct grpc_completion_queue_factory_vtable {
+ grpc_completion_queue* (*create)(const grpc_completion_queue_factory*,
+ const grpc_completion_queue_attributes*);
+} grpc_completion_queue_factory_vtable;
+
+struct grpc_completion_queue_factory {
+ const char* name;
+ void* data; /* Factory specific data */
+ grpc_completion_queue_factory_vtable* vtable;
+};
+
+#endif /* GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_FACTORY_H */
diff --git a/contrib/libs/grpc/src/core/lib/surface/event_string.cc b/contrib/libs/grpc/src/core/lib/surface/event_string.cc
index d69aac6deec..dabc6a845fa 100644
--- a/contrib/libs/grpc/src/core/lib/surface/event_string.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/event_string.cc
@@ -1,61 +1,61 @@
-/*
- *
- * 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/surface/event_string.h"
-
-#include <stdio.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/surface/event_string.h"
+
+#include <stdio.h>
+
#include <vector>
#include "y_absl/strings/str_format.h"
#include "y_absl/strings/str_join.h"
-#include <grpc/byte_buffer.h>
-#include <grpc/support/string_util.h>
-#include "src/core/lib/gpr/string.h"
-
+#include <grpc/byte_buffer.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/gpr/string.h"
+
static void addhdr(grpc_event* ev, std::vector<TString>* buf) {
buf->push_back(y_absl::StrFormat("tag:%p", ev->tag));
-}
-
-static const char* errstr(int success) { return success ? "OK" : "ERROR"; }
-
+}
+
+static const char* errstr(int success) { return success ? "OK" : "ERROR"; }
+
static void adderr(int success, std::vector<TString>* buf) {
buf->push_back(y_absl::StrFormat(" %s", errstr(success)));
-}
-
+}
+
TString grpc_event_string(grpc_event* ev) {
if (ev == nullptr) return "null";
std::vector<TString> out;
- switch (ev->type) {
- case GRPC_QUEUE_TIMEOUT:
+ switch (ev->type) {
+ case GRPC_QUEUE_TIMEOUT:
out.push_back("QUEUE_TIMEOUT");
- break;
- case GRPC_QUEUE_SHUTDOWN:
+ break;
+ case GRPC_QUEUE_SHUTDOWN:
out.push_back("QUEUE_SHUTDOWN");
- break;
- case GRPC_OP_COMPLETE:
+ break;
+ case GRPC_OP_COMPLETE:
out.push_back("OP_COMPLETE: ");
addhdr(ev, &out);
adderr(ev->success, &out);
- break;
- }
+ break;
+ }
return y_absl::StrJoin(out, "");
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/event_string.h b/contrib/libs/grpc/src/core/lib/surface/event_string.h
index f4ad847b3cd..97916bf2150 100644
--- a/contrib/libs/grpc/src/core/lib/surface/event_string.h
+++ b/contrib/libs/grpc/src/core/lib/surface/event_string.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_EVENT_STRING_H
#define GRPC_CORE_LIB_SURFACE_EVENT_STRING_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <util/generic/string.h>
#include <grpc/grpc.h>
diff --git a/contrib/libs/grpc/src/core/lib/surface/init.cc b/contrib/libs/grpc/src/core/lib/surface/init.cc
index 7b79ba426bc..71d4a8040ba 100644
--- a/contrib/libs/grpc/src/core/lib/surface/init.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/init.cc
@@ -1,187 +1,187 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/surface/init.h"
-#include <limits.h>
-#include <memory.h>
+#include <limits.h>
+#include <memory.h>
+
+#include <grpc/fork.h>
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
-#include <grpc/fork.h>
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/channel/channel_stack.h"
+#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channelz_registry.h"
-#include "src/core/lib/channel/connected_channel.h"
-#include "src/core/lib/channel/handshaker_registry.h"
-#include "src/core/lib/debug/stats.h"
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/channel/connected_channel.h"
+#include "src/core/lib/channel/handshaker_registry.h"
+#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/http/parser.h"
-#include "src/core/lib/iomgr/call_combiner.h"
-#include "src/core/lib/iomgr/combiner.h"
+#include "src/core/lib/http/parser.h"
+#include "src/core/lib/iomgr/call_combiner.h"
+#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/iomgr/resource_quota.h"
-#include "src/core/lib/iomgr/timer_manager.h"
-#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/surface/api_trace.h"
-#include "src/core/lib/surface/call.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/lib/surface/completion_queue.h"
-#include "src/core/lib/surface/lame_client.h"
-#include "src/core/lib/surface/server.h"
-#include "src/core/lib/transport/bdp_estimator.h"
-#include "src/core/lib/transport/connectivity_state.h"
-#include "src/core/lib/transport/transport_impl.h"
-
-/* (generated) built in registry of plugins */
-extern void grpc_register_built_in_plugins(void);
-
-#define MAX_PLUGINS 128
-
-static gpr_once g_basic_init = GPR_ONCE_INIT;
-static gpr_mu g_init_mu;
-static int g_initializations;
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/iomgr/resource_quota.h"
+#include "src/core/lib/iomgr/timer_manager.h"
+#include "src/core/lib/profiling/timers.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/surface/api_trace.h"
+#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/lib/surface/completion_queue.h"
+#include "src/core/lib/surface/lame_client.h"
+#include "src/core/lib/surface/server.h"
+#include "src/core/lib/transport/bdp_estimator.h"
+#include "src/core/lib/transport/connectivity_state.h"
+#include "src/core/lib/transport/transport_impl.h"
+
+/* (generated) built in registry of plugins */
+extern void grpc_register_built_in_plugins(void);
+
+#define MAX_PLUGINS 128
+
+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 void do_basic_init(void) {
- gpr_log_verbosity_init();
- gpr_mu_init(&g_init_mu);
+
+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;
- grpc_register_built_in_plugins();
- grpc_cq_global_init();
+ grpc_register_built_in_plugins();
+ grpc_cq_global_init();
grpc_core::grpc_executor_global_init();
gpr_time_init();
- g_initializations = 0;
-}
-
-static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
- return grpc_channel_stack_builder_append_filter(
- builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
-}
-
-static bool prepend_filter(grpc_channel_stack_builder* builder, void* arg) {
- return grpc_channel_stack_builder_prepend_filter(
- builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
-}
-
-static void register_builtin_channel_init() {
- grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
- GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- grpc_add_connected_filter, nullptr);
- grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL,
- GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- grpc_add_connected_filter, nullptr);
- grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
- GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- grpc_add_connected_filter, nullptr);
- grpc_channel_init_register_stage(GRPC_CLIENT_LAME_CHANNEL,
- GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
- append_filter, (void*)&grpc_lame_filter);
- grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, prepend_filter,
+ g_initializations = 0;
+}
+
+static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
+ return grpc_channel_stack_builder_append_filter(
+ builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
+}
+
+static bool prepend_filter(grpc_channel_stack_builder* builder, void* arg) {
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
+}
+
+static void register_builtin_channel_init() {
+ grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
+ GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ grpc_add_connected_filter, nullptr);
+ grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL,
+ GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ grpc_add_connected_filter, nullptr);
+ grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
+ GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ grpc_add_connected_filter, nullptr);
+ grpc_channel_init_register_stage(GRPC_CLIENT_LAME_CHANNEL,
+ GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
+ append_filter, (void*)&grpc_lame_filter);
+ grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, prepend_filter,
(void*)&grpc_core::Server::kServerTopFilter);
-}
-
-typedef struct grpc_plugin {
- void (*init)();
- void (*destroy)();
-} grpc_plugin;
-
-static grpc_plugin g_all_of_the_plugins[MAX_PLUGINS];
-static int g_number_of_plugins = 0;
-
-void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) {
- GRPC_API_TRACE("grpc_register_plugin(init=%p, destroy=%p)", 2,
- ((void*)(intptr_t)init, (void*)(intptr_t)destroy));
- GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS);
- g_all_of_the_plugins[g_number_of_plugins].init = init;
- g_all_of_the_plugins[g_number_of_plugins].destroy = destroy;
- g_number_of_plugins++;
-}
-
-void grpc_init(void) {
- int i;
- gpr_once_init(&g_basic_init, do_basic_init);
-
+}
+
+typedef struct grpc_plugin {
+ void (*init)();
+ void (*destroy)();
+} grpc_plugin;
+
+static grpc_plugin g_all_of_the_plugins[MAX_PLUGINS];
+static int g_number_of_plugins = 0;
+
+void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) {
+ GRPC_API_TRACE("grpc_register_plugin(init=%p, destroy=%p)", 2,
+ ((void*)(intptr_t)init, (void*)(intptr_t)destroy));
+ GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS);
+ g_all_of_the_plugins[g_number_of_plugins].init = init;
+ g_all_of_the_plugins[g_number_of_plugins].destroy = destroy;
+ g_number_of_plugins++;
+}
+
+void grpc_init(void) {
+ int i;
+ gpr_once_init(&g_basic_init, do_basic_init);
+
grpc_core::MutexLock lock(&g_init_mu);
- if (++g_initializations == 1) {
+ if (++g_initializations == 1) {
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_stats_init();
grpc_init_static_metadata_ctx();
- grpc_slice_intern_init();
- grpc_mdctx_global_init();
- grpc_channel_init_init();
+ grpc_slice_intern_init();
+ grpc_mdctx_global_init();
+ grpc_channel_init_init();
grpc_core::channelz::ChannelzRegistry::Init();
- grpc_security_pre_init();
+ grpc_security_pre_init();
grpc_core::ApplicationCallbackExecCtx::GlobalInit();
- grpc_core::ExecCtx::GlobalInit();
- grpc_iomgr_init();
- gpr_timers_global_init();
+ grpc_core::ExecCtx::GlobalInit();
+ grpc_iomgr_init();
+ gpr_timers_global_init();
grpc_core::HandshakerRegistry::Init();
- grpc_security_init();
- for (i = 0; i < g_number_of_plugins; i++) {
- if (g_all_of_the_plugins[i].init != nullptr) {
- g_all_of_the_plugins[i].init();
- }
- }
- /* register channel finalization AFTER all plugins, to ensure that it's run
- * at the appropriate time */
- grpc_register_security_filters();
- register_builtin_channel_init();
+ grpc_security_init();
+ for (i = 0; i < g_number_of_plugins; i++) {
+ if (g_all_of_the_plugins[i].init != nullptr) {
+ g_all_of_the_plugins[i].init();
+ }
+ }
+ /* register channel finalization AFTER all plugins, to ensure that it's run
+ * at the appropriate time */
+ grpc_register_security_filters();
+ register_builtin_channel_init();
grpc_tracer_init();
- /* no more changes to channel init pipelines */
- grpc_channel_init_finalize();
- grpc_iomgr_start();
- }
-
- GRPC_API_TRACE("grpc_init(void)", 0, ());
-}
-
+ /* no more changes to channel init pipelines */
+ grpc_channel_init_finalize();
+ grpc_iomgr_start();
+ }
+
+ GRPC_API_TRACE("grpc_init(void)", 0, ());
+}
+
void grpc_shutdown_internal_locked(void) {
- int i;
+ int i;
{
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_iomgr_shutdown();
gpr_timers_global_destroy();
grpc_tracer_shutdown();
@@ -190,7 +190,7 @@ void grpc_shutdown_internal_locked(void) {
grpc_slice_intern_shutdown();
grpc_core::channelz::ChannelzRegistry::Shutdown();
grpc_stats_shutdown();
- }
+ }
grpc_core::Fork::GlobalShutdown();
grpc_core::ExecCtx::GlobalShutdown();
grpc_core::ApplicationCallbackExecCtx::GlobalShutdown();
@@ -198,8 +198,8 @@ void grpc_shutdown_internal_locked(void) {
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);
@@ -249,13 +249,13 @@ void grpc_shutdown_blocking(void) {
}
}
-int grpc_is_initialized(void) {
- int r;
- gpr_once_init(&g_basic_init, do_basic_init);
+int grpc_is_initialized(void) {
+ int r;
+ gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
- r = g_initializations > 0;
- return r;
-}
+ r = g_initializations > 0;
+ return r;
+}
void grpc_maybe_wait_for_async_shutdown(void) {
gpr_once_init(&g_basic_init, do_basic_init);
diff --git a/contrib/libs/grpc/src/core/lib/surface/init.h b/contrib/libs/grpc/src/core/lib/surface/init.h
index 6eaa488d054..86d74d2df4c 100644
--- a/contrib/libs/grpc/src/core/lib/surface/init.h
+++ b/contrib/libs/grpc/src/core/lib/surface/init.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/core/lib/surface/init_secure.cc b/contrib/libs/grpc/src/core/lib/surface/init_secure.cc
index 428c5815c98..1bf4ae38b0f 100644
--- a/contrib/libs/grpc/src/core/lib/surface/init_secure.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/init_secure.cc
@@ -1,81 +1,81 @@
-/*
- *
- * 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/surface/init.h"
-
-#include <limits.h>
-#include <string.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/security/context/security_context.h"
-#include "src/core/lib/security/credentials/credentials.h"
-#include "src/core/lib/security/credentials/plugin/plugin_credentials.h"
-#include "src/core/lib/security/security_connector/security_connector.h"
-#include "src/core/lib/security/transport/auth_filters.h"
-#include "src/core/lib/security/transport/secure_endpoint.h"
-#include "src/core/lib/security/transport/security_handshaker.h"
-#include "src/core/lib/surface/channel_init.h"
-#include "src/core/tsi/transport_security_interface.h"
-
-void grpc_security_pre_init(void) {}
-
-static bool maybe_prepend_client_auth_filter(
+/*
+ *
+ * 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/surface/init.h"
+
+#include <limits.h>
+#include <string.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/security/context/security_context.h"
+#include "src/core/lib/security/credentials/credentials.h"
+#include "src/core/lib/security/credentials/plugin/plugin_credentials.h"
+#include "src/core/lib/security/security_connector/security_connector.h"
+#include "src/core/lib/security/transport/auth_filters.h"
+#include "src/core/lib/security/transport/secure_endpoint.h"
+#include "src/core/lib/security/transport/security_handshaker.h"
+#include "src/core/lib/surface/channel_init.h"
+#include "src/core/tsi/transport_security_interface.h"
+
+void grpc_security_pre_init(void) {}
+
+static bool maybe_prepend_client_auth_filter(
grpc_channel_stack_builder* builder, void* /*arg*/) {
- const grpc_channel_args* args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- if (args) {
- for (size_t i = 0; i < args->num_args; i++) {
- if (0 == strcmp(GRPC_ARG_SECURITY_CONNECTOR, args->args[i].key)) {
- return grpc_channel_stack_builder_prepend_filter(
- builder, &grpc_client_auth_filter, nullptr, nullptr);
- }
- }
- }
- return true;
-}
-
-static bool maybe_prepend_server_auth_filter(
+ const grpc_channel_args* args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ if (args) {
+ for (size_t i = 0; i < args->num_args; i++) {
+ if (0 == strcmp(GRPC_ARG_SECURITY_CONNECTOR, args->args[i].key)) {
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, &grpc_client_auth_filter, nullptr, nullptr);
+ }
+ }
+ }
+ return true;
+}
+
+static bool maybe_prepend_server_auth_filter(
grpc_channel_stack_builder* builder, void* /*arg*/) {
- const grpc_channel_args* args =
- grpc_channel_stack_builder_get_channel_arguments(builder);
- if (args) {
- for (size_t i = 0; i < args->num_args; i++) {
- if (0 == strcmp(GRPC_SERVER_CREDENTIALS_ARG, args->args[i].key)) {
- return grpc_channel_stack_builder_prepend_filter(
- builder, &grpc_server_auth_filter, nullptr, nullptr);
- }
- }
- }
- return true;
-}
-
-void grpc_register_security_filters(void) {
- // Register the auth client with a priority < INT_MAX to allow the authority
- // filter -on which the auth filter depends- to be higher on the channel
- // stack.
- grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, INT_MAX - 1,
- maybe_prepend_client_auth_filter, nullptr);
- grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, INT_MAX - 1,
- maybe_prepend_client_auth_filter, nullptr);
+ const grpc_channel_args* args =
+ grpc_channel_stack_builder_get_channel_arguments(builder);
+ if (args) {
+ for (size_t i = 0; i < args->num_args; i++) {
+ if (0 == strcmp(GRPC_SERVER_CREDENTIALS_ARG, args->args[i].key)) {
+ return grpc_channel_stack_builder_prepend_filter(
+ builder, &grpc_server_auth_filter, nullptr, nullptr);
+ }
+ }
+ }
+ return true;
+}
+
+void grpc_register_security_filters(void) {
+ // Register the auth client with a priority < INT_MAX to allow the authority
+ // filter -on which the auth filter depends- to be higher on the channel
+ // stack.
+ grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, INT_MAX - 1,
+ maybe_prepend_client_auth_filter, nullptr);
+ grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, INT_MAX - 1,
+ maybe_prepend_client_auth_filter, nullptr);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX - 1,
- maybe_prepend_server_auth_filter, nullptr);
-}
-
+ maybe_prepend_server_auth_filter, nullptr);
+}
+
void grpc_security_init() { grpc_core::SecurityRegisterHandshakerFactories(); }
diff --git a/contrib/libs/grpc/src/core/lib/surface/init_unsecure.cc b/contrib/libs/grpc/src/core/lib/surface/init_unsecure.cc
index 2b3bc643820..5e77ca7d5e6 100644
--- a/contrib/libs/grpc/src/core/lib/surface/init_unsecure.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/init_unsecure.cc
@@ -1,27 +1,27 @@
-/*
- *
- * 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/surface/init.h"
-
-void grpc_security_pre_init(void) {}
-
-void grpc_register_security_filters(void) {}
-
-void grpc_security_init(void) {}
+/*
+ *
+ * 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/surface/init.h"
+
+void grpc_security_pre_init(void) {}
+
+void grpc_register_security_filters(void) {}
+
+void grpc_security_init(void) {}
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 a9f5c9c7791..6ada4a7fc47 100644
--- a/contrib/libs/grpc/src/core/lib/surface/lame_client.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/lame_client.cc
@@ -1,104 +1,104 @@
-/*
- *
- * 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 <grpc/grpc.h>
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-#include "src/core/lib/gpr/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 <grpc/grpc.h>
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#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/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/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/static_metadata.h"
-
-namespace grpc_core {
-
-namespace {
-
-struct CallData {
+#include "src/core/lib/transport/static_metadata.h"
+
+namespace grpc_core {
+
+namespace {
+
+struct CallData {
CallCombiner* call_combiner;
- grpc_linked_mdelem status;
- grpc_linked_mdelem details;
+ grpc_linked_mdelem status;
+ grpc_linked_mdelem details;
Atomic<bool> filled_metadata;
-};
-
-struct ChannelData {
+};
+
+struct ChannelData {
ChannelData() : state_tracker("lame_channel", GRPC_CHANNEL_SHUTDOWN) {}
- grpc_status_code error_code;
- const char* error_message;
+ grpc_status_code error_code;
+ const char* error_message;
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;
+};
+
+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)) {
- 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(
+ 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));
- calld->details.md = grpc_mdelem_from_slices(
- GRPC_MDSTR_GRPC_MESSAGE,
+ calld->details.md = grpc_mdelem_from_slices(
+ GRPC_MDSTR_GRPC_MESSAGE,
grpc_core::UnmanagedMemorySlice(chand->error_message));
- calld->status.prev = calld->details.next = nullptr;
- calld->status.next = &calld->details;
- calld->details.prev = &calld->status;
- mdb->list.head = &calld->status;
- mdb->list.tail = &calld->details;
- mdb->list.count = 2;
- mdb->deadline = GRPC_MILLIS_INF_FUTURE;
-}
-
-static void lame_start_transport_stream_op_batch(
- grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
- CallData* calld = static_cast<CallData*>(elem->call_data);
- if (op->recv_initial_metadata) {
- fill_metadata(elem,
- op->payload->recv_initial_metadata.recv_initial_metadata);
- } else if (op->recv_trailing_metadata) {
- fill_metadata(elem,
- op->payload->recv_trailing_metadata.recv_trailing_metadata);
- }
- grpc_transport_stream_op_batch_finish_with_failure(
- op, GRPC_ERROR_CREATE_FROM_STATIC_STRING("lame client channel"),
- calld->call_combiner);
-}
-
+ calld->status.prev = calld->details.next = nullptr;
+ calld->status.next = &calld->details;
+ calld->details.prev = &calld->status;
+ mdb->list.head = &calld->status;
+ mdb->list.tail = &calld->details;
+ mdb->list.count = 2;
+ mdb->deadline = GRPC_MILLIS_INF_FUTURE;
+}
+
+static void lame_start_transport_stream_op_batch(
+ grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
+ CallData* calld = static_cast<CallData*>(elem->call_data);
+ if (op->recv_initial_metadata) {
+ fill_metadata(elem,
+ op->payload->recv_initial_metadata.recv_initial_metadata);
+ } else if (op->recv_trailing_metadata) {
+ fill_metadata(elem,
+ op->payload->recv_trailing_metadata.recv_trailing_metadata);
+ }
+ grpc_transport_stream_op_batch_finish_with_failure(
+ op, GRPC_ERROR_CREATE_FROM_STATIC_STRING("lame client channel"),
+ calld->call_combiner);
+}
+
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) {
+
+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);
@@ -109,83 +109,83 @@ static void lame_start_transport_op(grpc_channel_element* elem,
if (op->stop_connectivity_watch != nullptr) {
chand->state_tracker.RemoveWatcher(op->stop_connectivity_watch);
}
- }
- if (op->send_ping.on_initiate != nullptr) {
+ }
+ 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"));
- }
- if (op->send_ping.on_ack != nullptr) {
+ }
+ 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"));
- }
- GRPC_ERROR_UNREF(op->disconnect_with_error);
- if (op->on_consumed != nullptr) {
+ }
+ GRPC_ERROR_UNREF(op->disconnect_with_error);
+ if (op->on_consumed != nullptr) {
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) {
- CallData* calld = static_cast<CallData*>(elem->call_data);
- calld->call_combiner = args->call_combiner;
- return GRPC_ERROR_NONE;
-}
-
+ 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 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);
+ GPR_ASSERT(args->is_first);
+ GPR_ASSERT(args->is_last);
new (elem->channel_data) ChannelData;
- return GRPC_ERROR_NONE;
-}
-
+ return GRPC_ERROR_NONE;
+}
+
static void lame_destroy_channel_elem(grpc_channel_element* elem) {
ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
chand->~ChannelData();
}
-
-} // namespace
-
-} // namespace grpc_core
-
-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),
+
+} // namespace
+
+} // namespace grpc_core
+
+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_call_stack_ignore_set_pollset_or_pollset_set,
+ grpc_call_stack_ignore_set_pollset_or_pollset_set,
grpc_core::lame_destroy_call_elem,
- sizeof(grpc_core::ChannelData),
+ sizeof(grpc_core::ChannelData),
grpc_core::lame_init_channel_elem,
grpc_core::lame_destroy_channel_elem,
- grpc_core::lame_get_channel_info,
- "lame-client",
-};
-
-#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack*)((c) + 1))
-
-grpc_channel* grpc_lame_client_channel_create(const char* target,
- grpc_status_code error_code,
- const char* error_message) {
- grpc_core::ExecCtx exec_ctx;
- grpc_channel_element* elem;
- grpc_channel* channel =
- grpc_channel_create(target, nullptr, GRPC_CLIENT_LAME_CHANNEL, nullptr);
- elem = grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0);
- GRPC_API_TRACE(
- "grpc_lame_client_channel_create(target=%s, error_code=%d, "
- "error_message=%s)",
- 3, (target, (int)error_code, error_message));
- GPR_ASSERT(elem->filter == &grpc_lame_filter);
- auto chand = static_cast<grpc_core::ChannelData*>(elem->channel_data);
- chand->error_code = error_code;
- chand->error_message = error_message;
-
- return channel;
-}
+ grpc_core::lame_get_channel_info,
+ "lame-client",
+};
+
+#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack*)((c) + 1))
+
+grpc_channel* grpc_lame_client_channel_create(const char* target,
+ grpc_status_code error_code,
+ const char* error_message) {
+ grpc_core::ExecCtx exec_ctx;
+ grpc_channel_element* elem;
+ grpc_channel* channel =
+ grpc_channel_create(target, nullptr, GRPC_CLIENT_LAME_CHANNEL, nullptr);
+ elem = grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0);
+ GRPC_API_TRACE(
+ "grpc_lame_client_channel_create(target=%s, error_code=%d, "
+ "error_message=%s)",
+ 3, (target, (int)error_code, error_message));
+ GPR_ASSERT(elem->filter == &grpc_lame_filter);
+ auto chand = static_cast<grpc_core::ChannelData*>(elem->channel_data);
+ chand->error_code = error_code;
+ chand->error_message = error_message;
+
+ return channel;
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/lame_client.h b/contrib/libs/grpc/src/core/lib/surface/lame_client.h
index aefa67c24a6..db529d71be6 100644
--- a/contrib/libs/grpc/src/core/lib/surface/lame_client.h
+++ b/contrib/libs/grpc/src/core/lib/surface/lame_client.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SURFACE_LAME_CLIENT_H
#define GRPC_CORE_LIB_SURFACE_LAME_CLIENT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/channel/channel_stack.h"
extern const grpc_channel_filter grpc_lame_filter;
diff --git a/contrib/libs/grpc/src/core/lib/surface/metadata_array.cc b/contrib/libs/grpc/src/core/lib/surface/metadata_array.cc
index f794a2bb952..975b391eff0 100644
--- a/contrib/libs/grpc/src/core/lib/surface/metadata_array.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/metadata_array.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-
-#include <string.h>
-
-#include "src/core/lib/surface/api_trace.h"
-
-void grpc_metadata_array_init(grpc_metadata_array* array) {
- GRPC_API_TRACE("grpc_metadata_array_init(array=%p)", 1, (array));
- memset(array, 0, sizeof(*array));
-}
-
-void grpc_metadata_array_destroy(grpc_metadata_array* array) {
- GRPC_API_TRACE("grpc_metadata_array_destroy(array=%p)", 1, (array));
- gpr_free(array->metadata);
-}
+/*
+ *
+ * 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 <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+
+#include <string.h>
+
+#include "src/core/lib/surface/api_trace.h"
+
+void grpc_metadata_array_init(grpc_metadata_array* array) {
+ GRPC_API_TRACE("grpc_metadata_array_init(array=%p)", 1, (array));
+ memset(array, 0, sizeof(*array));
+}
+
+void grpc_metadata_array_destroy(grpc_metadata_array* array) {
+ GRPC_API_TRACE("grpc_metadata_array_destroy(array=%p)", 1, (array));
+ gpr_free(array->metadata);
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/server.cc b/contrib/libs/grpc/src/core/lib/surface/server.cc
index 0775c6ee4c4..f4ccf0b3b05 100644
--- a/contrib/libs/grpc/src/core/lib/surface/server.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/server.cc
@@ -13,15 +13,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/surface/server.h"
-
-#include <limits.h>
-#include <stdlib.h>
-#include <string.h>
-
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/surface/server.h"
+
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+
#include <algorithm>
#include <atomic>
#include <iterator>
@@ -32,30 +32,30 @@
#include "y_absl/types/optional.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 <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/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/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/iomgr/executor.h"
-#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/slice/slice_internal.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/completion_queue.h"
-#include "src/core/lib/surface/init.h"
-#include "src/core/lib/transport/metadata.h"
-#include "src/core/lib/transport/static_metadata.h"
-
+#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/iomgr.h"
+#include "src/core/lib/slice/slice_internal.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/completion_queue.h"
+#include "src/core/lib/surface/init.h"
+#include "src/core/lib/transport/metadata.h"
+#include "src/core/lib/transport/static_metadata.h"
+
namespace grpc_core {
-
+
TraceFlag grpc_server_channel_trace(false, "server_channel");
//
@@ -96,24 +96,24 @@ struct Server::RequestedCall {
void* const tag;
grpc_completion_queue* const cq_bound_to_call;
grpc_call** const call;
- grpc_cq_completion completion;
+ grpc_cq_completion completion;
grpc_metadata_array* const initial_metadata;
- union {
- struct {
- grpc_call_details* details;
- } batch;
- struct {
+ union {
+ struct {
+ grpc_call_details* details;
+ } batch;
+ struct {
RegisteredMethod* method;
- gpr_timespec* deadline;
- grpc_byte_buffer** optional_payload;
- } registered;
- } data;
-};
-
+ gpr_timespec* deadline;
+ grpc_byte_buffer** optional_payload;
+ } registered;
+ } data;
+};
+
//
// Server::RegisteredMethod
//
-
+
struct Server::RegisteredMethod {
RegisteredMethod(
const char* method_arg, const char* host_arg,
@@ -123,9 +123,9 @@ struct Server::RegisteredMethod {
host(host_arg == nullptr ? "" : host_arg),
payload_handling(payload_handling_arg),
flags(flags_arg) {}
-
+
~RegisteredMethod() = default;
-
+
const TString method;
const TString host;
const grpc_server_register_method_payload_handling payload_handling;
@@ -133,11 +133,11 @@ struct Server::RegisteredMethod {
// One request matcher per method.
std::unique_ptr<RequestMatcherInterface> matcher;
};
-
+
//
// Server::RequestMatcherInterface
//
-
+
// RPCs that come in from the transport must be matched against RPC requests
// from the application. An incoming request from the application can be matched
// to an RPC that has already arrived or can be queued up for later use.
@@ -199,8 +199,8 @@ class Server::RealRequestMatcher : public RequestMatcherInterface {
for (LockedMultiProducerSingleConsumerQueue& queue : requests_per_cq_) {
GPR_ASSERT(queue.Pop() == nullptr);
}
- }
-
+ }
+
void ZombifyPending() override {
while (!pending_.empty()) {
CallData* calld = pending_.front();
@@ -208,8 +208,8 @@ class Server::RealRequestMatcher : public RequestMatcherInterface {
calld->KillZombie();
pending_.pop();
}
- }
-
+ }
+
void KillRequests(grpc_error* error) override {
for (size_t i = 0; i < requests_per_cq_.size(); i++) {
RequestedCall* rc;
@@ -220,11 +220,11 @@ class Server::RealRequestMatcher : public RequestMatcherInterface {
}
GRPC_ERROR_UNREF(error);
}
-
+
size_t request_queue_count() const override {
return requests_per_cq_.size();
- }
-
+ }
+
void RequestCallWithPossiblePublish(size_t request_queue_index,
RequestedCall* call) override {
if (requests_per_cq_[request_queue_index].Push(&call->mpscq_node)) {
@@ -259,9 +259,9 @@ class Server::RealRequestMatcher : public RequestMatcherInterface {
next_pending.calld->Publish(request_queue_index, next_pending.rc);
}
}
- }
- }
-
+ }
+ }
+
void MatchOrQueue(size_t start_request_queue_index,
CallData* calld) override {
for (size_t i = 0; i < requests_per_cq_.size(); i++) {
@@ -418,9 +418,9 @@ class Server::AllocatingRequestMatcherRegistered
//
// ChannelBroadcaster
//
-
+
namespace {
-
+
class ChannelBroadcaster {
public:
// This can have an empty constructor and destructor since we want to control
@@ -430,7 +430,7 @@ class ChannelBroadcaster {
void FillChannelsLocked(std::vector<grpc_channel*> channels) {
GPR_DEBUG_ASSERT(channels_.empty());
channels_ = std::move(channels);
- }
+ }
// Broadcasts a shutdown on each channel.
void BroadcastShutdown(bool send_goaway, grpc_error* force_disconnect) {
@@ -440,7 +440,7 @@ class ChannelBroadcaster {
}
channels_.clear(); // just for safety against double broadcast
GRPC_ERROR_UNREF(force_disconnect);
- }
+ }
private:
struct ShutdownCleanupArgs {
@@ -509,8 +509,8 @@ grpc_resource_user* CreateDefaultResourceUser(const grpc_channel_args* args) {
}
}
return nullptr;
-}
-
+}
+
RefCountedPtr<channelz::ServerNode> CreateChannelzNode(
Server* server, const grpc_channel_args* args) {
RefCountedPtr<channelz::ServerNode> channelz_node;
@@ -524,12 +524,12 @@ RefCountedPtr<channelz::ServerNode> CreateChannelzNode(
channelz_node->AddTraceEvent(
channelz::ChannelTrace::Severity::Info,
grpc_slice_from_static_string("Server created"));
- }
+ }
return channelz_node;
-}
-
+}
+
} // namespace
-
+
Server::Server(const grpc_channel_args* args)
: channel_args_(grpc_channel_args_copy(args)),
default_resource_user_(CreateDefaultResourceUser(args)),
@@ -540,8 +540,8 @@ Server::~Server() {
for (size_t i = 0; i < cqs_.size(); i++) {
GRPC_CQ_INTERNAL_UNREF(cqs_[i], "server");
}
-}
-
+}
+
void Server::AddListener(OrphanablePtr<ListenerInterface> listener) {
channelz::ListenSocketNode* listen_socket_node =
listener->channelz_listen_socket_node();
@@ -549,8 +549,8 @@ void Server::AddListener(OrphanablePtr<ListenerInterface> listener) {
channelz_node_->AddChildListenSocket(listen_socket_node->Ref());
}
listeners_.emplace_back(std::move(listener));
-}
-
+}
+
void Server::Start() {
started_ = true;
for (grpc_completion_queue* cq : cqs_) {
@@ -577,7 +577,7 @@ void Server::Start() {
starting_ = false;
starting_cv_.Signal();
}
-
+
void Server::SetupTransport(
grpc_transport* transport, grpc_pollset* accepting_pollset,
const grpc_channel_args* args,
@@ -593,7 +593,7 @@ void Server::SetupTransport(
size_t cq_idx;
for (cq_idx = 0; cq_idx < cqs_.size(); cq_idx++) {
if (grpc_cq_pollset(cqs_[cq_idx]) == accepting_pollset) break;
- }
+ }
if (cq_idx == cqs_.size()) {
// Completion queue not found. Pick a random one to publish new calls to.
cq_idx = static_cast<size_t>(rand()) % cqs_.size();
@@ -607,20 +607,20 @@ void Server::SetupTransport(
// Initialize chand.
chand->InitTransport(Ref(), channel, cq_idx, transport, channelz_socket_uuid);
}
-
+
bool Server::HasOpenConnections() {
MutexLock lock(&mu_global_);
return !channels_.empty();
-}
-
+}
+
void Server::SetRegisteredMethodAllocator(
grpc_completion_queue* cq, void* method_tag,
std::function<RegisteredCallAllocation()> allocator) {
RegisteredMethod* rm = static_cast<RegisteredMethod*>(method_tag);
rm->matcher = y_absl::make_unique<AllocatingRequestMatcherRegistered>(
this, cq, rm, std::move(allocator));
-}
-
+}
+
void Server::SetBatchMethodAllocator(
grpc_completion_queue* cq, std::function<BatchCallAllocation()> allocator) {
GPR_DEBUG_ASSERT(unregistered_request_matcher_ == nullptr);
@@ -632,20 +632,20 @@ void Server::SetBatchMethodAllocator(
void Server::RegisterCompletionQueue(grpc_completion_queue* cq) {
for (grpc_completion_queue* queue : cqs_) {
if (queue == cq) return;
- }
+ }
GRPC_CQ_INTERNAL_REF(cq, "server");
cqs_.push_back(cq);
}
-
+
namespace {
bool streq(const TString& a, const char* b) {
return (a.empty() && b == nullptr) ||
((b != nullptr) && !strcmp(a.c_str(), b));
-}
-
+}
+
} // namespace
-
+
Server::RegisteredMethod* Server::RegisterMethod(
const char* method, const char* host,
grpc_server_register_method_payload_handling payload_handling,
@@ -654,7 +654,7 @@ Server::RegisteredMethod* Server::RegisterMethod(
gpr_log(GPR_ERROR,
"grpc_server_register_method method string cannot be NULL");
return nullptr;
- }
+ }
for (std::unique_ptr<RegisteredMethod>& m : registered_methods_) {
if (streq(m->method, method) && streq(m->host, host)) {
gpr_log(GPR_ERROR, "duplicate registration for %s@%s", method,
@@ -671,11 +671,11 @@ Server::RegisteredMethod* Server::RegisterMethod(
method, host, payload_handling, flags));
return registered_methods_.back().get();
}
-
+
void Server::DoneRequestEvent(void* req, grpc_cq_completion* /*c*/) {
delete static_cast<RequestedCall*>(req);
-}
-
+}
+
void Server::FailCall(size_t cq_idx, RequestedCall* rc, grpc_error* error) {
*rc->call = nullptr;
rc->initial_metadata->count = 0;
@@ -683,13 +683,13 @@ void Server::FailCall(size_t cq_idx, RequestedCall* rc, grpc_error* error) {
grpc_cq_end_op(cqs_[cq_idx], rc->tag, error, DoneRequestEvent, rc,
&rc->completion);
}
-
+
// Before calling MaybeFinishShutdown(), we must hold mu_global_ and not
// hold mu_call_.
void Server::MaybeFinishShutdown() {
if (!shutdown_flag_.load(std::memory_order_acquire) || shutdown_published_) {
- return;
- }
+ return;
+ }
{
MutexLock lock(&mu_call_);
KillPendingWorkLocked(
@@ -715,7 +715,7 @@ void Server::MaybeFinishShutdown() {
DoneShutdownEvent, this, &shutdown_tag.completion);
}
}
-
+
void Server::KillPendingWorkLocked(grpc_error* error) {
if (started_) {
unregistered_request_matcher_->KillRequests(GRPC_ERROR_REF(error));
@@ -723,11 +723,11 @@ void Server::KillPendingWorkLocked(grpc_error* error) {
for (std::unique_ptr<RegisteredMethod>& rm : registered_methods_) {
rm->matcher->KillRequests(GRPC_ERROR_REF(error));
rm->matcher->ZombifyPending();
- }
- }
+ }
+ }
GRPC_ERROR_UNREF(error);
-}
-
+}
+
std::vector<grpc_channel*> Server::GetChannelsLocked() const {
std::vector<grpc_channel*> channels;
channels.reserve(channels_.size());
@@ -737,7 +737,7 @@ std::vector<grpc_channel*> Server::GetChannelsLocked() const {
}
return channels;
}
-
+
void Server::ListenerDestroyDone(void* arg, grpc_error* /*error*/) {
Server* server = static_cast<Server*>(arg);
MutexLock lock(&server->mu_global_);
@@ -778,12 +778,12 @@ void Server::ShutdownAndNotify(grpc_completion_queue* cq, void* tag) {
if (shutdown_published_) {
grpc_cq_end_op(cq, tag, GRPC_ERROR_NONE, DonePublishedShutdown, nullptr,
new grpc_cq_completion);
- return;
- }
+ return;
+ }
shutdown_tags_.emplace_back(tag, cq);
if (shutdown_flag_.load(std::memory_order_acquire)) {
- return;
- }
+ return;
+ }
last_shutdown_message_time_ = gpr_now(GPR_CLOCK_REALTIME);
broadcaster.FillChannelsLocked(GetChannelsLocked());
shutdown_flag_.store(true, std::memory_order_release);
@@ -794,7 +794,7 @@ void Server::ShutdownAndNotify(grpc_completion_queue* cq, void* tag) {
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server Shutdown"));
}
MaybeFinishShutdown();
- }
+ }
// Shutdown listeners.
for (auto& listener : listeners_) {
channelz::ListenSocketNode* channelz_listen_socket_node =
@@ -809,19 +809,19 @@ void Server::ShutdownAndNotify(grpc_completion_queue* cq, void* tag) {
listener.listener.reset();
}
broadcaster.BroadcastShutdown(/*send_goaway=*/true, GRPC_ERROR_NONE);
-}
-
+}
+
void Server::CancelAllCalls() {
ChannelBroadcaster broadcaster;
{
MutexLock lock(&mu_global_);
broadcaster.FillChannelsLocked(GetChannelsLocked());
- }
+ }
broadcaster.BroadcastShutdown(
/*send_goaway=*/false,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Cancelling all calls"));
-}
-
+}
+
void Server::Orphan() {
{
MutexLock lock(&mu_global_);
@@ -835,8 +835,8 @@ void Server::Orphan() {
grpc_resource_user_unref(default_resource_user_);
}
Unref();
-}
-
+}
+
grpc_call_error Server::ValidateServerRequest(
grpc_completion_queue* cq_for_notification, void* tag,
grpc_byte_buffer** optional_payload, RegisteredMethod* rm) {
@@ -844,13 +844,13 @@ grpc_call_error Server::ValidateServerRequest(
((rm != nullptr) && ((optional_payload == nullptr) !=
(rm->payload_handling == GRPC_SRM_PAYLOAD_NONE)))) {
return GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH;
- }
+ }
if (grpc_cq_begin_op(cq_for_notification, tag) == false) {
return GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN;
}
return GRPC_CALL_OK;
-}
-
+}
+
grpc_call_error Server::ValidateServerRequestAndCq(
size_t* cq_idx, grpc_completion_queue* cq_for_notification, void* tag,
grpc_byte_buffer** optional_payload, RegisteredMethod* rm) {
@@ -858,8 +858,8 @@ grpc_call_error Server::ValidateServerRequestAndCq(
for (idx = 0; idx < cqs_.size(); idx++) {
if (cqs_[idx] == cq_for_notification) {
break;
- }
- }
+ }
+ }
if (idx == cqs_.size()) {
return GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE;
}
@@ -870,14 +870,14 @@ grpc_call_error Server::ValidateServerRequestAndCq(
}
*cq_idx = idx;
return GRPC_CALL_OK;
-}
-
+}
+
grpc_call_error Server::QueueRequestedCall(size_t cq_idx, RequestedCall* rc) {
if (shutdown_flag_.load(std::memory_order_acquire)) {
FailCall(cq_idx, rc,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server Shutdown"));
return GRPC_CALL_OK;
- }
+ }
RequestMatcherInterface* rm;
switch (rc->type) {
case RequestedCall::Type::BATCH_CALL:
@@ -890,7 +890,7 @@ grpc_call_error Server::QueueRequestedCall(size_t cq_idx, RequestedCall* rc) {
rm->RequestCallWithPossiblePublish(cq_idx, rc);
return GRPC_CALL_OK;
}
-
+
grpc_call_error Server::RequestCall(grpc_call** call,
grpc_call_details* details,
grpc_metadata_array* request_metadata,
@@ -907,7 +907,7 @@ grpc_call_error Server::RequestCall(grpc_call** call,
new RequestedCall(tag, cq_bound_to_call, call, request_metadata, details);
return QueueRequestedCall(cq_idx, rc);
}
-
+
grpc_call_error Server::RequestRegisteredCall(
RegisteredMethod* rm, grpc_call** call, gpr_timespec* deadline,
grpc_metadata_array* request_metadata, grpc_byte_buffer** optional_payload,
@@ -918,28 +918,28 @@ grpc_call_error Server::RequestRegisteredCall(
&cq_idx, cq_for_notification, tag_new, optional_payload, rm);
if (error != GRPC_CALL_OK) {
return error;
- }
+ }
RequestedCall* rc =
new RequestedCall(tag_new, cq_bound_to_call, call, request_metadata, rm,
deadline, optional_payload);
return QueueRequestedCall(cq_idx, rc);
-}
-
+}
+
//
// Server::ChannelData::ConnectivityWatcher
//
-
+
class Server::ChannelData::ConnectivityWatcher
: public AsyncConnectivityStateWatcherInterface {
public:
explicit ConnectivityWatcher(ChannelData* chand) : chand_(chand) {
GRPC_CHANNEL_INTERNAL_REF(chand_->channel_, "connectivity");
- }
+ }
~ConnectivityWatcher() {
GRPC_CHANNEL_INTERNAL_UNREF(chand_->channel_, "connectivity");
- }
-
+ }
+
private:
void OnConnectivityStateChange(grpc_connectivity_state new_state,
const y_absl::Status& /*status*/) override {
@@ -949,10 +949,10 @@ class Server::ChannelData::ConnectivityWatcher
MutexLock lock(&chand_->server_->mu_global_);
chand_->Destroy();
}
-
+
ChannelData* chand_;
};
-
+
//
// Server::ChannelData
//
@@ -970,7 +970,7 @@ Server::ChannelData::~ChannelData() {
}
}
registered_methods_.reset();
- }
+ }
if (server_ != nullptr) {
if (server_->channelz_node_ != nullptr && channelz_socket_uuid_ != 0) {
server_->channelz_node_->RemoveChildSocket(channelz_socket_uuid_);
@@ -984,8 +984,8 @@ Server::ChannelData::~ChannelData() {
server_->MaybeFinishShutdown();
}
}
-}
-
+}
+
void Server::ChannelData::InitTransport(RefCountedPtr<Server> server,
grpc_channel* channel, size_t cq_idx,
grpc_transport* transport,
@@ -1046,8 +1046,8 @@ void Server::ChannelData::InitTransport(RefCountedPtr<Server> server,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server shutdown");
}
grpc_transport_perform_op(transport, op);
-}
-
+}
+
Server::ChannelRegisteredMethod* Server::ChannelData::GetRegisteredMethod(
const grpc_slice& host, const grpc_slice& path, bool is_idempotent) {
if (registered_methods_ == nullptr) return nullptr;
@@ -1065,9 +1065,9 @@ Server::ChannelRegisteredMethod* Server::ChannelData::GetRegisteredMethod(
if ((rm->flags & GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST) &&
!is_idempotent) {
continue;
- }
+ }
return rm;
- }
+ }
/* check for a wildcard method definition (no host set) */
hash = GRPC_MDSTR_KV_HASH(0, grpc_slice_hash_internal(path));
for (size_t i = 0; i <= registered_method_max_probes_; i++) {
@@ -1083,43 +1083,43 @@ Server::ChannelRegisteredMethod* Server::ChannelData::GetRegisteredMethod(
return rm;
}
return nullptr;
-}
-
+}
+
void Server::ChannelData::AcceptStream(void* arg, grpc_transport* /*transport*/,
const void* transport_server_data) {
auto* chand = static_cast<Server::ChannelData*>(arg);
- /* create a call */
- grpc_call_create_args args;
+ /* create a call */
+ grpc_call_create_args args;
args.channel = chand->channel_;
args.server = chand->server_.get();
args.parent = nullptr;
args.propagation_mask = 0;
args.cq = nullptr;
args.pollset_set_alternative = nullptr;
- args.server_transport_data = transport_server_data;
+ args.server_transport_data = transport_server_data;
args.add_initial_metadata = nullptr;
args.add_initial_metadata_count = 0;
- args.send_deadline = GRPC_MILLIS_INF_FUTURE;
- grpc_call* call;
- grpc_error* error = grpc_call_create(&args, &call);
- grpc_call_element* elem =
- grpc_call_stack_element(grpc_call_get_call_stack(call), 0);
+ args.send_deadline = GRPC_MILLIS_INF_FUTURE;
+ grpc_call* call;
+ grpc_error* error = grpc_call_create(&args, &call);
+ grpc_call_element* elem =
+ grpc_call_stack_element(grpc_call_get_call_stack(call), 0);
auto* calld = static_cast<Server::CallData*>(elem->call_data);
- if (error != GRPC_ERROR_NONE) {
- GRPC_ERROR_UNREF(error);
+ if (error != GRPC_ERROR_NONE) {
+ GRPC_ERROR_UNREF(error);
calld->FailCallCreation();
- return;
- }
+ return;
+ }
calld->Start(elem);
-}
-
+}
+
void Server::ChannelData::FinishDestroy(void* cd, grpc_error* /*error*/) {
auto* chand = static_cast<Server::ChannelData*>(cd);
Server* server = chand->server_.get();
GRPC_CHANNEL_INTERNAL_UNREF(chand->channel_, "server");
server->Unref();
-}
-
+}
+
void Server::ChannelData::Destroy() {
if (!list_position_.has_value()) return;
GPR_ASSERT(server_ != nullptr);
@@ -1138,16 +1138,16 @@ void Server::ChannelData::Destroy() {
grpc_channel_next_op(
grpc_channel_stack_element(grpc_channel_get_channel_stack(channel_), 0),
op);
-}
-
+}
+
grpc_error* Server::ChannelData::InitChannelElement(
grpc_channel_element* elem, grpc_channel_element_args* args) {
- GPR_ASSERT(args->is_first);
- GPR_ASSERT(!args->is_last);
+ GPR_ASSERT(args->is_first);
+ GPR_ASSERT(!args->is_last);
new (elem->channel_data) ChannelData();
- return GRPC_ERROR_NONE;
-}
-
+ return GRPC_ERROR_NONE;
+}
+
void Server::ChannelData::DestroyChannelElement(grpc_channel_element* elem) {
auto* chand = static_cast<ChannelData*>(elem->channel_data);
chand->~ChannelData();
@@ -1174,14 +1174,14 @@ Server::CallData::~CallData() {
GRPC_ERROR_UNREF(recv_initial_metadata_error_);
if (host_.has_value()) {
grpc_slice_unref_internal(*host_);
- }
+ }
if (path_.has_value()) {
grpc_slice_unref_internal(*path_);
- }
+ }
grpc_metadata_array_destroy(&initial_metadata_);
grpc_byte_buffer_destroy(payload_);
-}
-
+}
+
void Server::CallData::SetState(CallState state) {
state_.Store(state, MemoryOrder::RELAXED);
}
@@ -1437,7 +1437,7 @@ void Server::CallData::StartTransportStreamOpBatch(
auto* calld = static_cast<CallData*>(elem->call_data);
calld->StartTransportStreamOpBatchImpl(elem, batch);
}
-
+
} // namespace grpc_core
//
@@ -1452,104 +1452,104 @@ grpc_server* grpc_server_create(const grpc_channel_args* args, void* reserved) {
return c_server;
}
-void grpc_server_register_completion_queue(grpc_server* server,
- grpc_completion_queue* cq,
- void* reserved) {
- GRPC_API_TRACE(
- "grpc_server_register_completion_queue(server=%p, cq=%p, reserved=%p)", 3,
- (server, cq, reserved));
+void grpc_server_register_completion_queue(grpc_server* server,
+ grpc_completion_queue* cq,
+ void* reserved) {
+ GRPC_API_TRACE(
+ "grpc_server_register_completion_queue(server=%p, cq=%p, reserved=%p)", 3,
+ (server, cq, reserved));
GPR_ASSERT(!reserved);
auto cq_type = grpc_get_cq_completion_type(cq);
if (cq_type != GRPC_CQ_NEXT && cq_type != GRPC_CQ_CALLBACK) {
- gpr_log(GPR_INFO,
+ gpr_log(GPR_INFO,
"Completion queue of type %d is being registered as a "
"server-completion-queue",
static_cast<int>(cq_type));
- /* Ideally we should log an error and abort but ruby-wrapped-language API
- calls grpc_completion_queue_pluck() on server completion queues */
- }
+ /* Ideally we should log an error and abort but ruby-wrapped-language API
+ calls grpc_completion_queue_pluck() on server completion queues */
+ }
server->core_server->RegisterCompletionQueue(cq);
-}
-
-void* grpc_server_register_method(
- grpc_server* server, const char* method, const char* host,
- grpc_server_register_method_payload_handling payload_handling,
- uint32_t flags) {
- GRPC_API_TRACE(
- "grpc_server_register_method(server=%p, method=%s, host=%s, "
- "flags=0x%08x)",
- 4, (server, method, host, flags));
+}
+
+void* grpc_server_register_method(
+ grpc_server* server, const char* method, const char* host,
+ grpc_server_register_method_payload_handling payload_handling,
+ uint32_t flags) {
+ GRPC_API_TRACE(
+ "grpc_server_register_method(server=%p, method=%s, host=%s, "
+ "flags=0x%08x)",
+ 4, (server, method, host, flags));
return server->core_server->RegisterMethod(method, host, payload_handling,
flags);
-}
-
-void grpc_server_start(grpc_server* server) {
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE("grpc_server_start(server=%p)", 1, (server));
+}
+
+void grpc_server_start(grpc_server* server) {
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE("grpc_server_start(server=%p)", 1, (server));
server->core_server->Start();
-}
-
-void grpc_server_shutdown_and_notify(grpc_server* server,
- grpc_completion_queue* cq, void* tag) {
+}
+
+void grpc_server_shutdown_and_notify(grpc_server* server,
+ grpc_completion_queue* cq, void* tag) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE("grpc_server_shutdown_and_notify(server=%p, cq=%p, tag=%p)", 3,
- (server, cq, tag));
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE("grpc_server_shutdown_and_notify(server=%p, cq=%p, tag=%p)", 3,
+ (server, cq, tag));
server->core_server->ShutdownAndNotify(cq, tag);
-}
-
-void grpc_server_cancel_all_calls(grpc_server* server) {
+}
+
+void grpc_server_cancel_all_calls(grpc_server* server) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE("grpc_server_cancel_all_calls(server=%p)", 1, (server));
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE("grpc_server_cancel_all_calls(server=%p)", 1, (server));
server->core_server->CancelAllCalls();
-}
-
-void grpc_server_destroy(grpc_server* server) {
+}
+
+void grpc_server_destroy(grpc_server* server) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- GRPC_API_TRACE("grpc_server_destroy(server=%p)", 1, (server));
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_API_TRACE("grpc_server_destroy(server=%p)", 1, (server));
delete server;
-}
-
-grpc_call_error grpc_server_request_call(
- grpc_server* server, grpc_call** call, grpc_call_details* details,
+}
+
+grpc_call_error grpc_server_request_call(
+ grpc_server* server, grpc_call** call, grpc_call_details* details,
grpc_metadata_array* request_metadata,
- grpc_completion_queue* cq_bound_to_call,
- grpc_completion_queue* cq_for_notification, void* tag) {
+ grpc_completion_queue* cq_bound_to_call,
+ grpc_completion_queue* cq_for_notification, void* tag) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- GRPC_STATS_INC_SERVER_REQUESTED_CALLS();
- GRPC_API_TRACE(
- "grpc_server_request_call("
- "server=%p, call=%p, details=%p, initial_metadata=%p, "
- "cq_bound_to_call=%p, cq_for_notification=%p, tag=%p)",
- 7,
+ grpc_core::ExecCtx exec_ctx;
+ GRPC_STATS_INC_SERVER_REQUESTED_CALLS();
+ GRPC_API_TRACE(
+ "grpc_server_request_call("
+ "server=%p, call=%p, details=%p, initial_metadata=%p, "
+ "cq_bound_to_call=%p, cq_for_notification=%p, tag=%p)",
+ 7,
(server, call, details, request_metadata, cq_bound_to_call,
- cq_for_notification, tag));
+ cq_for_notification, tag));
return server->core_server->RequestCall(call, details, request_metadata,
cq_bound_to_call, cq_for_notification,
tag);
-}
-
-grpc_call_error grpc_server_request_registered_call(
- grpc_server* server, void* rmp, grpc_call** call, gpr_timespec* deadline,
+}
+
+grpc_call_error grpc_server_request_registered_call(
+ grpc_server* server, void* rmp, grpc_call** call, gpr_timespec* deadline,
grpc_metadata_array* request_metadata, grpc_byte_buffer** optional_payload,
- grpc_completion_queue* cq_bound_to_call,
+ grpc_completion_queue* cq_bound_to_call,
grpc_completion_queue* cq_for_notification, void* tag_new) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
GRPC_STATS_INC_SERVER_REQUESTED_CALLS();
auto* rm = static_cast<grpc_core::Server::RegisteredMethod*>(rmp);
- GRPC_API_TRACE(
- "grpc_server_request_registered_call("
+ GRPC_API_TRACE(
+ "grpc_server_request_registered_call("
"server=%p, rmp=%p, call=%p, deadline=%p, request_metadata=%p, "
- "optional_payload=%p, cq_bound_to_call=%p, cq_for_notification=%p, "
- "tag=%p)",
- 9,
+ "optional_payload=%p, cq_bound_to_call=%p, cq_for_notification=%p, "
+ "tag=%p)",
+ 9,
(server, rmp, call, deadline, request_metadata, optional_payload,
cq_bound_to_call, cq_for_notification, tag_new));
return server->core_server->RequestRegisteredCall(
rm, call, deadline, request_metadata, optional_payload, cq_bound_to_call,
cq_for_notification, tag_new);
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/surface/server.h b/contrib/libs/grpc/src/core/lib/surface/server.h
index f4f4ff6449a..c39773f6346 100644
--- a/contrib/libs/grpc/src/core/lib/surface/server.h
+++ b/contrib/libs/grpc/src/core/lib/surface/server.h
@@ -17,8 +17,8 @@
#ifndef GRPC_CORE_LIB_SURFACE_SERVER_H
#define GRPC_CORE_LIB_SURFACE_SERVER_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <list>
#include <vector>
@@ -29,7 +29,7 @@
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/transport/transport.h"
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 138f5745e51..58a7fe665e3 100644
--- a/contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/validate_metadata.cc
@@ -1,105 +1,105 @@
-/*
- *
- * 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 <stdlib.h>
-#include <string.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.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 <stdlib.h>
+#include <string.h>
+
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.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"
-
+#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,
- const char* err_desc) {
- const uint8_t* p = GRPC_SLICE_START_PTR(slice);
- const uint8_t* e = GRPC_SLICE_END_PTR(slice);
- for (; p != e; p++) {
- int idx = *p;
- int byte = idx / 8;
- int bit = idx % 8;
- if ((legal_bits[byte] & (1 << bit)) == 0) {
- grpc_error* error = grpc_error_set_str(
- grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_desc),
- GRPC_ERROR_INT_OFFSET,
- p - GRPC_SLICE_START_PTR(slice)),
+ const char* err_desc) {
+ const uint8_t* p = GRPC_SLICE_START_PTR(slice);
+ const uint8_t* e = GRPC_SLICE_END_PTR(slice);
+ for (; p != e; p++) {
+ int idx = *p;
+ int byte = idx / 8;
+ int bit = idx % 8;
+ if ((legal_bits[byte] & (1 << bit)) == 0) {
+ grpc_error* error = grpc_error_set_str(
+ 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));
- return error;
- }
- }
- return GRPC_ERROR_NONE;
-}
-
-static int error2int(grpc_error* error) {
- int r = (error == GRPC_ERROR_NONE);
- GRPC_ERROR_UNREF(error);
- return r;
-}
-
+ return error;
+ }
+ }
+ return GRPC_ERROR_NONE;
+}
+
+static int error2int(grpc_error* error) {
+ int r = (error == GRPC_ERROR_NONE);
+ GRPC_ERROR_UNREF(error);
+ return r;
+}
+
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,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
- if (GRPC_SLICE_LENGTH(slice) == 0) {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Metadata keys cannot be zero length");
- }
+ 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,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ if (GRPC_SLICE_LENGTH(slice) == 0) {
+ 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_START_PTR(slice)[0] == ':') {
- return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
- "Metadata keys cannot start with :");
- }
- return conforms_to(slice, legal_header_bits, "Illegal header key");
-}
-
-int grpc_header_key_is_legal(grpc_slice slice) {
- return error2int(grpc_validate_header_key_is_legal(slice));
-}
-
+ if (GRPC_SLICE_START_PTR(slice)[0] == ':') {
+ return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
+ "Metadata keys cannot start with :");
+ }
+ return conforms_to(slice, legal_header_bits, "Illegal header key");
+}
+
+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) {
- 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,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
- return conforms_to(slice, legal_header_bits, "Illegal header value");
-}
-
-int grpc_header_nonbin_value_is_legal(grpc_slice slice) {
- return error2int(grpc_validate_header_nonbin_value_is_legal(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,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ return conforms_to(slice, legal_header_bits, "Illegal header value");
+}
+
+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(grpc_slice slice) {
+int grpc_is_binary_header(grpc_slice 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 db3be684c11..87e22f23d7f 100644
--- a/contrib/libs/grpc/src/core/lib/surface/validate_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/surface/validate_metadata.h
@@ -1,32 +1,32 @@
-/*
- *
- * 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_SURFACE_VALIDATE_METADATA_H
-#define GRPC_CORE_LIB_SURFACE_VALIDATE_METADATA_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.h>
-#include "src/core/lib/iomgr/error.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SURFACE_VALIDATE_METADATA_H
+#define GRPC_CORE_LIB_SURFACE_VALIDATE_METADATA_H
+
+#include <grpc/support/port_platform.h>
+
+#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;
@@ -38,4 +38,4 @@ inline int grpc_is_refcounted_slice_binary_header(const grpc_slice& slice) {
slice.data.refcounted.length);
}
-#endif /* GRPC_CORE_LIB_SURFACE_VALIDATE_METADATA_H */
+#endif /* GRPC_CORE_LIB_SURFACE_VALIDATE_METADATA_H */
diff --git a/contrib/libs/grpc/src/core/lib/surface/version.cc b/contrib/libs/grpc/src/core/lib/surface/version.cc
index bed4f427e99..1bc9e06bf89 100644
--- a/contrib/libs/grpc/src/core/lib/surface/version.cc
+++ b/contrib/libs/grpc/src/core/lib/surface/version.cc
@@ -1,28 +1,28 @@
-/*
- *
- * 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.
- *
- */
-
-/* This file is autogenerated from:
- templates/src/core/surface/version.c.template */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.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.
+ *
+ */
+
+/* This file is autogenerated from:
+ templates/src/core/surface/version.c.template */
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+
const char* grpc_version_string(void) { return "13.0.0"; }
-
+
const char* grpc_g_stands_for(void) { return "geeky"; }
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 8835e32bcff..99304931bff 100644
--- a/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.cc
@@ -1,87 +1,87 @@
-/*
- *
- * 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/transport/bdp_estimator.h"
-
-#include <inttypes.h>
-#include <stdlib.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-grpc_core::TraceFlag grpc_bdp_estimator_trace(false, "bdp_estimator");
-
-namespace grpc_core {
-
-BdpEstimator::BdpEstimator(const char* name)
- : ping_state_(PingState::UNSCHEDULED),
- accumulator_(0),
- estimate_(65536),
- ping_start_time_(gpr_time_0(GPR_CLOCK_MONOTONIC)),
- inter_ping_delay_(100.0), // start at 100ms
- stable_estimate_count_(0),
- bw_est_(0),
- name_(name) {}
-
-grpc_millis BdpEstimator::CompletePing() {
- gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
- gpr_timespec dt_ts = gpr_time_sub(now, ping_start_time_);
- double dt = static_cast<double>(dt_ts.tv_sec) +
- 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_;
+/*
+ *
+ * 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/transport/bdp_estimator.h"
+
+#include <inttypes.h>
+#include <stdlib.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+grpc_core::TraceFlag grpc_bdp_estimator_trace(false, "bdp_estimator");
+
+namespace grpc_core {
+
+BdpEstimator::BdpEstimator(const char* name)
+ : ping_state_(PingState::UNSCHEDULED),
+ accumulator_(0),
+ estimate_(65536),
+ ping_start_time_(gpr_time_0(GPR_CLOCK_MONOTONIC)),
+ inter_ping_delay_(100.0), // start at 100ms
+ stable_estimate_count_(0),
+ bw_est_(0),
+ name_(name) {}
+
+grpc_millis BdpEstimator::CompletePing() {
+ gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
+ gpr_timespec dt_ts = gpr_time_sub(now, ping_start_time_);
+ double dt = static_cast<double>(dt_ts.tv_sec) +
+ 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)) {
- gpr_log(GPR_INFO,
- "bdp[%s]:complete acc=%" PRId64 " est=%" PRId64
- " dt=%lf bw=%lfMbs bw_est=%lfMbs",
- name_, accumulator_, estimate_, dt, bw / 125000.0,
- bw_est_ / 125000.0);
- }
- GPR_ASSERT(ping_state_ == PingState::STARTED);
- if (accumulator_ > 2 * estimate_ / 3 && bw > bw_est_) {
- estimate_ = GPR_MAX(accumulator_, estimate_ * 2);
- bw_est_ = bw;
+ gpr_log(GPR_INFO,
+ "bdp[%s]:complete acc=%" PRId64 " est=%" PRId64
+ " dt=%lf bw=%lfMbs bw_est=%lfMbs",
+ name_, accumulator_, estimate_, dt, bw / 125000.0,
+ bw_est_ / 125000.0);
+ }
+ GPR_ASSERT(ping_state_ == PingState::STARTED);
+ 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)) {
- gpr_log(GPR_INFO, "bdp[%s]: estimate increased to %" PRId64, name_,
- estimate_);
- }
- inter_ping_delay_ /= 2; // if the ping estimate changes,
- // exponentially get faster at probing
- } else if (inter_ping_delay_ < 10000) {
- stable_estimate_count_++;
- if (stable_estimate_count_ >= 2) {
- inter_ping_delay_ +=
- 100 + static_cast<int>(rand() * 100.0 /
- RAND_MAX); // if the ping estimate is steady,
- // slowly ramp down the probe time
- }
- }
- if (start_inter_ping_delay != inter_ping_delay_) {
- stable_estimate_count_ = 0;
+ gpr_log(GPR_INFO, "bdp[%s]: estimate increased to %" PRId64, name_,
+ estimate_);
+ }
+ inter_ping_delay_ /= 2; // if the ping estimate changes,
+ // exponentially get faster at probing
+ } else if (inter_ping_delay_ < 10000) {
+ stable_estimate_count_++;
+ if (stable_estimate_count_ >= 2) {
+ inter_ping_delay_ +=
+ 100 + static_cast<int>(rand() * 100.0 /
+ RAND_MAX); // if the ping estimate is steady,
+ // slowly ramp down the probe time
+ }
+ }
+ if (start_inter_ping_delay != inter_ping_delay_) {
+ stable_estimate_count_ = 0;
if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
- gpr_log(GPR_INFO, "bdp[%s]:update_inter_time to %dms", name_,
- inter_ping_delay_);
- }
- }
- ping_state_ = PingState::UNSCHEDULED;
- accumulator_ = 0;
- return grpc_core::ExecCtx::Get()->Now() + inter_ping_delay_;
-}
-
-} // namespace grpc_core
+ gpr_log(GPR_INFO, "bdp[%s]:update_inter_time to %dms", name_,
+ inter_ping_delay_);
+ }
+ }
+ ping_state_ = PingState::UNSCHEDULED;
+ accumulator_ = 0;
+ return grpc_core::ExecCtx::Get()->Now() + inter_ping_delay_;
+}
+
+} // namespace grpc_core
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 7eb336d8bb4..f60fa10ca92 100644
--- a/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h
+++ b/contrib/libs/grpc/src/core/lib/transport/bdp_estimator.h
@@ -1,95 +1,95 @@
-/*
- *
- * 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_TRANSPORT_BDP_ESTIMATOR_H
-#define GRPC_CORE_LIB_TRANSPORT_BDP_ESTIMATOR_H
-
-#include <grpc/support/port_platform.h>
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdint.h>
-
-#include <grpc/support/log.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-
-extern grpc_core::TraceFlag grpc_bdp_estimator_trace;
-
-namespace grpc_core {
-
-class BdpEstimator {
- public:
- explicit BdpEstimator(const char* name);
- ~BdpEstimator() {}
-
- int64_t EstimateBdp() const { return estimate_; }
- double EstimateBandwidth() const { return bw_est_; }
-
- void AddIncomingBytes(int64_t num_bytes) { accumulator_ += num_bytes; }
-
- // Schedule a ping: call in response to receiving a true from
- // grpc_bdp_estimator_add_incoming_bytes once a ping has been scheduled by a
- // transport (but not necessarily started)
- void SchedulePing() {
+/*
+ *
+ * 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_TRANSPORT_BDP_ESTIMATOR_H
+#define GRPC_CORE_LIB_TRANSPORT_BDP_ESTIMATOR_H
+
+#include <grpc/support/port_platform.h>
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdint.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+
+extern grpc_core::TraceFlag grpc_bdp_estimator_trace;
+
+namespace grpc_core {
+
+class BdpEstimator {
+ public:
+ explicit BdpEstimator(const char* name);
+ ~BdpEstimator() {}
+
+ int64_t EstimateBdp() const { return estimate_; }
+ double EstimateBandwidth() const { return bw_est_; }
+
+ void AddIncomingBytes(int64_t num_bytes) { accumulator_ += num_bytes; }
+
+ // Schedule a ping: call in response to receiving a true from
+ // 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)) {
- gpr_log(GPR_INFO, "bdp[%s]:sched acc=%" PRId64 " est=%" PRId64, name_,
- accumulator_, estimate_);
- }
- GPR_ASSERT(ping_state_ == PingState::UNSCHEDULED);
- ping_state_ = PingState::SCHEDULED;
- accumulator_ = 0;
- }
-
- // Start a ping: call after calling grpc_bdp_estimator_schedule_ping and
- // once
- // the ping is on the wire
- void StartPing() {
+ gpr_log(GPR_INFO, "bdp[%s]:sched acc=%" PRId64 " est=%" PRId64, name_,
+ accumulator_, estimate_);
+ }
+ GPR_ASSERT(ping_state_ == PingState::UNSCHEDULED);
+ ping_state_ = PingState::SCHEDULED;
+ accumulator_ = 0;
+ }
+
+ // Start a ping: call after calling grpc_bdp_estimator_schedule_ping and
+ // once
+ // the ping is on the wire
+ void StartPing() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_bdp_estimator_trace)) {
- gpr_log(GPR_INFO, "bdp[%s]:start acc=%" PRId64 " est=%" PRId64, name_,
- accumulator_, estimate_);
- }
- GPR_ASSERT(ping_state_ == PingState::SCHEDULED);
- ping_state_ = PingState::STARTED;
- ping_start_time_ = gpr_now(GPR_CLOCK_MONOTONIC);
- }
-
- // Completes a previously started ping, returns when to schedule the next one
- grpc_millis CompletePing();
-
+ gpr_log(GPR_INFO, "bdp[%s]:start acc=%" PRId64 " est=%" PRId64, name_,
+ accumulator_, estimate_);
+ }
+ GPR_ASSERT(ping_state_ == PingState::SCHEDULED);
+ ping_state_ = PingState::STARTED;
+ ping_start_time_ = gpr_now(GPR_CLOCK_MONOTONIC);
+ }
+
+ // Completes a previously started ping, returns when to schedule the next one
+ grpc_millis CompletePing();
+
int64_t accumulator() { return accumulator_; }
- private:
- enum class PingState { UNSCHEDULED, SCHEDULED, STARTED };
-
- PingState ping_state_;
- int64_t accumulator_;
- int64_t estimate_;
- // when was the current ping started?
- gpr_timespec ping_start_time_;
- int inter_ping_delay_;
- int stable_estimate_count_;
- double bw_est_;
- const char* name_;
-};
-
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_LIB_TRANSPORT_BDP_ESTIMATOR_H */
+ private:
+ enum class PingState { UNSCHEDULED, SCHEDULED, STARTED };
+
+ PingState ping_state_;
+ int64_t accumulator_;
+ int64_t estimate_;
+ // when was the current ping started?
+ gpr_timespec ping_start_time_;
+ int inter_ping_delay_;
+ int stable_estimate_count_;
+ double bw_est_;
+ const char* name_;
+};
+
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_LIB_TRANSPORT_BDP_ESTIMATOR_H */
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 82f34ca1504..5783aa502d3 100644
--- a/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc
@@ -1,158 +1,158 @@
-/*
- *
- * 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/transport/byte_stream.h"
-
-#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-namespace grpc_core {
-
-//
-// SliceBufferByteStream
-//
-
-SliceBufferByteStream::SliceBufferByteStream(grpc_slice_buffer* slice_buffer,
- uint32_t flags)
- : ByteStream(static_cast<uint32_t>(slice_buffer->length), flags) {
- GPR_ASSERT(slice_buffer->length <= UINT32_MAX);
- grpc_slice_buffer_init(&backing_buffer_);
- grpc_slice_buffer_swap(slice_buffer, &backing_buffer_);
-}
-
-SliceBufferByteStream::~SliceBufferByteStream() {}
-
-void SliceBufferByteStream::Orphan() {
+/*
+ *
+ * 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/transport/byte_stream.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+namespace grpc_core {
+
+//
+// SliceBufferByteStream
+//
+
+SliceBufferByteStream::SliceBufferByteStream(grpc_slice_buffer* slice_buffer,
+ uint32_t flags)
+ : ByteStream(static_cast<uint32_t>(slice_buffer->length), flags) {
+ GPR_ASSERT(slice_buffer->length <= UINT32_MAX);
+ grpc_slice_buffer_init(&backing_buffer_);
+ grpc_slice_buffer_swap(slice_buffer, &backing_buffer_);
+}
+
+SliceBufferByteStream::~SliceBufferByteStream() {}
+
+void SliceBufferByteStream::Orphan() {
grpc_slice_buffer_destroy_internal(&backing_buffer_);
- GRPC_ERROR_UNREF(shutdown_error_);
- // Note: We do not actually delete the object here, since
- // SliceBufferByteStream is usually allocated as part of a larger
- // object and has an OrphanablePtr of itself passed down through the
- // filter stack.
-}
-
+ GRPC_ERROR_UNREF(shutdown_error_);
+ // Note: We do not actually delete the object here, since
+ // SliceBufferByteStream is usually allocated as part of a larger
+ // object and has an OrphanablePtr of itself passed down through the
+ // filter stack.
+}
+
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) {
+ return true;
+}
+
+grpc_error* SliceBufferByteStream::Pull(grpc_slice* slice) {
if (GPR_UNLIKELY(shutdown_error_ != GRPC_ERROR_NONE)) {
- return GRPC_ERROR_REF(shutdown_error_);
- }
+ return GRPC_ERROR_REF(shutdown_error_);
+ }
*slice = grpc_slice_buffer_take_first(&backing_buffer_);
- return GRPC_ERROR_NONE;
-}
-
-void SliceBufferByteStream::Shutdown(grpc_error* error) {
- GRPC_ERROR_UNREF(shutdown_error_);
- shutdown_error_ = error;
-}
-
-//
-// ByteStreamCache
-//
-
-ByteStreamCache::ByteStreamCache(OrphanablePtr<ByteStream> underlying_stream)
- : underlying_stream_(std::move(underlying_stream)),
- length_(underlying_stream_->length()),
- flags_(underlying_stream_->flags()) {
- grpc_slice_buffer_init(&cache_buffer_);
-}
-
-ByteStreamCache::~ByteStreamCache() { Destroy(); }
-
-void ByteStreamCache::Destroy() {
- underlying_stream_.reset();
- if (cache_buffer_.length > 0) {
- grpc_slice_buffer_destroy_internal(&cache_buffer_);
- }
-}
-
-//
-// ByteStreamCache::CachingByteStream
-//
-
-ByteStreamCache::CachingByteStream::CachingByteStream(ByteStreamCache* cache)
- : ByteStream(cache->length_, cache->flags_), cache_(cache) {}
-
-ByteStreamCache::CachingByteStream::~CachingByteStream() {}
-
-void ByteStreamCache::CachingByteStream::Orphan() {
- GRPC_ERROR_UNREF(shutdown_error_);
- // Note: We do not actually delete the object here, since
- // CachingByteStream is usually allocated as part of a larger
- // object and has an OrphanablePtr of itself passed down through the
- // filter stack.
-}
-
-bool ByteStreamCache::CachingByteStream::Next(size_t max_size_hint,
- grpc_closure* on_complete) {
- if (shutdown_error_ != GRPC_ERROR_NONE) return true;
- if (cursor_ < cache_->cache_buffer_.count) return true;
- GPR_ASSERT(cache_->underlying_stream_ != nullptr);
- return cache_->underlying_stream_->Next(max_size_hint, on_complete);
-}
-
-grpc_error* ByteStreamCache::CachingByteStream::Pull(grpc_slice* slice) {
- if (shutdown_error_ != GRPC_ERROR_NONE) {
- return GRPC_ERROR_REF(shutdown_error_);
- }
- if (cursor_ < cache_->cache_buffer_.count) {
- *slice = grpc_slice_ref_internal(cache_->cache_buffer_.slices[cursor_]);
- ++cursor_;
- offset_ += GRPC_SLICE_LENGTH(*slice);
- return GRPC_ERROR_NONE;
- }
- GPR_ASSERT(cache_->underlying_stream_ != nullptr);
- grpc_error* error = cache_->underlying_stream_->Pull(slice);
- if (error == GRPC_ERROR_NONE) {
- grpc_slice_buffer_add(&cache_->cache_buffer_,
- grpc_slice_ref_internal(*slice));
- ++cursor_;
- offset_ += GRPC_SLICE_LENGTH(*slice);
- // Orphan the underlying stream if it's been drained.
- if (offset_ == cache_->underlying_stream_->length()) {
- cache_->underlying_stream_.reset();
- }
- }
- return error;
-}
-
-void ByteStreamCache::CachingByteStream::Shutdown(grpc_error* error) {
- GRPC_ERROR_UNREF(shutdown_error_);
- shutdown_error_ = GRPC_ERROR_REF(error);
- if (cache_->underlying_stream_ != nullptr) {
- cache_->underlying_stream_->Shutdown(error);
- }
-}
-
-void ByteStreamCache::CachingByteStream::Reset() {
- cursor_ = 0;
- offset_ = 0;
-}
-
-} // namespace grpc_core
+ return GRPC_ERROR_NONE;
+}
+
+void SliceBufferByteStream::Shutdown(grpc_error* error) {
+ GRPC_ERROR_UNREF(shutdown_error_);
+ shutdown_error_ = error;
+}
+
+//
+// ByteStreamCache
+//
+
+ByteStreamCache::ByteStreamCache(OrphanablePtr<ByteStream> underlying_stream)
+ : underlying_stream_(std::move(underlying_stream)),
+ length_(underlying_stream_->length()),
+ flags_(underlying_stream_->flags()) {
+ grpc_slice_buffer_init(&cache_buffer_);
+}
+
+ByteStreamCache::~ByteStreamCache() { Destroy(); }
+
+void ByteStreamCache::Destroy() {
+ underlying_stream_.reset();
+ if (cache_buffer_.length > 0) {
+ grpc_slice_buffer_destroy_internal(&cache_buffer_);
+ }
+}
+
+//
+// ByteStreamCache::CachingByteStream
+//
+
+ByteStreamCache::CachingByteStream::CachingByteStream(ByteStreamCache* cache)
+ : ByteStream(cache->length_, cache->flags_), cache_(cache) {}
+
+ByteStreamCache::CachingByteStream::~CachingByteStream() {}
+
+void ByteStreamCache::CachingByteStream::Orphan() {
+ GRPC_ERROR_UNREF(shutdown_error_);
+ // Note: We do not actually delete the object here, since
+ // CachingByteStream is usually allocated as part of a larger
+ // object and has an OrphanablePtr of itself passed down through the
+ // filter stack.
+}
+
+bool ByteStreamCache::CachingByteStream::Next(size_t max_size_hint,
+ grpc_closure* on_complete) {
+ if (shutdown_error_ != GRPC_ERROR_NONE) return true;
+ if (cursor_ < cache_->cache_buffer_.count) return true;
+ GPR_ASSERT(cache_->underlying_stream_ != nullptr);
+ return cache_->underlying_stream_->Next(max_size_hint, on_complete);
+}
+
+grpc_error* ByteStreamCache::CachingByteStream::Pull(grpc_slice* slice) {
+ if (shutdown_error_ != GRPC_ERROR_NONE) {
+ return GRPC_ERROR_REF(shutdown_error_);
+ }
+ if (cursor_ < cache_->cache_buffer_.count) {
+ *slice = grpc_slice_ref_internal(cache_->cache_buffer_.slices[cursor_]);
+ ++cursor_;
+ offset_ += GRPC_SLICE_LENGTH(*slice);
+ return GRPC_ERROR_NONE;
+ }
+ GPR_ASSERT(cache_->underlying_stream_ != nullptr);
+ grpc_error* error = cache_->underlying_stream_->Pull(slice);
+ if (error == GRPC_ERROR_NONE) {
+ grpc_slice_buffer_add(&cache_->cache_buffer_,
+ grpc_slice_ref_internal(*slice));
+ ++cursor_;
+ offset_ += GRPC_SLICE_LENGTH(*slice);
+ // Orphan the underlying stream if it's been drained.
+ if (offset_ == cache_->underlying_stream_->length()) {
+ cache_->underlying_stream_.reset();
+ }
+ }
+ return error;
+}
+
+void ByteStreamCache::CachingByteStream::Shutdown(grpc_error* error) {
+ GRPC_ERROR_UNREF(shutdown_error_);
+ shutdown_error_ = GRPC_ERROR_REF(error);
+ if (cache_->underlying_stream_ != nullptr) {
+ cache_->underlying_stream_->Shutdown(error);
+ }
+}
+
+void ByteStreamCache::CachingByteStream::Reset() {
+ cursor_ = 0;
+ offset_ = 0;
+}
+
+} // namespace grpc_core
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 ecb605ad9bb..740fd6d51d5 100644
--- a/contrib/libs/grpc/src/core/lib/transport/byte_stream.h
+++ b/contrib/libs/grpc/src/core/lib/transport/byte_stream.h
@@ -1,29 +1,29 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_BYTE_STREAM_H
#define GRPC_CORE_LIB_TRANSPORT_BYTE_STREAM_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/slice_buffer.h>
-#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/iomgr/closure.h"
+#include "src/core/lib/gprpp/orphanable.h"
+#include "src/core/lib/iomgr/closure.h"
/** Internal bit flag for grpc_begin_message's \a flags signaling the use of
* compression for the message. (Does not apply for stream compression.) */
@@ -36,130 +36,130 @@
#define GRPC_WRITE_INTERNAL_USED_MASK \
(GRPC_WRITE_INTERNAL_COMPRESS | GRPC_WRITE_INTERNAL_TEST_ONLY_WAS_COMPRESSED)
-namespace grpc_core {
-
-class ByteStream : public Orphanable {
- public:
- virtual ~ByteStream() {}
+namespace grpc_core {
- // 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
+class ByteStream : public Orphanable {
+ public:
+ virtual ~ByteStream() {}
+
+ // 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.
- //
- // max_size_hint can be set as a hint as to the maximum number
- // of bytes that would be acceptable to read.
+ //
+ // 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;
-
- // 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.
+
+ // 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;
-
- // Shuts down the byte stream.
- //
- // If there is a pending call to on_complete from Next(), it will be
- // invoked with the error passed to Shutdown().
- //
- // The next call to Pull() (if any) will return the error passed to
- // Shutdown().
+
+ // Shuts down the byte stream.
+ //
+ // If there is a pending call to on_complete from Next(), it will be
+ // invoked with the error passed to Shutdown().
+ //
+ // The next call to Pull() (if any) will return the error passed to
+ // Shutdown().
virtual void Shutdown(grpc_error* error) = 0;
-
- uint32_t length() const { return length_; }
- uint32_t flags() const { return flags_; }
-
- void set_flags(uint32_t flags) { flags_ = flags; }
-
- protected:
- ByteStream(uint32_t length, uint32_t flags)
- : length_(length), flags_(flags) {}
-
- private:
- const uint32_t length_;
- uint32_t flags_;
+
+ uint32_t length() const { return length_; }
+ uint32_t flags() const { return flags_; }
+
+ void set_flags(uint32_t flags) { flags_ = flags; }
+
+ protected:
+ ByteStream(uint32_t length, uint32_t flags)
+ : length_(length), flags_(flags) {}
+
+ private:
+ const uint32_t length_;
+ uint32_t flags_;
};
-//
-// SliceBufferByteStream
-//
-// A ByteStream that wraps a slice buffer.
-//
-
-class SliceBufferByteStream : public ByteStream {
- public:
- // Removes all slices in slice_buffer, leaving it empty.
- SliceBufferByteStream(grpc_slice_buffer* slice_buffer, uint32_t flags);
+//
+// SliceBufferByteStream
+//
+// A ByteStream that wraps a slice buffer.
+//
- ~SliceBufferByteStream();
+class SliceBufferByteStream : public ByteStream {
+ public:
+ // Removes all slices in slice_buffer, leaving it empty.
+ SliceBufferByteStream(grpc_slice_buffer* slice_buffer, uint32_t flags);
- void Orphan() override;
+ ~SliceBufferByteStream();
- bool Next(size_t max_size_hint, grpc_closure* on_complete) override;
- grpc_error* Pull(grpc_slice* slice) override;
- void Shutdown(grpc_error* error) override;
+ void Orphan() override;
- private:
+ bool Next(size_t max_size_hint, grpc_closure* on_complete) override;
+ grpc_error* Pull(grpc_slice* slice) override;
+ void Shutdown(grpc_error* error) override;
+
+ private:
grpc_error* shutdown_error_ = GRPC_ERROR_NONE;
- grpc_slice_buffer backing_buffer_;
-};
-
-//
-// CachingByteStream
-//
-// A ByteStream that that wraps an underlying byte stream but caches
-// the resulting slices in a slice buffer. If an initial attempt fails
-// without fully draining the underlying stream, a new caching stream
-// can be created from the same underlying cache, in which case it will
-// return whatever is in the backing buffer before continuing to read the
-// underlying stream.
-//
-// NOTE: No synchronization is done, so it is not safe to have multiple
-// CachingByteStreams simultaneously drawing from the same underlying
-// ByteStreamCache at the same time.
-//
-
-class ByteStreamCache {
- public:
- class CachingByteStream : public ByteStream {
- public:
- explicit CachingByteStream(ByteStreamCache* cache);
-
- ~CachingByteStream();
-
- void Orphan() override;
-
- bool Next(size_t max_size_hint, grpc_closure* on_complete) override;
- grpc_error* Pull(grpc_slice* slice) override;
- void Shutdown(grpc_error* error) override;
-
- // Resets the byte stream to the start of the underlying stream.
- void Reset();
-
- private:
- ByteStreamCache* cache_;
- size_t cursor_ = 0;
- size_t offset_ = 0;
- grpc_error* shutdown_error_ = GRPC_ERROR_NONE;
- };
-
- explicit ByteStreamCache(OrphanablePtr<ByteStream> underlying_stream);
-
- ~ByteStreamCache();
-
- // Must not be destroyed while still in use by a CachingByteStream.
- void Destroy();
-
- grpc_slice_buffer* cache_buffer() { return &cache_buffer_; }
-
- private:
- OrphanablePtr<ByteStream> underlying_stream_;
- uint32_t length_;
- uint32_t flags_;
- grpc_slice_buffer cache_buffer_;
-};
-
-} // namespace grpc_core
-
+ grpc_slice_buffer backing_buffer_;
+};
+
+//
+// CachingByteStream
+//
+// A ByteStream that that wraps an underlying byte stream but caches
+// the resulting slices in a slice buffer. If an initial attempt fails
+// without fully draining the underlying stream, a new caching stream
+// can be created from the same underlying cache, in which case it will
+// return whatever is in the backing buffer before continuing to read the
+// underlying stream.
+//
+// NOTE: No synchronization is done, so it is not safe to have multiple
+// CachingByteStreams simultaneously drawing from the same underlying
+// ByteStreamCache at the same time.
+//
+
+class ByteStreamCache {
+ public:
+ class CachingByteStream : public ByteStream {
+ public:
+ explicit CachingByteStream(ByteStreamCache* cache);
+
+ ~CachingByteStream();
+
+ void Orphan() override;
+
+ bool Next(size_t max_size_hint, grpc_closure* on_complete) override;
+ grpc_error* Pull(grpc_slice* slice) override;
+ void Shutdown(grpc_error* error) override;
+
+ // Resets the byte stream to the start of the underlying stream.
+ void Reset();
+
+ private:
+ ByteStreamCache* cache_;
+ size_t cursor_ = 0;
+ size_t offset_ = 0;
+ grpc_error* shutdown_error_ = GRPC_ERROR_NONE;
+ };
+
+ explicit ByteStreamCache(OrphanablePtr<ByteStream> underlying_stream);
+
+ ~ByteStreamCache();
+
+ // Must not be destroyed while still in use by a CachingByteStream.
+ void Destroy();
+
+ grpc_slice_buffer* cache_buffer() { return &cache_buffer_; }
+
+ private:
+ OrphanablePtr<ByteStream> underlying_stream_;
+ uint32_t length_;
+ uint32_t flags_;
+ grpc_slice_buffer cache_buffer_;
+};
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_LIB_TRANSPORT_BYTE_STREAM_H */
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 7b130490177..58b916bc284 100644
--- a/contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/connectivity_state.cc
@@ -1,58 +1,58 @@
-/*
- *
- * 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/transport/connectivity_state.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_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.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/transport/connectivity_state.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#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) {
- switch (state) {
- case GRPC_CHANNEL_IDLE:
- return "IDLE";
- case GRPC_CHANNEL_CONNECTING:
- return "CONNECTING";
- case GRPC_CHANNEL_READY:
- return "READY";
- case GRPC_CHANNEL_TRANSIENT_FAILURE:
- return "TRANSIENT_FAILURE";
- case GRPC_CHANNEL_SHUTDOWN:
- return "SHUTDOWN";
- }
- GPR_UNREACHABLE_CODE(return "UNKNOWN");
-}
-
+ switch (state) {
+ case GRPC_CHANNEL_IDLE:
+ return "IDLE";
+ case GRPC_CHANNEL_CONNECTING:
+ return "CONNECTING";
+ case GRPC_CHANNEL_READY:
+ return "READY";
+ case GRPC_CHANNEL_TRANSIENT_FAILURE:
+ return "TRANSIENT_FAILURE";
+ case GRPC_CHANNEL_SHUTDOWN:
+ return "SHUTDOWN";
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
+
//
// AsyncConnectivityStateWatcherInterface
//
-
+
// A fire-and-forget class to asynchronously deliver a connectivity
// state notification to a watcher.
class AsyncConnectivityStateWatcherInterface::Notifier {
@@ -65,12 +65,12 @@ class AsyncConnectivityStateWatcherInterface::Notifier {
work_serializer->Run(
[this]() { SendNotification(this, GRPC_ERROR_NONE); },
DEBUG_LOCATION);
- } else {
+ } else {
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*/) {
@@ -94,8 +94,8 @@ void AsyncConnectivityStateWatcherInterface::Notify(
grpc_connectivity_state state, const y_absl::Status& status) {
new Notifier(Ref(), state, status,
work_serializer_); // Deletes itself when done.
-}
-
+}
+
//
// ConnectivityStateTracker
//
@@ -111,16 +111,16 @@ ConnectivityStateTracker::~ConnectivityStateTracker() {
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());
- }
+ }
grpc_connectivity_state current_state = state_.Load(MemoryOrder::RELAXED);
if (initial_state != current_state) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
@@ -130,14 +130,14 @@ void ConnectivityStateTracker::AddWatcher(
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)));
}
-}
-
+}
+
void ConnectivityStateTracker::RemoveWatcher(
ConnectivityStateWatcherInterface* watcher) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_connectivity_state_trace)) {
@@ -145,8 +145,8 @@ void ConnectivityStateTracker::RemoveWatcher(
name_, this, watcher);
}
watchers_.erase(watcher);
-}
-
+}
+
void ConnectivityStateTracker::SetState(grpc_connectivity_state state,
const y_absl::Status& status,
const char* reason) {
@@ -156,7 +156,7 @@ void ConnectivityStateTracker::SetState(grpc_connectivity_state state,
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);
status_ = status;
for (const auto& p : watchers_) {
@@ -165,21 +165,21 @@ void ConnectivityStateTracker::SetState(grpc_connectivity_state state,
"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();
-}
-
+}
+
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;
-}
+}
} // 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 9e34c646c76..fb00b69b6a8 100644
--- a/contrib/libs/grpc/src/core/lib/transport/connectivity_state.h
+++ b/contrib/libs/grpc/src/core/lib/transport/connectivity_state.h
@@ -1,35 +1,35 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_CONNECTIVITY_STATE_H
#define GRPC_CORE_LIB_TRANSPORT_CONNECTIVITY_STATE_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "y_absl/status/status.h"
#include <grpc/grpc.h>
-#include "src/core/lib/debug/trace.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/iomgr/closure.h"
+#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/work_serializer.h"
@@ -72,7 +72,7 @@ class AsyncConnectivityStateWatcherInterface
protected:
class Notifier;
-
+
// If \a work_serializer is nullptr, then the notification will be scheduled
// on the ExecCtx.
explicit AsyncConnectivityStateWatcherInterface(
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 9634f09ad1e..c46a9533789 100644
--- a/contrib/libs/grpc/src/core/lib/transport/error_utils.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/error_utils.cc
@@ -1,54 +1,54 @@
-/*
- *
- * 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/transport/error_utils.h"
-
-#include <grpc/support/string_util.h>
-#include "src/core/lib/iomgr/error_internal.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/transport/error_utils.h"
+
+#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/transport/status_conversion.h"
-
-static grpc_error* recursively_find_error_with_field(grpc_error* error,
- grpc_error_ints which) {
+#include "src/core/lib/transport/status_conversion.h"
+
+static grpc_error* recursively_find_error_with_field(grpc_error* error,
+ grpc_error_ints which) {
intptr_t unused;
- // If the error itself has a status code, return it.
+ // If the error itself has a status code, return it.
if (grpc_error_get_int(error, which, &unused)) {
- return error;
- }
- if (grpc_error_is_special(error)) return nullptr;
- // Otherwise, search through its children.
- uint8_t slot = error->first_err;
- while (slot != UINT8_MAX) {
- grpc_linked_error* lerr =
- reinterpret_cast<grpc_linked_error*>(error->arena + slot);
- grpc_error* result = recursively_find_error_with_field(lerr->err, which);
- if (result) return result;
- slot = lerr->next;
- }
- return nullptr;
-}
-
-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) {
+ return error;
+ }
+ if (grpc_error_is_special(error)) return nullptr;
+ // Otherwise, search through its children.
+ uint8_t slot = error->first_err;
+ while (slot != UINT8_MAX) {
+ grpc_linked_error* lerr =
+ reinterpret_cast<grpc_linked_error*>(error->arena + slot);
+ grpc_error* result = recursively_find_error_with_field(lerr->err, which);
+ if (result) return result;
+ slot = lerr->next;
+ }
+ return nullptr;
+}
+
+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;
@@ -69,60 +69,60 @@ void grpc_error_get_status(grpc_error* error, grpc_millis deadline,
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 =
- recursively_find_error_with_field(error, GRPC_ERROR_INT_GRPC_STATUS);
- if (found_error == nullptr) {
- /// If no grpc-status exists, retry through the tree to find a http2 error
- /// code
- found_error =
- recursively_find_error_with_field(error, GRPC_ERROR_INT_HTTP2_ERROR);
- }
-
- // If we found an error with a status code above, use that; otherwise,
- // fall back to using the parent error.
- if (found_error == nullptr) found_error = error;
-
- grpc_status_code status = GRPC_STATUS_UNKNOWN;
- intptr_t integer;
- if (grpc_error_get_int(found_error, GRPC_ERROR_INT_GRPC_STATUS, &integer)) {
- status = static_cast<grpc_status_code>(integer);
- } else if (grpc_error_get_int(found_error, GRPC_ERROR_INT_HTTP2_ERROR,
- &integer)) {
- status = grpc_http2_error_to_grpc_status(
- static_cast<grpc_http2_error_code>(integer), deadline);
- }
- if (code != nullptr) *code = status;
-
- if (error_string != nullptr && status != GRPC_STATUS_OK) {
- *error_string = gpr_strdup(grpc_error_string(error));
- }
-
- if (http_error != nullptr) {
- if (grpc_error_get_int(found_error, GRPC_ERROR_INT_HTTP2_ERROR, &integer)) {
- *http_error = static_cast<grpc_http2_error_code>(integer);
- } else if (grpc_error_get_int(found_error, GRPC_ERROR_INT_GRPC_STATUS,
- &integer)) {
- *http_error =
- grpc_status_to_http2_error(static_cast<grpc_status_code>(integer));
- } else {
- *http_error = found_error == GRPC_ERROR_NONE ? GRPC_HTTP2_NO_ERROR
- : GRPC_HTTP2_INTERNAL_ERROR;
- }
- }
-
- // If the error has a status message, use it. Otherwise, fall back to
- // the error description.
- if (slice != nullptr) {
- if (!grpc_error_get_str(found_error, GRPC_ERROR_STR_GRPC_MESSAGE, slice)) {
- if (!grpc_error_get_str(found_error, GRPC_ERROR_STR_DESCRIPTION, slice)) {
- *slice = grpc_slice_from_static_string("unknown error");
- }
- }
- }
-}
-
+ // 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 =
+ recursively_find_error_with_field(error, GRPC_ERROR_INT_GRPC_STATUS);
+ if (found_error == nullptr) {
+ /// If no grpc-status exists, retry through the tree to find a http2 error
+ /// code
+ found_error =
+ recursively_find_error_with_field(error, GRPC_ERROR_INT_HTTP2_ERROR);
+ }
+
+ // If we found an error with a status code above, use that; otherwise,
+ // fall back to using the parent error.
+ if (found_error == nullptr) found_error = error;
+
+ grpc_status_code status = GRPC_STATUS_UNKNOWN;
+ intptr_t integer;
+ if (grpc_error_get_int(found_error, GRPC_ERROR_INT_GRPC_STATUS, &integer)) {
+ status = static_cast<grpc_status_code>(integer);
+ } else if (grpc_error_get_int(found_error, GRPC_ERROR_INT_HTTP2_ERROR,
+ &integer)) {
+ status = grpc_http2_error_to_grpc_status(
+ static_cast<grpc_http2_error_code>(integer), deadline);
+ }
+ if (code != nullptr) *code = status;
+
+ if (error_string != nullptr && status != GRPC_STATUS_OK) {
+ *error_string = gpr_strdup(grpc_error_string(error));
+ }
+
+ if (http_error != nullptr) {
+ if (grpc_error_get_int(found_error, GRPC_ERROR_INT_HTTP2_ERROR, &integer)) {
+ *http_error = static_cast<grpc_http2_error_code>(integer);
+ } else if (grpc_error_get_int(found_error, GRPC_ERROR_INT_GRPC_STATUS,
+ &integer)) {
+ *http_error =
+ grpc_status_to_http2_error(static_cast<grpc_status_code>(integer));
+ } else {
+ *http_error = found_error == GRPC_ERROR_NONE ? GRPC_HTTP2_NO_ERROR
+ : GRPC_HTTP2_INTERNAL_ERROR;
+ }
+ }
+
+ // If the error has a status message, use it. Otherwise, fall back to
+ // the error description.
+ if (slice != nullptr) {
+ if (!grpc_error_get_str(found_error, GRPC_ERROR_STR_GRPC_MESSAGE, slice)) {
+ if (!grpc_error_get_str(found_error, GRPC_ERROR_STR_DESCRIPTION, slice)) {
+ *slice = grpc_slice_from_static_string("unknown error");
+ }
+ }
+ }
+}
+
y_absl::Status grpc_error_to_absl_status(grpc_error* error) {
grpc_status_code status;
// TODO(yashykt): This should be updated once we decide on how to use the
@@ -136,19 +136,19 @@ y_absl::Status grpc_error_to_absl_status(grpc_error* error) {
GRPC_SLICE_LENGTH(message)));
}
-bool grpc_error_has_clear_grpc_status(grpc_error* error) {
+bool grpc_error_has_clear_grpc_status(grpc_error* error) {
intptr_t unused;
if (grpc_error_get_int(error, GRPC_ERROR_INT_GRPC_STATUS, &unused)) {
- return true;
- }
- uint8_t slot = error->first_err;
- while (slot != UINT8_MAX) {
- grpc_linked_error* lerr =
- reinterpret_cast<grpc_linked_error*>(error->arena + slot);
- if (grpc_error_has_clear_grpc_status(lerr->err)) {
- return true;
- }
- slot = lerr->next;
- }
- return false;
-}
+ return true;
+ }
+ uint8_t slot = error->first_err;
+ while (slot != UINT8_MAX) {
+ grpc_linked_error* lerr =
+ reinterpret_cast<grpc_linked_error*>(error->arena + slot);
+ if (grpc_error_has_clear_grpc_status(lerr->err)) {
+ return true;
+ }
+ slot = lerr->next;
+ }
+ return false;
+}
diff --git a/contrib/libs/grpc/src/core/lib/transport/error_utils.h b/contrib/libs/grpc/src/core/lib/transport/error_utils.h
index fb967202f32..ab76e37f5e2 100644
--- a/contrib/libs/grpc/src/core/lib/transport/error_utils.h
+++ b/contrib/libs/grpc/src/core/lib/transport/error_utils.h
@@ -1,52 +1,52 @@
-/*
- *
- * 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_TRANSPORT_ERROR_UTILS_H
-#define GRPC_CORE_LIB_TRANSPORT_ERROR_UTILS_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_LIB_TRANSPORT_ERROR_UTILS_H
+#define GRPC_CORE_LIB_TRANSPORT_ERROR_UTILS_H
+
+#include <grpc/support/port_platform.h>
+
#include "y_absl/status/status.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/transport/http2_errors.h"
-
-/// A utility function to get the status code and message to be returned
-/// to the application. If not set in the top-level message, looks
-/// through child errors until it finds the first one with these attributes.
-/// All attributes are pulled from the same child error. error_string will
-/// be populated with the entire error string. If any of the attributes (code,
-/// msg, http_status, error_string) are unneeded, they can be passed as
-/// NULL.
-void grpc_error_get_status(grpc_error* error, grpc_millis deadline,
- grpc_status_code* code, grpc_slice* slice,
- grpc_http2_error_code* http_status,
- const char** error_string);
-
+#include "src/core/lib/iomgr/error.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/transport/http2_errors.h"
+
+/// A utility function to get the status code and message to be returned
+/// to the application. If not set in the top-level message, looks
+/// through child errors until it finds the first one with these attributes.
+/// All attributes are pulled from the same child error. error_string will
+/// be populated with the entire error string. If any of the attributes (code,
+/// msg, http_status, error_string) are unneeded, they can be passed as
+/// NULL.
+void grpc_error_get_status(grpc_error* error, grpc_millis deadline,
+ grpc_status_code* code, grpc_slice* slice,
+ grpc_http2_error_code* http_status,
+ const char** error_string);
+
/// Utility Function to convert a grpc_error * \a error to an y_absl::Status.
/// Does NOT consume a ref to grpc_error.
y_absl::Status grpc_error_to_absl_status(grpc_error* error);
-/// A utility function to check whether there is a clear status code that
-/// doesn't need to be guessed in \a error. This means that \a error or some
-/// child has GRPC_ERROR_INT_GRPC_STATUS set, or that it is GRPC_ERROR_NONE or
-/// GRPC_ERROR_CANCELLED
-bool grpc_error_has_clear_grpc_status(grpc_error* error);
-
-#endif /* GRPC_CORE_LIB_TRANSPORT_ERROR_UTILS_H */
+/// A utility function to check whether there is a clear status code that
+/// doesn't need to be guessed in \a error. This means that \a error or some
+/// child has GRPC_ERROR_INT_GRPC_STATUS set, or that it is GRPC_ERROR_NONE or
+/// GRPC_ERROR_CANCELLED
+bool grpc_error_has_clear_grpc_status(grpc_error* error);
+
+#endif /* GRPC_CORE_LIB_TRANSPORT_ERROR_UTILS_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/http2_errors.h b/contrib/libs/grpc/src/core/lib/transport/http2_errors.h
index d412c5dffc7..1bfc97442d5 100644
--- a/contrib/libs/grpc/src/core/lib/transport/http2_errors.h
+++ b/contrib/libs/grpc/src/core/lib/transport/http2_errors.h
@@ -1,41 +1,41 @@
-/*
- *
- * 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_TRANSPORT_HTTP2_ERRORS_H
-#define GRPC_CORE_LIB_TRANSPORT_HTTP2_ERRORS_H
-
-/* error codes for RST_STREAM from http2 draft 14 section 7 */
-typedef enum {
- GRPC_HTTP2_NO_ERROR = 0x0,
- GRPC_HTTP2_PROTOCOL_ERROR = 0x1,
- GRPC_HTTP2_INTERNAL_ERROR = 0x2,
- GRPC_HTTP2_FLOW_CONTROL_ERROR = 0x3,
- GRPC_HTTP2_SETTINGS_TIMEOUT = 0x4,
- GRPC_HTTP2_STREAM_CLOSED = 0x5,
- GRPC_HTTP2_FRAME_SIZE_ERROR = 0x6,
- GRPC_HTTP2_REFUSED_STREAM = 0x7,
- GRPC_HTTP2_CANCEL = 0x8,
- GRPC_HTTP2_COMPRESSION_ERROR = 0x9,
- GRPC_HTTP2_CONNECT_ERROR = 0xa,
- GRPC_HTTP2_ENHANCE_YOUR_CALM = 0xb,
- GRPC_HTTP2_INADEQUATE_SECURITY = 0xc,
- /* force use of a default clause */
- GRPC_HTTP2__ERROR_DO_NOT_USE = -1
-} grpc_http2_error_code;
-
-#endif /* GRPC_CORE_LIB_TRANSPORT_HTTP2_ERRORS_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_TRANSPORT_HTTP2_ERRORS_H
+#define GRPC_CORE_LIB_TRANSPORT_HTTP2_ERRORS_H
+
+/* error codes for RST_STREAM from http2 draft 14 section 7 */
+typedef enum {
+ GRPC_HTTP2_NO_ERROR = 0x0,
+ GRPC_HTTP2_PROTOCOL_ERROR = 0x1,
+ GRPC_HTTP2_INTERNAL_ERROR = 0x2,
+ GRPC_HTTP2_FLOW_CONTROL_ERROR = 0x3,
+ GRPC_HTTP2_SETTINGS_TIMEOUT = 0x4,
+ GRPC_HTTP2_STREAM_CLOSED = 0x5,
+ GRPC_HTTP2_FRAME_SIZE_ERROR = 0x6,
+ GRPC_HTTP2_REFUSED_STREAM = 0x7,
+ GRPC_HTTP2_CANCEL = 0x8,
+ GRPC_HTTP2_COMPRESSION_ERROR = 0x9,
+ GRPC_HTTP2_CONNECT_ERROR = 0xa,
+ GRPC_HTTP2_ENHANCE_YOUR_CALM = 0xb,
+ GRPC_HTTP2_INADEQUATE_SECURITY = 0xc,
+ /* force use of a default clause */
+ GRPC_HTTP2__ERROR_DO_NOT_USE = -1
+} grpc_http2_error_code;
+
+#endif /* GRPC_CORE_LIB_TRANSPORT_HTTP2_ERRORS_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata.cc b/contrib/libs/grpc/src/core/lib/transport/metadata.cc
index 33d4d5ac705..35e9476350f 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata.cc
@@ -1,64 +1,64 @@
-/*
- *
- * 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/transport/metadata.h"
-
-#include <assert.h>
-#include <inttypes.h>
-#include <stddef.h>
-#include <string.h>
-
-#include <grpc/compression.h>
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/gpr/murmur_hash.h"
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/iomgr/iomgr_internal.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/transport/static_metadata.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/transport/metadata.h"
+
+#include <assert.h>
+#include <inttypes.h>
+#include <stddef.h>
+#include <string.h>
+
+#include <grpc/compression.h>
+#include <grpc/grpc.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/gpr/murmur_hash.h"
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/iomgr/iomgr_internal.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/transport/static_metadata.h"
+
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().
- * Dynamic instances are stored in hash tables on grpc_mdctx, and are backed
- * by internal_string and internal_element structures.
- * Internal helper functions here-in (is_mdstr_static, is_mdelem_static) are
- * used to determine which kind of element a pointer refers to.
- */
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_metadata(false, "metadata");
-
-#ifndef NDEBUG
-#define DEBUG_ARGS , const char *file, int line
+/* 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().
+ * Dynamic instances are stored in hash tables on grpc_mdctx, and are backed
+ * by internal_string and internal_element structures.
+ * Internal helper functions here-in (is_mdstr_static, is_mdelem_static) are
+ * used to determine which kind of element a pointer refers to.
+ */
+
+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,
@@ -90,23 +90,23 @@ void grpc_mdelem_trace_unref(void* md, const grpc_slice& key,
}
#else // ifndef NDEBUG
-#define DEBUG_ARGS
-#define FWD_DEBUG_ARGS
+#define DEBUG_ARGS
+#define FWD_DEBUG_ARGS
#endif // ifndef NDEBUG
-
-#define INITIAL_SHARD_CAPACITY 8
-#define LOG2_SHARD_COUNT 4
-#define SHARD_COUNT ((size_t)(1 << LOG2_SHARD_COUNT))
-
-#define TABLE_IDX(hash, capacity) (((hash) >> (LOG2_SHARD_COUNT)) % (capacity))
-#define SHARD_IDX(hash) ((hash) & ((1 << (LOG2_SHARD_COUNT)) - 1))
-
+
+#define INITIAL_SHARD_CAPACITY 8
+#define LOG2_SHARD_COUNT 4
+#define SHARD_COUNT ((size_t)(1 << LOG2_SHARD_COUNT))
+
+#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),
@@ -115,7 +115,7 @@ AllocatedMetadata::AllocatedMetadata(const grpc_slice& key,
TraceAtStart("ALLOC_MD");
#endif
}
-
+
AllocatedMetadata::AllocatedMetadata(const grpc_slice& key,
const grpc_slice& value, const NoRefKey*)
: RefcountedMdBase(key, grpc_slice_ref_internal(value)) {
@@ -123,7 +123,7 @@ AllocatedMetadata::AllocatedMetadata(const grpc_slice& key,
TraceAtStart("ALLOC_MD_NOREF_KEY");
#endif
}
-
+
AllocatedMetadata::AllocatedMetadata(
const grpc_core::ManagedMemorySlice& key,
const grpc_core::UnmanagedMemorySlice& value)
@@ -132,7 +132,7 @@ AllocatedMetadata::AllocatedMetadata(
TraceAtStart("ALLOC_MD_NOREF_KEY_VAL");
#endif
}
-
+
AllocatedMetadata::AllocatedMetadata(
const grpc_core::ExternallyManagedSlice& key,
const grpc_core::UnmanagedMemorySlice& value)
@@ -141,7 +141,7 @@ AllocatedMetadata::AllocatedMetadata(
TraceAtStart("ALLOC_MD_NOREF_KEY_VAL");
#endif
}
-
+
AllocatedMetadata::~AllocatedMetadata() {
grpc_slice_unref_internal(key());
grpc_slice_unref_internal(value());
@@ -152,7 +152,7 @@ AllocatedMetadata::~AllocatedMetadata() {
destroy_user_data(user_data);
}
}
-
+
#ifndef NDEBUG
void grpc_core::RefcountedMdBase::TraceAtStart(const char* tag) {
if (grpc_trace_metadata.enabled()) {
@@ -165,7 +165,7 @@ void grpc_core::RefcountedMdBase::TraceAtStart(const char* tag) {
}
}
#endif
-
+
InternedMetadata::InternedMetadata(const grpc_slice& key,
const grpc_slice& value, uint32_t hash,
InternedMetadata* next)
@@ -216,42 +216,42 @@ size_t InternedMetadata::CleanupLinkedMetadata(
return num_freed;
}
-typedef struct mdtab_shard {
- gpr_mu mu;
+typedef struct mdtab_shard {
+ gpr_mu mu;
InternedMetadata::BucketLink* elems;
- size_t count;
- size_t capacity;
- /** Estimate of the number of unreferenced mdelems in the hash table.
- This will eventually converge to the exact number, but it's instantaneous
- accuracy is not guaranteed */
- gpr_atm free_estimate;
-} mdtab_shard;
-
-static mdtab_shard g_shards[SHARD_COUNT];
-
-static void gc_mdtab(mdtab_shard* shard);
-
-void grpc_mdctx_global_init(void) {
- /* initialize shards */
- for (size_t i = 0; i < SHARD_COUNT; i++) {
- mdtab_shard* shard = &g_shards[i];
- gpr_mu_init(&shard->mu);
- shard->count = 0;
- gpr_atm_no_barrier_store(&shard->free_estimate, 0);
- shard->capacity = INITIAL_SHARD_CAPACITY;
+ size_t count;
+ size_t capacity;
+ /** Estimate of the number of unreferenced mdelems in the hash table.
+ This will eventually converge to the exact number, but it's instantaneous
+ accuracy is not guaranteed */
+ gpr_atm free_estimate;
+} mdtab_shard;
+
+static mdtab_shard g_shards[SHARD_COUNT];
+
+static void gc_mdtab(mdtab_shard* shard);
+
+void grpc_mdctx_global_init(void) {
+ /* initialize shards */
+ for (size_t i = 0; i < SHARD_COUNT; i++) {
+ mdtab_shard* shard = &g_shards[i];
+ gpr_mu_init(&shard->mu);
+ shard->count = 0;
+ gpr_atm_no_barrier_store(&shard->free_estimate, 0);
+ shard->capacity = INITIAL_SHARD_CAPACITY;
shard->elems = static_cast<InternedMetadata::BucketLink*>(
- gpr_zalloc(sizeof(*shard->elems) * shard->capacity));
- }
-}
-
-void grpc_mdctx_global_shutdown() {
- for (size_t i = 0; i < SHARD_COUNT; i++) {
- mdtab_shard* shard = &g_shards[i];
- gpr_mu_destroy(&shard->mu);
- gc_mdtab(shard);
- if (shard->count != 0) {
+ gpr_zalloc(sizeof(*shard->elems) * shard->capacity));
+ }
+}
+
+void grpc_mdctx_global_shutdown() {
+ for (size_t i = 0; i < SHARD_COUNT; i++) {
+ mdtab_shard* shard = &g_shards[i];
+ gpr_mu_destroy(&shard->mu);
+ gc_mdtab(shard);
+ if (shard->count != 0) {
gpr_log(GPR_ERROR, "WARNING: %" PRIuPTR " metadata elements were leaked",
- shard->count);
+ shard->count);
for (int i = 0; i < shard->capacity; i++) {
for (InternedMetadata* md = shard->elems[i].next; md;
md = md->bucket_next()) {
@@ -262,95 +262,95 @@ void grpc_mdctx_global_shutdown() {
gpr_free(value_str);
}
}
- if (grpc_iomgr_abort_on_leaks()) {
- abort();
- }
- }
+ if (grpc_iomgr_abort_on_leaks()) {
+ abort();
+ }
+ }
// 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
- gpr_free(shard->elems);
- }
-}
-
+ gpr_free(shard->elems);
+ }
+}
+
#ifndef NDEBUG
-static int is_mdelem_static(grpc_mdelem e) {
+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];
-}
+}
#endif
-
+
void InternedMetadata::RefWithShardLocked(mdtab_shard* shard) {
-#ifndef NDEBUG
- if (grpc_trace_metadata.enabled()) {
+#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);
- gpr_free(key_str);
- gpr_free(value_str);
- }
-#endif
+ gpr_free(key_str);
+ gpr_free(value_str);
+ }
+#endif
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);
+ 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;
- }
+ }
gpr_atm_no_barrier_fetch_add(&shard->free_estimate,
-static_cast<intptr_t>(num_freed));
-}
-
-static void grow_mdtab(mdtab_shard* shard) {
- GPR_TIMER_SCOPE("grow_mdtab", 0);
-
- size_t capacity = shard->capacity * 2;
- size_t i;
+}
+
+static void grow_mdtab(mdtab_shard* shard) {
+ GPR_TIMER_SCOPE("grow_mdtab", 0);
+
+ size_t capacity = shard->capacity * 2;
+ size_t i;
InternedMetadata::BucketLink* mdtab;
InternedMetadata *md, *next;
- uint32_t hash;
-
+ uint32_t hash;
+
mdtab = static_cast<InternedMetadata::BucketLink*>(
gpr_zalloc(sizeof(InternedMetadata::BucketLink) * capacity));
-
- for (i = 0; i < shard->capacity; i++) {
+
+ for (i = 0; i < shard->capacity; i++) {
for (md = shard->elems[i].next; md; md = next) {
- size_t idx;
+ size_t idx;
hash = md->hash();
next = md->bucket_next();
- idx = TABLE_IDX(hash, capacity);
+ idx = TABLE_IDX(hash, capacity);
md->set_bucket_next(mdtab[idx].next);
mdtab[idx].next = md;
- }
- }
- gpr_free(shard->elems);
- shard->elems = mdtab;
- shard->capacity = capacity;
-}
-
-static void rehash_mdtab(mdtab_shard* shard) {
- if (gpr_atm_no_barrier_load(&shard->free_estimate) >
- static_cast<gpr_atm>(shard->capacity / 4)) {
- gc_mdtab(shard);
- } else {
- grow_mdtab(shard);
- }
-}
-
+ }
+ }
+ gpr_free(shard->elems);
+ shard->elems = mdtab;
+ shard->capacity = capacity;
+}
+
+static void rehash_mdtab(mdtab_shard* shard) {
+ if (gpr_atm_no_barrier_load(&shard->free_estimate) >
+ static_cast<gpr_atm>(shard->capacity / 4)) {
+ gc_mdtab(shard);
+ } else {
+ grow_mdtab(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);
@@ -362,7 +362,7 @@ static grpc_mdelem md_create_must_intern(const grpc_slice& key,
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) {
+ 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));
@@ -375,10 +375,10 @@ static grpc_mdelem md_create(
// 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) {
+ if (compatible_external_backing_store != nullptr) {
// Caller provided backing store.
- return GRPC_MAKE_MDELEM(compatible_external_backing_store,
- GRPC_MDELEM_STORAGE_EXTERNAL);
+ return GRPC_MAKE_MDELEM(compatible_external_backing_store,
+ GRPC_MDELEM_STORAGE_EXTERNAL);
} else {
// We allocate backing store.
return key_definitely_static
@@ -390,12 +390,12 @@ static grpc_mdelem md_create(
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) {
@@ -418,13 +418,13 @@ static grpc_mdelem md_create_maybe_static(const grpc_slice& 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(
+ grpc_mdelem static_elem = grpc_static_mdelem_for_static_strings(
kidx, GRPC_STATIC_METADATA_INDEX(value));
- if (!GRPC_MDISNULL(static_elem)) {
- return static_elem;
- }
- }
-
+ 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);
@@ -445,42 +445,42 @@ static grpc_mdelem md_create_must_intern(const grpc_slice& key,
// 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;
-
- GPR_TIMER_SCOPE("grpc_mdelem_from_metadata_strings", 0);
-
- gpr_mu_lock(&shard->mu);
-
- idx = TABLE_IDX(hash, shard->capacity);
- /* search for an existing pair */
+ mdtab_shard* shard = &g_shards[SHARD_IDX(hash)];
+ size_t idx;
+
+ GPR_TIMER_SCOPE("grpc_mdelem_from_metadata_strings", 0);
+
+ gpr_mu_lock(&shard->mu);
+
+ 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);
- gpr_mu_unlock(&shard->mu);
- return GRPC_MAKE_MDELEM(md, GRPC_MDELEM_STORAGE_INTERNED);
- }
- }
-
- /* not found: create a new pair */
+ 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;
- shard->count++;
-
- if (shard->count > shard->capacity * 2) {
- rehash_mdtab(shard);
- }
-
- gpr_mu_unlock(&shard->mu);
-
- return GRPC_MAKE_MDELEM(md, GRPC_MDELEM_STORAGE_INTERNED);
-}
-
+ shard->count++;
+
+ if (shard->count > shard->capacity * 2) {
+ rehash_mdtab(shard);
+ }
+
+ gpr_mu_unlock(&shard->mu);
+
+ 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) {
@@ -543,22 +543,22 @@ grpc_mdelem grpc_mdelem_from_slices(
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;
-}
-
-grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_metadata* metadata) {
- bool changed = false;
- grpc_slice key_slice =
- grpc_slice_maybe_static_intern(metadata->key, &changed);
- grpc_slice value_slice =
- grpc_slice_maybe_static_intern(metadata->value, &changed);
- return grpc_mdelem_create(
- key_slice, value_slice,
- changed ? nullptr : reinterpret_cast<grpc_mdelem_data*>(metadata));
-}
-
+ grpc_slice_unref_internal(key);
+ grpc_slice_unref_internal(value);
+ return out;
+}
+
+grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_metadata* metadata) {
+ bool changed = false;
+ grpc_slice key_slice =
+ grpc_slice_maybe_static_intern(metadata->key, &changed);
+ grpc_slice value_slice =
+ grpc_slice_maybe_static_intern(metadata->value, &changed);
+ return grpc_mdelem_create(
+ key_slice, value_slice,
+ 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) {
@@ -570,9 +570,9 @@ static void* get_user_data(UserData* user_data, void (*destroy_func)(void*)) {
void* grpc_mdelem_get_user_data(grpc_mdelem md, void (*destroy_func)(void*)) {
switch (GRPC_MDELEM_STORAGE(md)) {
- case GRPC_MDELEM_STORAGE_EXTERNAL:
+ case GRPC_MDELEM_STORAGE_EXTERNAL:
return nullptr;
- case GRPC_MDELEM_STORAGE_STATIC:
+ case GRPC_MDELEM_STORAGE_STATIC:
return reinterpret_cast<void*>(
grpc_static_mdelem_user_data
[reinterpret_cast<grpc_core::StaticMetadata*>(
@@ -582,10 +582,10 @@ void* grpc_mdelem_get_user_data(grpc_mdelem md, void (*destroy_func)(void*)) {
auto* am = reinterpret_cast<AllocatedMetadata*>(GRPC_MDELEM_DATA(md));
return get_user_data(am->user_data(), destroy_func);
}
- case GRPC_MDELEM_STORAGE_INTERNED: {
+ case GRPC_MDELEM_STORAGE_INTERNED: {
auto* im = reinterpret_cast<InternedMetadata*> GRPC_MDELEM_DATA(md);
return get_user_data(im->user_data(), destroy_func);
- }
+ }
}
GPR_UNREACHABLE_CODE(return nullptr);
}
@@ -620,19 +620,19 @@ void* grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void*),
[reinterpret_cast<grpc_core::StaticMetadata*>(
GRPC_MDELEM_DATA(md)) -
grpc_static_mdelem_table()]);
- case GRPC_MDELEM_STORAGE_ALLOCATED: {
+ 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);
}
- }
+ }
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;
@@ -647,43 +647,43 @@ static void note_disposed_interned_metadata(uint32_t hash) {
}
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:
+ switch (GRPC_MDELEM_STORAGE(gmd)) {
+ case GRPC_MDELEM_STORAGE_EXTERNAL:
+ case GRPC_MDELEM_STORAGE_STATIC:
return;
- case GRPC_MDELEM_STORAGE_INTERNED: {
+ 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))) {
- /* 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 */
+ /* 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);
- }
- break;
- }
- case GRPC_MDELEM_STORAGE_ALLOCATED: {
+ }
+ 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;
- }
- break;
- }
- }
-}
-
+ }
+ break;
+ }
+ }
+}
+
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:
+ case GRPC_MDELEM_STORAGE_EXTERNAL:
+ case GRPC_MDELEM_STORAGE_STATIC:
return;
- case GRPC_MDELEM_STORAGE_INTERNED: {
+ case GRPC_MDELEM_STORAGE_INTERNED: {
note_disposed_interned_metadata(hash);
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 4bb8d64dd03..24cf7eda4ac 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata.h
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata.h
@@ -1,38 +1,38 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_METADATA_H
#define GRPC_CORE_LIB_TRANSPORT_METADATA_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <grpc/impl/codegen/log.h>
-#include <grpc/grpc.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/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"
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_metadata;
+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.
@@ -64,56 +64,56 @@ extern grpc_core::DebugOnlyTraceFlag grpc_trace_metadata;
/* Forward declarations */
typedef struct grpc_mdelem grpc_mdelem;
-/* if changing this, make identical changes in:
+/* if changing this, make identical changes in:
- grpc_core::{InternedMetadata, AllocatedMetadata}
- - grpc_metadata in grpc_types.h */
-typedef struct grpc_mdelem_data {
- const grpc_slice key;
- const grpc_slice value;
+ - grpc_metadata in grpc_types.h */
+typedef struct grpc_mdelem_data {
+ const grpc_slice key;
+ const grpc_slice value;
/* there is a private part to this in metadata.c */
-} grpc_mdelem_data;
-
-/* GRPC_MDELEM_STORAGE_* enum values that can be treated as interned always have
- this bit set in their integer value */
-#define GRPC_MDELEM_STORAGE_INTERNED_BIT 1
+} grpc_mdelem_data;
+/* GRPC_MDELEM_STORAGE_* enum values that can be treated as interned always have
+ 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). */
-typedef enum {
- /* memory pointed to by grpc_mdelem::payload is owned by an external system */
- GRPC_MDELEM_STORAGE_EXTERNAL = 0,
+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 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 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,
-} grpc_mdelem_data_storage;
-
+} grpc_mdelem_data_storage;
+
struct grpc_mdelem {
- /* a grpc_mdelem_data* generally, with the two lower bits signalling memory
- ownership as per grpc_mdelem_data_storage */
- uintptr_t payload;
+ /* a grpc_mdelem_data* generally, with the two lower bits signalling memory
+ ownership as per grpc_mdelem_data_storage */
+ uintptr_t payload;
};
-#define GRPC_MDELEM_DATA(md) ((grpc_mdelem_data*)((md).payload & ~(uintptr_t)3))
-#define GRPC_MDELEM_STORAGE(md) \
- ((grpc_mdelem_data_storage)((md).payload & (uintptr_t)3))
-#ifdef __cplusplus
-#define GRPC_MAKE_MDELEM(data, storage) \
- (grpc_mdelem{((uintptr_t)(data)) | ((uintptr_t)storage)})
-#else
-#define GRPC_MAKE_MDELEM(data, storage) \
- ((grpc_mdelem){((uintptr_t)(data)) | ((uintptr_t)storage)})
-#endif
-#define GRPC_MDELEM_IS_INTERNED(md) \
- ((grpc_mdelem_data_storage)((md).payload & \
- (uintptr_t)GRPC_MDELEM_STORAGE_INTERNED_BIT))
+#define GRPC_MDELEM_DATA(md) ((grpc_mdelem_data*)((md).payload & ~(uintptr_t)3))
+#define GRPC_MDELEM_STORAGE(md) \
+ ((grpc_mdelem_data_storage)((md).payload & (uintptr_t)3))
+#ifdef __cplusplus
+#define GRPC_MAKE_MDELEM(data, storage) \
+ (grpc_mdelem{((uintptr_t)(data)) | ((uintptr_t)storage)})
+#else
+#define GRPC_MAKE_MDELEM(data, storage) \
+ ((grpc_mdelem){((uintptr_t)(data)) | ((uintptr_t)storage)})
+#endif
+#define GRPC_MDELEM_IS_INTERNED(md) \
+ ((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,
@@ -140,17 +140,17 @@ grpc_mdelem grpc_mdelem_from_slices(const grpc_core::StaticMetadataSlice& key,
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);
+/* 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);
-/* Does not unref the slices; if a new non-interned mdelem is needed, allocates
- one if compatible_external_backing_store is NULL, or uses
- compatible_external_backing_store if it is non-NULL (in which case it's the
- users responsibility to ensure that it outlives usage) */
-grpc_mdelem grpc_mdelem_create(
+/* Does not unref the slices; if a new non-interned mdelem is needed, allocates
+ one if compatible_external_backing_store is NULL, or uses
+ compatible_external_backing_store if it is non-NULL (in which case it's the
+ users responsibility to ensure that it outlives usage) */
+grpc_mdelem grpc_mdelem_create(
const grpc_slice& key, const grpc_slice& value,
- grpc_mdelem_data* compatible_external_backing_store);
+ grpc_mdelem_data* compatible_external_backing_store);
/* Like grpc_mdelem_create, but we know that key is static. */
grpc_mdelem grpc_mdelem_create(
@@ -160,7 +160,7 @@ grpc_mdelem grpc_mdelem_create(
#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);
+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
@@ -182,14 +182,14 @@ inline bool grpc_mdelem_both_interned_eq(grpc_mdelem a_interned,
/* 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* 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
+#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);
@@ -365,12 +365,12 @@ inline grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd) {
}
#ifndef NDEBUG
-#define GRPC_MDELEM_UNREF(s) grpc_mdelem_unref((s), __FILE__, __LINE__)
+#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) {
#else
-#define GRPC_MDELEM_UNREF(s) grpc_mdelem_unref((s))
+#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) {
@@ -400,17 +400,17 @@ inline void grpc_mdelem_unref(grpc_mdelem gmd) {
}
}
-#define GRPC_MDNULL GRPC_MAKE_MDELEM(NULL, GRPC_MDELEM_STORAGE_EXTERNAL)
+#define GRPC_MDNULL GRPC_MAKE_MDELEM(NULL, GRPC_MDELEM_STORAGE_EXTERNAL)
/* We add 32 bytes of padding as per RFC-7540 section 6.5.2. */
-#define GRPC_MDELEM_LENGTH(e) \
- (GRPC_SLICE_LENGTH(GRPC_MDKEY((e))) + GRPC_SLICE_LENGTH(GRPC_MDVALUE((e))) + \
- 32)
+#define GRPC_MDELEM_LENGTH(e) \
+ (GRPC_SLICE_LENGTH(GRPC_MDKEY((e))) + GRPC_SLICE_LENGTH(GRPC_MDVALUE((e))) + \
+ 32)
#define GRPC_MDSTR_KV_HASH(k_hash, v_hash) (GPR_ROTL((k_hash), 2) ^ (v_hash))
void grpc_mdctx_global_init(void);
-void grpc_mdctx_global_shutdown();
+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
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 66749b671c7..3a5b39c105a 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc
@@ -1,104 +1,104 @@
-/*
- *
- * 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/transport/metadata_batch.h"
-
-#include <stdbool.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.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"
-
-static void assert_valid_list(grpc_mdelem_list* list) {
-#ifndef NDEBUG
- grpc_linked_mdelem* l;
-
- GPR_ASSERT((list->head == nullptr) == (list->tail == nullptr));
- if (!list->head) return;
- GPR_ASSERT(list->head->prev == nullptr);
- GPR_ASSERT(list->tail->next == nullptr);
- GPR_ASSERT((list->head == list->tail) == (list->head->next == nullptr));
-
- size_t verified_count = 0;
- for (l = list->head; l; l = l->next) {
- GPR_ASSERT(!GRPC_MDISNULL(l->md));
- GPR_ASSERT((l->prev == nullptr) == (l == list->head));
- GPR_ASSERT((l->next == nullptr) == (l == list->tail));
- if (l->next) GPR_ASSERT(l->next->prev == l);
- if (l->prev) GPR_ASSERT(l->prev->next == l);
- verified_count++;
- }
- GPR_ASSERT(list->count == verified_count);
+/*
+ *
+ * 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/transport/metadata_batch.h"
+
+#include <stdbool.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.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"
+
+static void assert_valid_list(grpc_mdelem_list* list) {
+#ifndef NDEBUG
+ grpc_linked_mdelem* l;
+
+ GPR_ASSERT((list->head == nullptr) == (list->tail == nullptr));
+ if (!list->head) return;
+ GPR_ASSERT(list->head->prev == nullptr);
+ GPR_ASSERT(list->tail->next == nullptr);
+ GPR_ASSERT((list->head == list->tail) == (list->head->next == nullptr));
+
+ size_t verified_count = 0;
+ for (l = list->head; l; l = l->next) {
+ GPR_ASSERT(!GRPC_MDISNULL(l->md));
+ GPR_ASSERT((l->prev == nullptr) == (l == list->head));
+ GPR_ASSERT((l->next == nullptr) == (l == list->tail));
+ if (l->next) GPR_ASSERT(l->next->prev == l);
+ if (l->prev) GPR_ASSERT(l->prev->next == l);
+ verified_count++;
+ }
+ GPR_ASSERT(list->count == verified_count);
#else
// Avoid unused-parameter warning for debug-only parameter
(void)list;
-#endif /* NDEBUG */
-}
-
-static void assert_valid_callouts(grpc_metadata_batch* batch) {
-#ifndef NDEBUG
- for (grpc_linked_mdelem* l = batch->list.head; l != nullptr; l = l->next) {
- grpc_slice key_interned = grpc_slice_intern(GRPC_MDKEY(l->md));
- grpc_metadata_batch_callouts_index callout_idx =
- GRPC_BATCH_INDEX_OF(key_interned);
- if (callout_idx != GRPC_BATCH_CALLOUTS_COUNT) {
- GPR_ASSERT(batch->idx.array[callout_idx] == l);
- }
- grpc_slice_unref_internal(key_interned);
- }
+#endif /* NDEBUG */
+}
+
+static void assert_valid_callouts(grpc_metadata_batch* batch) {
+#ifndef NDEBUG
+ for (grpc_linked_mdelem* l = batch->list.head; l != nullptr; l = l->next) {
+ grpc_slice key_interned = grpc_slice_intern(GRPC_MDKEY(l->md));
+ grpc_metadata_batch_callouts_index callout_idx =
+ GRPC_BATCH_INDEX_OF(key_interned);
+ if (callout_idx != GRPC_BATCH_CALLOUTS_COUNT) {
+ GPR_ASSERT(batch->idx.array[callout_idx] == l);
+ }
+ grpc_slice_unref_internal(key_interned);
+ }
#else
// Avoid unused-parameter warning for debug-only parameter
(void)batch;
-#endif
-}
-
-#ifndef NDEBUG
-void grpc_metadata_batch_assert_ok(grpc_metadata_batch* batch) {
- assert_valid_list(&batch->list);
-}
-#endif /* NDEBUG */
-
-void grpc_metadata_batch_init(grpc_metadata_batch* batch) {
- memset(batch, 0, sizeof(*batch));
- batch->deadline = GRPC_MILLIS_INF_FUTURE;
-}
-
-void grpc_metadata_batch_destroy(grpc_metadata_batch* batch) {
- grpc_linked_mdelem* l;
- for (l = batch->list.head; l; l = l->next) {
- GRPC_MDELEM_UNREF(l->md);
- }
-}
-
-grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md) {
- grpc_error* out = grpc_error_set_str(
- grpc_error_set_str(src, GRPC_ERROR_STR_KEY,
- grpc_slice_ref_internal(GRPC_MDKEY(md))),
- GRPC_ERROR_STR_VALUE, grpc_slice_ref_internal(GRPC_MDVALUE(md)));
- return out;
-}
-
+#endif
+}
+
+#ifndef NDEBUG
+void grpc_metadata_batch_assert_ok(grpc_metadata_batch* batch) {
+ assert_valid_list(&batch->list);
+}
+#endif /* NDEBUG */
+
+void grpc_metadata_batch_init(grpc_metadata_batch* batch) {
+ memset(batch, 0, sizeof(*batch));
+ batch->deadline = GRPC_MILLIS_INF_FUTURE;
+}
+
+void grpc_metadata_batch_destroy(grpc_metadata_batch* batch) {
+ grpc_linked_mdelem* l;
+ for (l = batch->list.head; l; l = l->next) {
+ GRPC_MDELEM_UNREF(l->md);
+ }
+}
+
+grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md) {
+ grpc_error* out = grpc_error_set_str(
+ grpc_error_set_str(src, GRPC_ERROR_STR_KEY,
+ grpc_slice_ref_internal(GRPC_MDKEY(md))),
+ GRPC_ERROR_STR_VALUE, grpc_slice_ref_internal(GRPC_MDVALUE(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);
@@ -116,69 +116,69 @@ static grpc_error* link_callout(grpc_metadata_batch* batch,
return error_with_md(storage->md);
}
-static grpc_error* maybe_link_callout(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage)
- GRPC_MUST_USE_RESULT;
-
-static grpc_error* maybe_link_callout(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage) {
- grpc_metadata_batch_callouts_index idx =
- GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md));
- if (idx == GRPC_BATCH_CALLOUTS_COUNT) {
- return GRPC_ERROR_NONE;
- }
+static grpc_error* maybe_link_callout(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage)
+ GRPC_MUST_USE_RESULT;
+
+static grpc_error* maybe_link_callout(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage) {
+ grpc_metadata_batch_callouts_index idx =
+ GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md));
+ if (idx == GRPC_BATCH_CALLOUTS_COUNT) {
+ return GRPC_ERROR_NONE;
+ }
return link_callout(batch, storage, idx);
-}
-
-static void maybe_unlink_callout(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage) {
- grpc_metadata_batch_callouts_index idx =
- GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md));
- if (idx == GRPC_BATCH_CALLOUTS_COUNT) {
- return;
- }
+}
+
+static void maybe_unlink_callout(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage) {
+ grpc_metadata_batch_callouts_index idx =
+ GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md));
+ if (idx == GRPC_BATCH_CALLOUTS_COUNT) {
+ return;
+ }
--batch->list.default_count;
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) {
+ 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));
- 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);
+ 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));
- storage->prev = nullptr;
- storage->next = list->head;
+ storage->prev = nullptr;
+ storage->next = list->head;
storage->reserved = nullptr;
- if (list->head != nullptr) {
- list->head->prev = storage;
- } else {
- list->tail = storage;
- }
- list->head = storage;
- list->count++;
- assert_valid_list(list);
-}
-
-grpc_error* grpc_metadata_batch_link_head(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage) {
- assert_valid_callouts(batch);
- grpc_error* err = maybe_link_callout(batch, storage);
- if (err != GRPC_ERROR_NONE) {
- assert_valid_callouts(batch);
- return err;
- }
- link_head(&batch->list, storage);
- assert_valid_callouts(batch);
- return GRPC_ERROR_NONE;
-}
-
+ if (list->head != nullptr) {
+ list->head->prev = storage;
+ } else {
+ list->tail = storage;
+ }
+ list->head = storage;
+ list->count++;
+ assert_valid_list(list);
+}
+
+grpc_error* grpc_metadata_batch_link_head(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage) {
+ assert_valid_callouts(batch);
+ grpc_error* err = maybe_link_callout(batch, storage);
+ if (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?
@@ -197,43 +197,43 @@ grpc_error* grpc_metadata_batch_link_head(
return GRPC_ERROR_NONE;
}
-grpc_error* grpc_metadata_batch_add_tail(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage,
- grpc_mdelem elem_to_add) {
+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));
- 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);
+ 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));
- storage->prev = list->tail;
- storage->next = nullptr;
- storage->reserved = nullptr;
- if (list->tail != nullptr) {
- list->tail->next = storage;
- } else {
- list->head = storage;
- }
- list->tail = storage;
- list->count++;
- assert_valid_list(list);
-}
-
-grpc_error* grpc_metadata_batch_link_tail(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage) {
- assert_valid_callouts(batch);
- grpc_error* err = maybe_link_callout(batch, storage);
- if (err != GRPC_ERROR_NONE) {
- assert_valid_callouts(batch);
- return err;
- }
- link_tail(&batch->list, storage);
- assert_valid_callouts(batch);
- return GRPC_ERROR_NONE;
-}
-
+ storage->prev = list->tail;
+ storage->next = nullptr;
+ storage->reserved = nullptr;
+ if (list->tail != nullptr) {
+ list->tail->next = storage;
+ } else {
+ list->head = storage;
+ }
+ list->tail = storage;
+ list->count++;
+ assert_valid_list(list);
+}
+
+grpc_error* grpc_metadata_batch_link_tail(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage) {
+ assert_valid_callouts(batch);
+ grpc_error* err = maybe_link_callout(batch, storage);
+ if (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) {
@@ -249,32 +249,32 @@ grpc_error* grpc_metadata_batch_link_tail(
return GRPC_ERROR_NONE;
}
-static void unlink_storage(grpc_mdelem_list* list,
- grpc_linked_mdelem* storage) {
- assert_valid_list(list);
- if (storage->prev != nullptr) {
- storage->prev->next = storage->next;
- } else {
- list->head = storage->next;
- }
- if (storage->next != nullptr) {
- storage->next->prev = storage->prev;
- } else {
- list->tail = storage->prev;
- }
- list->count--;
- assert_valid_list(list);
-}
-
-void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage) {
- assert_valid_callouts(batch);
- maybe_unlink_callout(batch, storage);
- unlink_storage(&batch->list, storage);
- GRPC_MDELEM_UNREF(storage->md);
- assert_valid_callouts(batch);
-}
-
+static void unlink_storage(grpc_mdelem_list* list,
+ grpc_linked_mdelem* storage) {
+ assert_valid_list(list);
+ if (storage->prev != nullptr) {
+ storage->prev->next = storage->next;
+ } else {
+ list->head = storage->next;
+ }
+ if (storage->next != nullptr) {
+ storage->next->prev = storage->prev;
+ } else {
+ list->tail = storage->prev;
+ }
+ list->count--;
+ assert_valid_list(list);
+}
+
+void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage) {
+ assert_valid_callouts(batch);
+ maybe_unlink_callout(batch, storage);
+ 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);
@@ -287,106 +287,106 @@ void grpc_metadata_batch_remove(grpc_metadata_batch* batch,
assert_valid_callouts(batch);
}
-void grpc_metadata_batch_set_value(grpc_linked_mdelem* storage,
+void grpc_metadata_batch_set_value(grpc_linked_mdelem* storage,
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);
- storage->md = new_mdelem;
- GRPC_MDELEM_UNREF(old_mdelem);
-}
-
-grpc_error* grpc_metadata_batch_substitute(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage,
- grpc_mdelem new_mdelem) {
- assert_valid_callouts(batch);
- grpc_error* error = GRPC_ERROR_NONE;
- grpc_mdelem old_mdelem = storage->md;
- if (!grpc_slice_eq(GRPC_MDKEY(new_mdelem), GRPC_MDKEY(old_mdelem))) {
- maybe_unlink_callout(batch, storage);
- storage->md = new_mdelem;
- error = maybe_link_callout(batch, storage);
- if (error != GRPC_ERROR_NONE) {
- unlink_storage(&batch->list, storage);
- GRPC_MDELEM_UNREF(storage->md);
- }
- } else {
- storage->md = new_mdelem;
- }
- GRPC_MDELEM_UNREF(old_mdelem);
- assert_valid_callouts(batch);
- return error;
-}
-
-void grpc_metadata_batch_clear(grpc_metadata_batch* batch) {
- grpc_metadata_batch_destroy(batch);
- grpc_metadata_batch_init(batch);
-}
-
-bool grpc_metadata_batch_is_empty(grpc_metadata_batch* batch) {
- return batch->list.head == nullptr &&
- batch->deadline == GRPC_MILLIS_INF_FUTURE;
-}
-
-size_t grpc_metadata_batch_size(grpc_metadata_batch* batch) {
- size_t size = 0;
- for (grpc_linked_mdelem* elem = batch->list.head; elem != nullptr;
- elem = elem->next) {
- size += GRPC_MDELEM_LENGTH(elem->md);
- }
- return size;
-}
-
-static void add_error(grpc_error** composite, grpc_error* error,
- const char* composite_error_string) {
- if (error == GRPC_ERROR_NONE) return;
- if (*composite == GRPC_ERROR_NONE) {
- *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(composite_error_string);
- }
- *composite = grpc_error_add_child(*composite, error);
-}
-
-grpc_error* grpc_metadata_batch_filter(grpc_metadata_batch* batch,
- grpc_metadata_batch_filter_func func,
- void* user_data,
- const char* composite_error_string) {
- grpc_linked_mdelem* l = batch->list.head;
- grpc_error* error = GRPC_ERROR_NONE;
- while (l) {
- grpc_linked_mdelem* next = l->next;
- grpc_filtered_mdelem new_mdelem = func(user_data, l->md);
- add_error(&error, new_mdelem.error, composite_error_string);
- if (GRPC_MDISNULL(new_mdelem.md)) {
- grpc_metadata_batch_remove(batch, l);
- } else if (new_mdelem.md.payload != l->md.payload) {
- grpc_metadata_batch_substitute(batch, l, new_mdelem.md);
- }
- l = next;
- }
- return error;
-}
-
-void grpc_metadata_batch_copy(grpc_metadata_batch* src,
- grpc_metadata_batch* dst,
- grpc_linked_mdelem* storage) {
- grpc_metadata_batch_init(dst);
- dst->deadline = src->deadline;
- size_t i = 0;
- for (grpc_linked_mdelem* elem = src->list.head; elem != nullptr;
- elem = elem->next) {
+ grpc_mdelem old_mdelem = storage->md;
+ grpc_mdelem new_mdelem = grpc_mdelem_from_slices(
+ grpc_slice_ref_internal(GRPC_MDKEY(old_mdelem)), value);
+ storage->md = new_mdelem;
+ GRPC_MDELEM_UNREF(old_mdelem);
+}
+
+grpc_error* grpc_metadata_batch_substitute(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage,
+ grpc_mdelem new_mdelem) {
+ assert_valid_callouts(batch);
+ grpc_error* error = GRPC_ERROR_NONE;
+ grpc_mdelem old_mdelem = storage->md;
+ if (!grpc_slice_eq(GRPC_MDKEY(new_mdelem), GRPC_MDKEY(old_mdelem))) {
+ maybe_unlink_callout(batch, storage);
+ storage->md = new_mdelem;
+ error = maybe_link_callout(batch, storage);
+ if (error != GRPC_ERROR_NONE) {
+ unlink_storage(&batch->list, storage);
+ GRPC_MDELEM_UNREF(storage->md);
+ }
+ } else {
+ storage->md = new_mdelem;
+ }
+ GRPC_MDELEM_UNREF(old_mdelem);
+ assert_valid_callouts(batch);
+ return error;
+}
+
+void grpc_metadata_batch_clear(grpc_metadata_batch* batch) {
+ grpc_metadata_batch_destroy(batch);
+ grpc_metadata_batch_init(batch);
+}
+
+bool grpc_metadata_batch_is_empty(grpc_metadata_batch* batch) {
+ return batch->list.head == nullptr &&
+ batch->deadline == GRPC_MILLIS_INF_FUTURE;
+}
+
+size_t grpc_metadata_batch_size(grpc_metadata_batch* batch) {
+ size_t size = 0;
+ for (grpc_linked_mdelem* elem = batch->list.head; elem != nullptr;
+ elem = elem->next) {
+ size += GRPC_MDELEM_LENGTH(elem->md);
+ }
+ return size;
+}
+
+static void add_error(grpc_error** composite, grpc_error* error,
+ const char* composite_error_string) {
+ if (error == GRPC_ERROR_NONE) return;
+ if (*composite == GRPC_ERROR_NONE) {
+ *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(composite_error_string);
+ }
+ *composite = grpc_error_add_child(*composite, error);
+}
+
+grpc_error* grpc_metadata_batch_filter(grpc_metadata_batch* batch,
+ grpc_metadata_batch_filter_func func,
+ void* user_data,
+ const char* composite_error_string) {
+ grpc_linked_mdelem* l = batch->list.head;
+ grpc_error* error = GRPC_ERROR_NONE;
+ while (l) {
+ grpc_linked_mdelem* next = l->next;
+ grpc_filtered_mdelem new_mdelem = func(user_data, l->md);
+ add_error(&error, new_mdelem.error, composite_error_string);
+ if (GRPC_MDISNULL(new_mdelem.md)) {
+ grpc_metadata_batch_remove(batch, l);
+ } else if (new_mdelem.md.payload != l->md.payload) {
+ grpc_metadata_batch_substitute(batch, l, new_mdelem.md);
+ }
+ l = next;
+ }
+ return error;
+}
+
+void grpc_metadata_batch_copy(grpc_metadata_batch* src,
+ grpc_metadata_batch* dst,
+ grpc_linked_mdelem* storage) {
+ grpc_metadata_batch_init(dst);
+ dst->deadline = src->deadline;
+ 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));
- // 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.
+ // 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);
- }
-}
-
-void grpc_metadata_batch_move(grpc_metadata_batch* src,
- grpc_metadata_batch* dst) {
- *dst = *src;
- grpc_metadata_batch_init(src);
-}
+ }
+}
+
+void grpc_metadata_batch_move(grpc_metadata_batch* src,
+ grpc_metadata_batch* dst) {
+ *dst = *src;
+ grpc_metadata_batch_init(src);
+}
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 3101f485a2b..0635d2aca1d 100644
--- a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h
+++ b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h
@@ -1,91 +1,91 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_METADATA_BATCH_H
#define GRPC_CORE_LIB_TRANSPORT_METADATA_BATCH_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <stdbool.h>
#include <grpc/grpc.h>
#include <grpc/slice.h>
#include <grpc/support/time.h>
-#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/transport/metadata.h"
-#include "src/core/lib/transport/static_metadata.h"
+#include "src/core/lib/transport/static_metadata.h"
typedef struct grpc_linked_mdelem {
grpc_linked_mdelem() {}
- grpc_mdelem md;
+ grpc_mdelem md;
struct grpc_linked_mdelem* next = nullptr;
struct grpc_linked_mdelem* prev = nullptr;
- void* reserved;
+ void* reserved;
} grpc_linked_mdelem;
typedef struct grpc_mdelem_list {
- size_t count;
- size_t default_count; // Number of default keys.
- grpc_linked_mdelem* head;
- grpc_linked_mdelem* tail;
+ size_t count;
+ size_t default_count; // Number of default keys.
+ grpc_linked_mdelem* head;
+ grpc_linked_mdelem* tail;
} grpc_mdelem_list;
typedef struct grpc_metadata_batch {
/** Metadata elements in this batch */
grpc_mdelem_list list;
- grpc_metadata_batch_callouts idx;
+ grpc_metadata_batch_callouts idx;
/** Used to calculate grpc-timeout at the point of sending,
- or GRPC_MILLIS_INF_FUTURE if this batch does not need to send a
+ or GRPC_MILLIS_INF_FUTURE if this batch does not need to send a
grpc-timeout */
- grpc_millis deadline;
+ grpc_millis deadline;
} grpc_metadata_batch;
-void grpc_metadata_batch_init(grpc_metadata_batch* batch);
-void grpc_metadata_batch_destroy(grpc_metadata_batch* batch);
-void grpc_metadata_batch_clear(grpc_metadata_batch* batch);
-bool grpc_metadata_batch_is_empty(grpc_metadata_batch* batch);
+void grpc_metadata_batch_init(grpc_metadata_batch* batch);
+void grpc_metadata_batch_destroy(grpc_metadata_batch* batch);
+void grpc_metadata_batch_clear(grpc_metadata_batch* batch);
+bool grpc_metadata_batch_is_empty(grpc_metadata_batch* batch);
/* Returns the transport size of the batch. */
-size_t grpc_metadata_batch_size(grpc_metadata_batch* batch);
+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);
+/** 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);
-/** Substitute a new mdelem for an old value */
-grpc_error* grpc_metadata_batch_substitute(grpc_metadata_batch* batch,
- grpc_linked_mdelem* storage,
- grpc_mdelem new_value);
-
-void grpc_metadata_batch_set_value(grpc_linked_mdelem* storage,
+/** Substitute a new mdelem for an old value */
+grpc_error* grpc_metadata_batch_substitute(grpc_metadata_batch* batch,
+ grpc_linked_mdelem* storage,
+ grpc_mdelem new_value);
+
+void grpc_metadata_batch_set_value(grpc_linked_mdelem* storage,
const grpc_slice& value);
-
+
/** Add \a storage to the beginning of \a batch. storage->md is
assumed to be valid.
\a storage is owned by the caller and must survive for the
lifetime of batch. This usually means it should be around
for the lifetime of the call. */
-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_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;
@@ -95,9 +95,9 @@ grpc_error* grpc_metadata_batch_link_head(
\a storage is owned by the caller and must survive for the
lifetime of batch. This usually means it should be around
for the lifetime of the call. */
-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_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;
@@ -108,9 +108,9 @@ grpc_error* grpc_metadata_batch_link_tail(
lifetime of batch. This usually means it should be around
for the lifetime of the call.
Takes ownership of \a elem_to_add */
-grpc_error* grpc_metadata_batch_add_head(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT;
+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.
@@ -134,9 +134,9 @@ inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_head(
lifetime of batch. This usually means it should be around
for the lifetime of the call.
Takes ownership of \a elem_to_add */
-grpc_error* grpc_metadata_batch_add_tail(
- grpc_metadata_batch* batch, grpc_linked_mdelem* storage,
- grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT;
+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,
@@ -152,40 +152,40 @@ inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_tail(
return grpc_metadata_batch_add_tail(batch, storage, idx);
}
-grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md);
+grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md);
struct grpc_filtered_mdelem {
- grpc_error* error;
- grpc_mdelem md;
+ grpc_error* error;
+ grpc_mdelem md;
};
-#define GRPC_FILTERED_ERROR(error) \
- { (error), GRPC_MDNULL }
-#define GRPC_FILTERED_MDELEM(md) \
- { GRPC_ERROR_NONE, (md) }
-#define GRPC_FILTERED_REMOVE() \
- { GRPC_ERROR_NONE, GRPC_MDNULL }
-
-typedef grpc_filtered_mdelem (*grpc_metadata_batch_filter_func)(
- void* user_data, grpc_mdelem elem);
-grpc_error* grpc_metadata_batch_filter(
- grpc_metadata_batch* batch, grpc_metadata_batch_filter_func func,
- void* user_data, const char* composite_error_string) GRPC_MUST_USE_RESULT;
-
+#define GRPC_FILTERED_ERROR(error) \
+ { (error), GRPC_MDNULL }
+#define GRPC_FILTERED_MDELEM(md) \
+ { GRPC_ERROR_NONE, (md) }
+#define GRPC_FILTERED_REMOVE() \
+ { GRPC_ERROR_NONE, GRPC_MDNULL }
+
+typedef grpc_filtered_mdelem (*grpc_metadata_batch_filter_func)(
+ void* user_data, grpc_mdelem elem);
+grpc_error* grpc_metadata_batch_filter(
+ grpc_metadata_batch* batch, grpc_metadata_batch_filter_func func,
+ void* user_data, const char* composite_error_string) GRPC_MUST_USE_RESULT;
+
#ifndef NDEBUG
-void grpc_metadata_batch_assert_ok(grpc_metadata_batch* comd);
+void grpc_metadata_batch_assert_ok(grpc_metadata_batch* comd);
#else
#define grpc_metadata_batch_assert_ok(comd) \
do { \
} while (0)
#endif
-/// Copies \a src to \a dst. \a storage must point to an array of
-/// \a grpc_linked_mdelem structs of at least the same size as \a src.
-void grpc_metadata_batch_copy(grpc_metadata_batch* src,
- grpc_metadata_batch* dst,
- grpc_linked_mdelem* storage);
-
-void grpc_metadata_batch_move(grpc_metadata_batch* src,
- grpc_metadata_batch* dst);
+/// Copies \a src to \a dst. \a storage must point to an array of
+/// \a grpc_linked_mdelem structs of at least the same size as \a src.
+void grpc_metadata_batch_copy(grpc_metadata_batch* src,
+ grpc_metadata_batch* dst,
+ grpc_linked_mdelem* storage);
+void grpc_metadata_batch_move(grpc_metadata_batch* src,
+ grpc_metadata_batch* dst);
+
#endif /* GRPC_CORE_LIB_TRANSPORT_METADATA_BATCH_H */
diff --git a/contrib/libs/grpc/src/core/lib/transport/pid_controller.cc b/contrib/libs/grpc/src/core/lib/transport/pid_controller.cc
index dbc98f4917f..86695da552f 100644
--- a/contrib/libs/grpc/src/core/lib/transport/pid_controller.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/pid_controller.cc
@@ -1,51 +1,51 @@
-/*
- *
- * 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/transport/pid_controller.h"
-
-#include "src/core/lib/gpr/useful.h"
-
-namespace grpc_core {
-
-PidController::PidController(const Args& args)
- : last_control_value_(args.initial_control_value()), args_(args) {}
-
-double PidController::Update(double error, double dt) {
- if (dt <= 0) return last_control_value_;
- /* integrate error using the trapezoid rule */
- error_integral_ += dt * (last_error_ + error) * 0.5;
- error_integral_ = GPR_CLAMP(error_integral_, -args_.integral_range(),
- args_.integral_range());
- double diff_error = (error - last_error_) / dt;
- /* calculate derivative of control value vs time */
- double dc_dt = args_.gain_p() * error + args_.gain_i() * error_integral_ +
- args_.gain_d() * diff_error;
- /* and perform trapezoidal integration */
- double new_control_value =
- last_control_value_ + dt * (last_dc_dt_ + dc_dt) * 0.5;
- new_control_value = GPR_CLAMP(new_control_value, args_.min_control_value(),
- args_.max_control_value());
- last_error_ = error;
- last_dc_dt_ = dc_dt;
- last_control_value_ = new_control_value;
- return new_control_value;
-}
-
-} // 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/transport/pid_controller.h"
+
+#include "src/core/lib/gpr/useful.h"
+
+namespace grpc_core {
+
+PidController::PidController(const Args& args)
+ : last_control_value_(args.initial_control_value()), args_(args) {}
+
+double PidController::Update(double error, double dt) {
+ if (dt <= 0) return last_control_value_;
+ /* integrate error using the trapezoid rule */
+ error_integral_ += dt * (last_error_ + error) * 0.5;
+ error_integral_ = GPR_CLAMP(error_integral_, -args_.integral_range(),
+ args_.integral_range());
+ double diff_error = (error - last_error_) / dt;
+ /* calculate derivative of control value vs time */
+ double dc_dt = args_.gain_p() * error + args_.gain_i() * error_integral_ +
+ args_.gain_d() * diff_error;
+ /* and perform trapezoidal integration */
+ double new_control_value =
+ last_control_value_ + dt * (last_dc_dt_ + dc_dt) * 0.5;
+ new_control_value = GPR_CLAMP(new_control_value, args_.min_control_value(),
+ args_.max_control_value());
+ last_error_ = error;
+ last_dc_dt_ = dc_dt;
+ last_control_value_ = new_control_value;
+ return new_control_value;
+}
+
+} // namespace grpc_core
diff --git a/contrib/libs/grpc/src/core/lib/transport/pid_controller.h b/contrib/libs/grpc/src/core/lib/transport/pid_controller.h
index e26205bf20d..0200d9259c6 100644
--- a/contrib/libs/grpc/src/core/lib/transport/pid_controller.h
+++ b/contrib/libs/grpc/src/core/lib/transport/pid_controller.h
@@ -1,28 +1,28 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_PID_CONTROLLER_H
#define GRPC_CORE_LIB_TRANSPORT_PID_CONTROLLER_H
-#include <grpc/support/port_platform.h>
-
-#include <limits>
-
+#include <grpc/support/port_platform.h>
+
+#include <limits>
+
/* \file Simple PID controller.
Implements a proportional-integral-derivative controller.
Used when we want to iteratively control a variable to converge some other
@@ -30,87 +30,87 @@
Gains can be set to adjust sensitivity to current error (p), the integral
of error (i), and the derivative of error (d). */
-namespace grpc_core {
-
-class PidController {
- public:
- class Args {
- public:
- double gain_p() const { return gain_p_; }
- double gain_i() const { return gain_i_; }
- double gain_d() const { return gain_d_; }
- double initial_control_value() const { return initial_control_value_; }
- double min_control_value() const { return min_control_value_; }
- double max_control_value() const { return max_control_value_; }
- double integral_range() const { return integral_range_; }
-
- Args& set_gain_p(double gain_p) {
- gain_p_ = gain_p;
- return *this;
- }
- Args& set_gain_i(double gain_i) {
- gain_i_ = gain_i;
- return *this;
- }
- Args& set_gain_d(double gain_d) {
- gain_d_ = gain_d;
- return *this;
- }
- Args& set_initial_control_value(double initial_control_value) {
- initial_control_value_ = initial_control_value;
- return *this;
- }
- Args& set_min_control_value(double min_control_value) {
- min_control_value_ = min_control_value;
- return *this;
- }
- Args& set_max_control_value(double max_control_value) {
- max_control_value_ = max_control_value;
- return *this;
- }
- Args& set_integral_range(double integral_range) {
- integral_range_ = integral_range;
- return *this;
- }
-
- private:
- double gain_p_ = 0.0;
- double gain_i_ = 0.0;
- double gain_d_ = 0.0;
- double initial_control_value_ = 0.0;
- double min_control_value_ = std::numeric_limits<double>::min();
- double max_control_value_ = std::numeric_limits<double>::max();
- double integral_range_ = std::numeric_limits<double>::max();
- };
-
- explicit PidController(const Args& args);
-
- /// Reset the controller internal state: useful when the environment has
- /// changed significantly
- void Reset() {
- last_error_ = 0.0;
- last_dc_dt_ = 0.0;
- error_integral_ = 0.0;
- }
-
- /// Update the controller: given a current error estimate, and the time since
- /// the last update, returns a new control value
- double Update(double error, double dt);
-
- /// Returns the last control value calculated
- double last_control_value() const { return last_control_value_; }
-
- /// Returns the current error integral (mostly for testing)
- double error_integral() const { return error_integral_; }
-
- private:
- double last_error_ = 0.0;
- double error_integral_ = 0.0;
- double last_control_value_;
- double last_dc_dt_ = 0.0;
- const Args args_;
-};
-
-} // namespace grpc_core
-
+namespace grpc_core {
+
+class PidController {
+ public:
+ class Args {
+ public:
+ double gain_p() const { return gain_p_; }
+ double gain_i() const { return gain_i_; }
+ double gain_d() const { return gain_d_; }
+ double initial_control_value() const { return initial_control_value_; }
+ double min_control_value() const { return min_control_value_; }
+ double max_control_value() const { return max_control_value_; }
+ double integral_range() const { return integral_range_; }
+
+ Args& set_gain_p(double gain_p) {
+ gain_p_ = gain_p;
+ return *this;
+ }
+ Args& set_gain_i(double gain_i) {
+ gain_i_ = gain_i;
+ return *this;
+ }
+ Args& set_gain_d(double gain_d) {
+ gain_d_ = gain_d;
+ return *this;
+ }
+ Args& set_initial_control_value(double initial_control_value) {
+ initial_control_value_ = initial_control_value;
+ return *this;
+ }
+ Args& set_min_control_value(double min_control_value) {
+ min_control_value_ = min_control_value;
+ return *this;
+ }
+ Args& set_max_control_value(double max_control_value) {
+ max_control_value_ = max_control_value;
+ return *this;
+ }
+ Args& set_integral_range(double integral_range) {
+ integral_range_ = integral_range;
+ return *this;
+ }
+
+ private:
+ double gain_p_ = 0.0;
+ double gain_i_ = 0.0;
+ double gain_d_ = 0.0;
+ double initial_control_value_ = 0.0;
+ double min_control_value_ = std::numeric_limits<double>::min();
+ double max_control_value_ = std::numeric_limits<double>::max();
+ double integral_range_ = std::numeric_limits<double>::max();
+ };
+
+ explicit PidController(const Args& args);
+
+ /// Reset the controller internal state: useful when the environment has
+ /// changed significantly
+ void Reset() {
+ last_error_ = 0.0;
+ last_dc_dt_ = 0.0;
+ error_integral_ = 0.0;
+ }
+
+ /// Update the controller: given a current error estimate, and the time since
+ /// the last update, returns a new control value
+ double Update(double error, double dt);
+
+ /// Returns the last control value calculated
+ double last_control_value() const { return last_control_value_; }
+
+ /// Returns the current error integral (mostly for testing)
+ double error_integral() const { return error_integral_; }
+
+ private:
+ double last_error_ = 0.0;
+ double error_integral_ = 0.0;
+ double last_control_value_;
+ double last_dc_dt_ = 0.0;
+ const Args args_;
+};
+
+} // namespace grpc_core
+
#endif /* GRPC_CORE_LIB_TRANSPORT_PID_CONTROLLER_H */
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 e027c00d390..2408c138f20 100644
--- a/contrib/libs/grpc/src/core/lib/transport/static_metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/static_metadata.cc
@@ -1,54 +1,54 @@
-/*
- * 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.
- */
-
-/*
- * WARNING: Auto-generated code.
- *
- * To make changes to this file, change
- * tools/codegen/core/gen_static_metadata.py, and then re-run it.
- *
- * See metadata.h for an explanation of the interface here, and metadata.cc for
- * an explanation of what's going on.
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/transport/static_metadata.h"
-
-#include "src/core/lib/slice/slice_internal.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.
+ */
+
+/*
+ * WARNING: Auto-generated code.
+ *
+ * To make changes to this file, change
+ * tools/codegen/core/gen_static_metadata.py, and then re-run it.
+ *
+ * See metadata.h for an explanation of the interface here, and metadata.cc for
+ * an explanation of what's going on.
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/lib/transport/static_metadata.h"
+
+#include "src/core/lib/slice/slice_internal.h"
+
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,
- 115, 115, 97, 103, 101, 103, 114, 112, 99, 45, 115, 116, 97, 116, 117,
- 115, 103, 114, 112, 99, 45, 112, 97, 121, 108, 111, 97, 100, 45, 98,
- 105, 110, 103, 114, 112, 99, 45, 101, 110, 99, 111, 100, 105, 110, 103,
- 103, 114, 112, 99, 45, 97, 99, 99, 101, 112, 116, 45, 101, 110, 99,
- 111, 100, 105, 110, 103, 103, 114, 112, 99, 45, 115, 101, 114, 118, 101,
- 114, 45, 115, 116, 97, 116, 115, 45, 98, 105, 110, 103, 114, 112, 99,
- 45, 116, 97, 103, 115, 45, 98, 105, 110, 103, 114, 112, 99, 45, 116,
- 114, 97, 99, 101, 45, 98, 105, 110, 99, 111, 110, 116, 101, 110, 116,
- 45, 116, 121, 112, 101, 99, 111, 110, 116, 101, 110, 116, 45, 101, 110,
- 99, 111, 100, 105, 110, 103, 97, 99, 99, 101, 112, 116, 45, 101, 110,
- 99, 111, 100, 105, 110, 103, 103, 114, 112, 99, 45, 105, 110, 116, 101,
- 114, 110, 97, 108, 45, 101, 110, 99, 111, 100, 105, 110, 103, 45, 114,
- 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,
+ 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,
+ 115, 115, 97, 103, 101, 103, 114, 112, 99, 45, 115, 116, 97, 116, 117,
+ 115, 103, 114, 112, 99, 45, 112, 97, 121, 108, 111, 97, 100, 45, 98,
+ 105, 110, 103, 114, 112, 99, 45, 101, 110, 99, 111, 100, 105, 110, 103,
+ 103, 114, 112, 99, 45, 97, 99, 99, 101, 112, 116, 45, 101, 110, 99,
+ 111, 100, 105, 110, 103, 103, 114, 112, 99, 45, 115, 101, 114, 118, 101,
+ 114, 45, 115, 116, 97, 116, 115, 45, 98, 105, 110, 103, 114, 112, 99,
+ 45, 116, 97, 103, 115, 45, 98, 105, 110, 103, 114, 112, 99, 45, 116,
+ 114, 97, 99, 101, 45, 98, 105, 110, 99, 111, 110, 116, 101, 110, 116,
+ 45, 116, 121, 112, 101, 99, 111, 110, 116, 101, 110, 116, 45, 101, 110,
+ 99, 111, 100, 105, 110, 103, 97, 99, 99, 101, 112, 116, 45, 101, 110,
+ 99, 111, 100, 105, 110, 103, 103, 114, 112, 99, 45, 105, 110, 116, 101,
+ 114, 110, 97, 108, 45, 101, 110, 99, 111, 100, 105, 110, 103, 45, 114,
+ 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,
@@ -130,9 +130,9 @@ static constexpr uint8_t g_bytes[] = {
101, 110, 116, 105, 116, 121, 44, 103, 122, 105, 112, 100, 101, 102, 108,
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;
-
+
namespace grpc_core {
struct StaticMetadataCtx {
#ifndef NDEBUG
@@ -1151,9 +1151,9 @@ struct StaticMetadataCtx {
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;
@@ -1188,32 +1188,32 @@ void grpc_destroy_static_metadata_ctx(void) {
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,
+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};
-
-static const int8_t elems_r[] = {
+
+static const int8_t elems_r[] = {
15, 10, -8, 0, 2, -43, -83, -44, 0, 4, -8, 0, 0, 0, 10, 0, -7, 0,
0, 3, 3, 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, -68, 0, -53, -56, -53, -77, 0, 30, 29, 28, 27, 26, 25, 24, 35, 22,
21, 20, 19, 18, 17, 16, 15, 16, 16, 16, 15, 14, 13, 12, 11, 10, 9, 8,
7, 6, 5, 4, 3, 2, 3, 2, 2, 6, 0, 0, 0, 0, 0, 0, -7, 0};
-static uint32_t elems_phash(uint32_t i) {
+static uint32_t elems_phash(uint32_t i) {
i -= 45;
uint32_t x = i % 108;
uint32_t y = i / 108;
- uint32_t h = x;
- if (y < GPR_ARRAY_SIZE(elems_r)) {
- uint32_t delta = (uint32_t)elems_r[y];
- h += delta;
- }
- return h;
-}
-
-static const uint16_t elem_keys[] = {
+ uint32_t h = x;
+ if (y < GPR_ARRAY_SIZE(elems_r)) {
+ uint32_t delta = (uint32_t)elems_r[y];
+ h += delta;
+ }
+ return h;
+}
+
+static const uint16_t elem_keys[] = {
269, 270, 271, 272, 273, 274, 275, 1140, 1141, 1789, 153,
154, 487, 488, 1679, 45, 46, 1030, 1031, 795, 796, 1801,
1569, 651, 869, 2119, 1691, 2229, 6189, 6739, 6849, 6959, 7069,
@@ -1223,27 +1223,27 @@ static const uint16_t elem_keys[] = {
10369, 1200, 543, 10479, 10589, 214, 10699, 1206, 1207, 1208, 1209,
1090, 10809, 11579, 1860, 0, 0, 0, 0, 1750, 0, 1867,
0, 0, 359, 0, 0, 0, 0, 1642};
-static const uint8_t elem_idxs[] = {
+static const uint8_t elem_idxs[] = {
7, 8, 9, 10, 11, 12, 13, 76, 78, 71, 1, 2, 5, 6, 25, 3,
4, 66, 65, 62, 63, 83, 30, 67, 61, 57, 73, 37, 14, 19, 20, 21,
22, 23, 24, 26, 27, 15, 29, 31, 32, 33, 34, 35, 36, 38, 17, 16,
39, 28, 40, 18, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
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) {
- if (a == -1 || b == -1) return GRPC_MDNULL;
+ 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
+ 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_MDNULL;
-}
-
+ : 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_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 5d844af558c..416d71ee52e 100644
--- a/contrib/libs/grpc/src/core/lib/transport/static_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/transport/static_metadata.h
@@ -1,17 +1,17 @@
/*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
/*
@@ -20,15 +20,15 @@
* To make changes to this file, change
* tools/codegen/core/gen_static_metadata.py, and then re-run it.
*
- * See metadata.h for an explanation of the interface here, and metadata.cc for
+ * See metadata.h for an explanation of the interface here, and metadata.cc for
* an explanation of what's going on.
*/
#ifndef GRPC_CORE_LIB_TRANSPORT_STATIC_METADATA_H
#define GRPC_CORE_LIB_TRANSPORT_STATIC_METADATA_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include <cstdint>
#include "src/core/lib/transport/metadata.h"
@@ -54,80 +54,80 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() {
return grpc_core::g_static_metadata_slice_table;
}
-/* ":path" */
+/* ":path" */
#define GRPC_MDSTR_PATH (grpc_static_slice_table()[0])
-/* ":method" */
+/* ":method" */
#define GRPC_MDSTR_METHOD (grpc_static_slice_table()[1])
-/* ":status" */
+/* ":status" */
#define GRPC_MDSTR_STATUS (grpc_static_slice_table()[2])
-/* ":authority" */
+/* ":authority" */
#define GRPC_MDSTR_AUTHORITY (grpc_static_slice_table()[3])
-/* ":scheme" */
+/* ":scheme" */
#define GRPC_MDSTR_SCHEME (grpc_static_slice_table()[4])
-/* "te" */
+/* "te" */
#define GRPC_MDSTR_TE (grpc_static_slice_table()[5])
-/* "grpc-message" */
+/* "grpc-message" */
#define GRPC_MDSTR_GRPC_MESSAGE (grpc_static_slice_table()[6])
-/* "grpc-status" */
+/* "grpc-status" */
#define GRPC_MDSTR_GRPC_STATUS (grpc_static_slice_table()[7])
-/* "grpc-payload-bin" */
+/* "grpc-payload-bin" */
#define GRPC_MDSTR_GRPC_PAYLOAD_BIN (grpc_static_slice_table()[8])
-/* "grpc-encoding" */
+/* "grpc-encoding" */
#define GRPC_MDSTR_GRPC_ENCODING (grpc_static_slice_table()[9])
-/* "grpc-accept-encoding" */
+/* "grpc-accept-encoding" */
#define GRPC_MDSTR_GRPC_ACCEPT_ENCODING (grpc_static_slice_table()[10])
-/* "grpc-server-stats-bin" */
+/* "grpc-server-stats-bin" */
#define GRPC_MDSTR_GRPC_SERVER_STATS_BIN (grpc_static_slice_table()[11])
-/* "grpc-tags-bin" */
+/* "grpc-tags-bin" */
#define GRPC_MDSTR_GRPC_TAGS_BIN (grpc_static_slice_table()[12])
-/* "grpc-trace-bin" */
+/* "grpc-trace-bin" */
#define GRPC_MDSTR_GRPC_TRACE_BIN (grpc_static_slice_table()[13])
-/* "content-type" */
+/* "content-type" */
#define GRPC_MDSTR_CONTENT_TYPE (grpc_static_slice_table()[14])
-/* "content-encoding" */
+/* "content-encoding" */
#define GRPC_MDSTR_CONTENT_ENCODING (grpc_static_slice_table()[15])
-/* "accept-encoding" */
+/* "accept-encoding" */
#define GRPC_MDSTR_ACCEPT_ENCODING (grpc_static_slice_table()[16])
-/* "grpc-internal-encoding-request" */
+/* "grpc-internal-encoding-request" */
#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-internal-stream-encoding-request" */
+#define GRPC_MDSTR_GRPC_INTERNAL_STREAM_ENCODING_REQUEST \
(grpc_static_slice_table()[18])
-/* "user-agent" */
+/* "user-agent" */
#define GRPC_MDSTR_USER_AGENT (grpc_static_slice_table()[19])
-/* "host" */
+/* "host" */
#define GRPC_MDSTR_HOST (grpc_static_slice_table()[20])
-/* "grpc-previous-rpc-attempts" */
+/* "grpc-previous-rpc-attempts" */
#define GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS (grpc_static_slice_table()[21])
-/* "grpc-retry-pushback-ms" */
+/* "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])
-/* "grpc-timeout" */
+/* "grpc-timeout" */
#define GRPC_MDSTR_GRPC_TIMEOUT (grpc_static_slice_table()[24])
/* "1" */
#define GRPC_MDSTR_1 (grpc_static_slice_table()[25])
/* "2" */
#define GRPC_MDSTR_2 (grpc_static_slice_table()[26])
-/* "3" */
+/* "3" */
#define GRPC_MDSTR_3 (grpc_static_slice_table()[27])
-/* "4" */
+/* "4" */
#define GRPC_MDSTR_4 (grpc_static_slice_table()[28])
-/* "" */
+/* "" */
#define GRPC_MDSTR_EMPTY (grpc_static_slice_table()[29])
-/* "grpc.wait_for_ready" */
+/* "grpc.wait_for_ready" */
#define GRPC_MDSTR_GRPC_DOT_WAIT_FOR_READY (grpc_static_slice_table()[30])
-/* "grpc.timeout" */
+/* "grpc.timeout" */
#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.max_request_message_bytes" */
+#define GRPC_MDSTR_GRPC_DOT_MAX_REQUEST_MESSAGE_BYTES \
(grpc_static_slice_table()[32])
-/* "grpc.max_response_message_bytes" */
-#define GRPC_MDSTR_GRPC_DOT_MAX_RESPONSE_MESSAGE_BYTES \
+/* "grpc.max_response_message_bytes" */
+#define GRPC_MDSTR_GRPC_DOT_MAX_RESPONSE_MESSAGE_BYTES \
(grpc_static_slice_table()[33])
-/* "/grpc.lb.v1.LoadBalancer/BalanceLoad" */
-#define GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD \
+/* "/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 \
@@ -146,23 +146,23 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() {
*/
#define GRPC_MDSTR_SLASH_ENVOY_DOT_SERVICE_DOT_DISCOVERY_DOT_V3_DOT_AGGREGATEDDISCOVERYSERVICE_SLASH_STREAMAGGREGATEDRESOURCES \
(grpc_static_slice_table()[39])
-/* "deflate" */
+/* "deflate" */
#define GRPC_MDSTR_DEFLATE (grpc_static_slice_table()[40])
-/* "gzip" */
+/* "gzip" */
#define GRPC_MDSTR_GZIP (grpc_static_slice_table()[41])
-/* "stream/gzip" */
+/* "stream/gzip" */
#define GRPC_MDSTR_STREAM_SLASH_GZIP (grpc_static_slice_table()[42])
/* "GET" */
#define GRPC_MDSTR_GET (grpc_static_slice_table()[43])
-/* "POST" */
+/* "POST" */
#define GRPC_MDSTR_POST (grpc_static_slice_table()[44])
/* "/" */
#define GRPC_MDSTR_SLASH (grpc_static_slice_table()[45])
/* "/index.html" */
#define GRPC_MDSTR_SLASH_INDEX_DOT_HTML (grpc_static_slice_table()[46])
-/* "http" */
+/* "http" */
#define GRPC_MDSTR_HTTP (grpc_static_slice_table()[47])
-/* "https" */
+/* "https" */
#define GRPC_MDSTR_HTTPS (grpc_static_slice_table()[48])
/* "200" */
#define GRPC_MDSTR_200 (grpc_static_slice_table()[49])
@@ -180,13 +180,13 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() {
#define GRPC_MDSTR_500 (grpc_static_slice_table()[55])
/* "accept-charset" */
#define GRPC_MDSTR_ACCEPT_CHARSET (grpc_static_slice_table()[56])
-/* "gzip, deflate" */
+/* "gzip, deflate" */
#define GRPC_MDSTR_GZIP_COMMA_DEFLATE (grpc_static_slice_table()[57])
/* "accept-language" */
#define GRPC_MDSTR_ACCEPT_LANGUAGE (grpc_static_slice_table()[58])
/* "accept-ranges" */
#define GRPC_MDSTR_ACCEPT_RANGES (grpc_static_slice_table()[59])
-/* "accept" */
+/* "accept" */
#define GRPC_MDSTR_ACCEPT (grpc_static_slice_table()[60])
/* "access-control-allow-origin" */
#define GRPC_MDSTR_ACCESS_CONTROL_ALLOW_ORIGIN (grpc_static_slice_table()[61])
@@ -278,14 +278,14 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() {
#define GRPC_MDSTR_PUT (grpc_static_slice_table()[104])
/* "lb-cost-bin" */
#define GRPC_MDSTR_LB_COST_BIN (grpc_static_slice_table()[105])
-/* "identity,deflate" */
+/* "identity,deflate" */
#define GRPC_MDSTR_IDENTITY_COMMA_DEFLATE (grpc_static_slice_table()[106])
-/* "identity,gzip" */
+/* "identity,gzip" */
#define GRPC_MDSTR_IDENTITY_COMMA_GZIP (grpc_static_slice_table()[107])
-/* "deflate,gzip" */
+/* "deflate,gzip" */
#define GRPC_MDSTR_DEFLATE_COMMA_GZIP (grpc_static_slice_table()[108])
-/* "identity,deflate,gzip" */
-#define GRPC_MDSTR_IDENTITY_COMMA_DEFLATE_COMMA_GZIP \
+/* "identity,deflate,gzip" */
+#define GRPC_MDSTR_IDENTITY_COMMA_DEFLATE_COMMA_GZIP \
(grpc_static_slice_table()[109])
namespace grpc_core {
@@ -299,14 +299,14 @@ inline grpc_core::StaticSliceRefcount* grpc_static_metadata_refcounts() {
return grpc_core::g_static_metadata_slice_refcounts;
}
-#define GRPC_IS_STATIC_METADATA_STRING(slice) \
- ((slice).refcount != NULL && \
+#define GRPC_IS_STATIC_METADATA_STRING(slice) \
+ ((slice).refcount != NULL && \
(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 {
@@ -342,19 +342,19 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
#define GRPC_MDELEM_SCHEME_HTTP (grpc_static_mdelem_manifested()[5])
/* ":scheme": "https" */
#define GRPC_MDELEM_SCHEME_HTTPS (grpc_static_mdelem_manifested()[6])
-/* ":status": "200" */
+/* ":status": "200" */
#define GRPC_MDELEM_STATUS_200 (grpc_static_mdelem_manifested()[7])
-/* ":status": "204" */
+/* ":status": "204" */
#define GRPC_MDELEM_STATUS_204 (grpc_static_mdelem_manifested()[8])
-/* ":status": "206" */
+/* ":status": "206" */
#define GRPC_MDELEM_STATUS_206 (grpc_static_mdelem_manifested()[9])
-/* ":status": "304" */
+/* ":status": "304" */
#define GRPC_MDELEM_STATUS_304 (grpc_static_mdelem_manifested()[10])
-/* ":status": "400" */
+/* ":status": "400" */
#define GRPC_MDELEM_STATUS_400 (grpc_static_mdelem_manifested()[11])
/* ":status": "404" */
#define GRPC_MDELEM_STATUS_404 (grpc_static_mdelem_manifested()[12])
-/* ":status": "500" */
+/* ":status": "500" */
#define GRPC_MDELEM_STATUS_500 (grpc_static_mdelem_manifested()[13])
/* "accept-charset": "" */
#define GRPC_MDELEM_ACCEPT_CHARSET_EMPTY (grpc_static_mdelem_manifested()[14])
@@ -365,7 +365,7 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
#define GRPC_MDELEM_ACCEPT_LANGUAGE_EMPTY (grpc_static_mdelem_manifested()[16])
/* "accept-ranges": "" */
#define GRPC_MDELEM_ACCEPT_RANGES_EMPTY (grpc_static_mdelem_manifested()[17])
-/* "accept": "" */
+/* "accept": "" */
#define GRPC_MDELEM_ACCEPT_EMPTY (grpc_static_mdelem_manifested()[18])
/* "access-control-allow-origin": "" */
#define GRPC_MDELEM_ACCESS_CONTROL_ALLOW_ORIGIN_EMPTY \
@@ -379,7 +379,7 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
/* "cache-control": "" */
#define GRPC_MDELEM_CACHE_CONTROL_EMPTY (grpc_static_mdelem_manifested()[23])
/* "content-disposition": "" */
-#define GRPC_MDELEM_CONTENT_DISPOSITION_EMPTY \
+#define GRPC_MDELEM_CONTENT_DISPOSITION_EMPTY \
(grpc_static_mdelem_manifested()[24])
/* "content-encoding": "" */
#define GRPC_MDELEM_CONTENT_ENCODING_EMPTY (grpc_static_mdelem_manifested()[25])
@@ -410,14 +410,14 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
/* "if-match": "" */
#define GRPC_MDELEM_IF_MATCH_EMPTY (grpc_static_mdelem_manifested()[38])
/* "if-modified-since": "" */
-#define GRPC_MDELEM_IF_MODIFIED_SINCE_EMPTY \
+#define GRPC_MDELEM_IF_MODIFIED_SINCE_EMPTY \
(grpc_static_mdelem_manifested()[39])
/* "if-none-match": "" */
#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])
/* "if-unmodified-since": "" */
-#define GRPC_MDELEM_IF_UNMODIFIED_SINCE_EMPTY \
+#define GRPC_MDELEM_IF_UNMODIFIED_SINCE_EMPTY \
(grpc_static_mdelem_manifested()[42])
/* "last-modified": "" */
#define GRPC_MDELEM_LAST_MODIFIED_EMPTY (grpc_static_mdelem_manifested()[43])
@@ -428,10 +428,10 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
/* "max-forwards": "" */
#define GRPC_MDELEM_MAX_FORWARDS_EMPTY (grpc_static_mdelem_manifested()[46])
/* "proxy-authenticate": "" */
-#define GRPC_MDELEM_PROXY_AUTHENTICATE_EMPTY \
+#define GRPC_MDELEM_PROXY_AUTHENTICATE_EMPTY \
(grpc_static_mdelem_manifested()[47])
/* "proxy-authorization": "" */
-#define GRPC_MDELEM_PROXY_AUTHORIZATION_EMPTY \
+#define GRPC_MDELEM_PROXY_AUTHORIZATION_EMPTY \
(grpc_static_mdelem_manifested()[48])
/* "range": "" */
#define GRPC_MDELEM_RANGE_EMPTY (grpc_static_mdelem_manifested()[49])
@@ -449,7 +449,7 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
#define GRPC_MDELEM_STRICT_TRANSPORT_SECURITY_EMPTY \
(grpc_static_mdelem_manifested()[55])
/* "transfer-encoding": "" */
-#define GRPC_MDELEM_TRANSFER_ENCODING_EMPTY \
+#define GRPC_MDELEM_TRANSFER_ENCODING_EMPTY \
(grpc_static_mdelem_manifested()[56])
/* "user-agent": "" */
#define GRPC_MDELEM_USER_AGENT_EMPTY (grpc_static_mdelem_manifested()[57])
@@ -489,95 +489,95 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT];
#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])
-/* "grpc-accept-encoding": "identity" */
-#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY \
+/* "grpc-accept-encoding": "identity" */
+#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY \
(grpc_static_mdelem_manifested()[75])
-/* "grpc-accept-encoding": "deflate" */
-#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE \
+/* "grpc-accept-encoding": "deflate" */
+#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE \
(grpc_static_mdelem_manifested()[76])
-/* "grpc-accept-encoding": "identity,deflate" */
-#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE \
+/* "grpc-accept-encoding": "identity,deflate" */
+#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE \
(grpc_static_mdelem_manifested()[77])
-/* "grpc-accept-encoding": "gzip" */
-#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_GZIP \
+/* "grpc-accept-encoding": "gzip" */
+#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_GZIP \
(grpc_static_mdelem_manifested()[78])
-/* "grpc-accept-encoding": "identity,gzip" */
-#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP \
+/* "grpc-accept-encoding": "identity,gzip" */
+#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP \
(grpc_static_mdelem_manifested()[79])
-/* "grpc-accept-encoding": "deflate,gzip" */
-#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE_COMMA_GZIP \
+/* "grpc-accept-encoding": "deflate,gzip" */
+#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_DEFLATE_COMMA_GZIP \
(grpc_static_mdelem_manifested()[80])
-/* "grpc-accept-encoding": "identity,deflate,gzip" */
-#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP \
+/* "grpc-accept-encoding": "identity,deflate,gzip" */
+#define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP \
(grpc_static_mdelem_manifested()[81])
-/* "accept-encoding": "identity" */
-#define GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY \
+/* "accept-encoding": "identity" */
+#define GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY \
(grpc_static_mdelem_manifested()[82])
-/* "accept-encoding": "gzip" */
+/* "accept-encoding": "gzip" */
#define GRPC_MDELEM_ACCEPT_ENCODING_GZIP (grpc_static_mdelem_manifested()[83])
-/* "accept-encoding": "identity,gzip" */
-#define GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP \
+/* "accept-encoding": "identity,gzip" */
+#define GRPC_MDELEM_ACCEPT_ENCODING_IDENTITY_COMMA_GZIP \
(grpc_static_mdelem_manifested()[84])
grpc_mdelem grpc_static_mdelem_for_static_strings(intptr_t a, intptr_t b);
-typedef enum {
- GRPC_BATCH_PATH,
- GRPC_BATCH_METHOD,
- GRPC_BATCH_STATUS,
- GRPC_BATCH_AUTHORITY,
- GRPC_BATCH_SCHEME,
- GRPC_BATCH_TE,
- GRPC_BATCH_GRPC_MESSAGE,
- GRPC_BATCH_GRPC_STATUS,
- GRPC_BATCH_GRPC_PAYLOAD_BIN,
- GRPC_BATCH_GRPC_ENCODING,
- GRPC_BATCH_GRPC_ACCEPT_ENCODING,
- GRPC_BATCH_GRPC_SERVER_STATS_BIN,
- GRPC_BATCH_GRPC_TAGS_BIN,
- GRPC_BATCH_GRPC_TRACE_BIN,
- GRPC_BATCH_CONTENT_TYPE,
- GRPC_BATCH_CONTENT_ENCODING,
- GRPC_BATCH_ACCEPT_ENCODING,
- GRPC_BATCH_GRPC_INTERNAL_ENCODING_REQUEST,
- GRPC_BATCH_GRPC_INTERNAL_STREAM_ENCODING_REQUEST,
- GRPC_BATCH_USER_AGENT,
- GRPC_BATCH_HOST,
- GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS,
- GRPC_BATCH_GRPC_RETRY_PUSHBACK_MS,
+typedef enum {
+ GRPC_BATCH_PATH,
+ GRPC_BATCH_METHOD,
+ GRPC_BATCH_STATUS,
+ GRPC_BATCH_AUTHORITY,
+ GRPC_BATCH_SCHEME,
+ GRPC_BATCH_TE,
+ GRPC_BATCH_GRPC_MESSAGE,
+ GRPC_BATCH_GRPC_STATUS,
+ GRPC_BATCH_GRPC_PAYLOAD_BIN,
+ GRPC_BATCH_GRPC_ENCODING,
+ GRPC_BATCH_GRPC_ACCEPT_ENCODING,
+ GRPC_BATCH_GRPC_SERVER_STATS_BIN,
+ GRPC_BATCH_GRPC_TAGS_BIN,
+ GRPC_BATCH_GRPC_TRACE_BIN,
+ GRPC_BATCH_CONTENT_TYPE,
+ GRPC_BATCH_CONTENT_ENCODING,
+ GRPC_BATCH_ACCEPT_ENCODING,
+ GRPC_BATCH_GRPC_INTERNAL_ENCODING_REQUEST,
+ GRPC_BATCH_GRPC_INTERNAL_STREAM_ENCODING_REQUEST,
+ GRPC_BATCH_USER_AGENT,
+ GRPC_BATCH_HOST,
+ GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS,
+ GRPC_BATCH_GRPC_RETRY_PUSHBACK_MS,
GRPC_BATCH_X_ENDPOINT_LOAD_METRICS_BIN,
- GRPC_BATCH_CALLOUTS_COUNT
-} grpc_metadata_batch_callouts_index;
-
-typedef union {
- struct grpc_linked_mdelem* array[GRPC_BATCH_CALLOUTS_COUNT];
- struct {
- struct grpc_linked_mdelem* path;
- struct grpc_linked_mdelem* method;
- struct grpc_linked_mdelem* status;
- struct grpc_linked_mdelem* authority;
- struct grpc_linked_mdelem* scheme;
- struct grpc_linked_mdelem* te;
- struct grpc_linked_mdelem* grpc_message;
- struct grpc_linked_mdelem* grpc_status;
- struct grpc_linked_mdelem* grpc_payload_bin;
- struct grpc_linked_mdelem* grpc_encoding;
- struct grpc_linked_mdelem* grpc_accept_encoding;
- struct grpc_linked_mdelem* grpc_server_stats_bin;
- struct grpc_linked_mdelem* grpc_tags_bin;
- struct grpc_linked_mdelem* grpc_trace_bin;
- struct grpc_linked_mdelem* content_type;
- struct grpc_linked_mdelem* content_encoding;
- struct grpc_linked_mdelem* accept_encoding;
- struct grpc_linked_mdelem* grpc_internal_encoding_request;
- struct grpc_linked_mdelem* grpc_internal_stream_encoding_request;
- struct grpc_linked_mdelem* user_agent;
- struct grpc_linked_mdelem* host;
- struct grpc_linked_mdelem* grpc_previous_rpc_attempts;
- struct grpc_linked_mdelem* grpc_retry_pushback_ms;
+ GRPC_BATCH_CALLOUTS_COUNT
+} grpc_metadata_batch_callouts_index;
+
+typedef union {
+ struct grpc_linked_mdelem* array[GRPC_BATCH_CALLOUTS_COUNT];
+ struct {
+ struct grpc_linked_mdelem* path;
+ struct grpc_linked_mdelem* method;
+ struct grpc_linked_mdelem* status;
+ struct grpc_linked_mdelem* authority;
+ struct grpc_linked_mdelem* scheme;
+ struct grpc_linked_mdelem* te;
+ struct grpc_linked_mdelem* grpc_message;
+ struct grpc_linked_mdelem* grpc_status;
+ struct grpc_linked_mdelem* grpc_payload_bin;
+ struct grpc_linked_mdelem* grpc_encoding;
+ struct grpc_linked_mdelem* grpc_accept_encoding;
+ struct grpc_linked_mdelem* grpc_server_stats_bin;
+ struct grpc_linked_mdelem* grpc_tags_bin;
+ struct grpc_linked_mdelem* grpc_trace_bin;
+ struct grpc_linked_mdelem* content_type;
+ struct grpc_linked_mdelem* content_encoding;
+ struct grpc_linked_mdelem* accept_encoding;
+ struct grpc_linked_mdelem* grpc_internal_encoding_request;
+ struct grpc_linked_mdelem* grpc_internal_stream_encoding_request;
+ struct grpc_linked_mdelem* user_agent;
+ 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;
- } named;
-} grpc_metadata_batch_callouts;
-
+ } named;
+} grpc_metadata_batch_callouts;
+
#define GRPC_BATCH_INDEX_OF(slice) \
(GRPC_IS_STATIC_METADATA_STRING((slice)) && \
reinterpret_cast<grpc_core::StaticSliceRefcount*>((slice).refcount) \
@@ -586,19 +586,19 @@ typedef union {
reinterpret_cast<grpc_core::StaticSliceRefcount*>( \
(slice).refcount) \
->index) \
- : GRPC_BATCH_CALLOUTS_COUNT)
-
+ : 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))
-
-extern const uint8_t grpc_static_accept_stream_encoding_metadata[4];
-#define GRPC_MDELEM_ACCEPT_STREAM_ENCODING_FOR_ALGORITHMS(algs) \
+
+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_MDELEM_STORAGE_STATIC))
+ 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 46c6cd8c3b0..7fa8670d4da 100644
--- a/contrib/libs/grpc/src/core/lib/transport/status_conversion.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/status_conversion.cc
@@ -1,92 +1,92 @@
-/*
- *
- * 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/transport/status_conversion.h"
-
-grpc_http2_error_code grpc_status_to_http2_error(grpc_status_code status) {
- switch (status) {
- case GRPC_STATUS_OK:
- return GRPC_HTTP2_NO_ERROR;
- case GRPC_STATUS_CANCELLED:
- return GRPC_HTTP2_CANCEL;
- case GRPC_STATUS_DEADLINE_EXCEEDED:
- return GRPC_HTTP2_CANCEL;
- case GRPC_STATUS_RESOURCE_EXHAUSTED:
- return GRPC_HTTP2_ENHANCE_YOUR_CALM;
- case GRPC_STATUS_PERMISSION_DENIED:
- return GRPC_HTTP2_INADEQUATE_SECURITY;
- case GRPC_STATUS_UNAVAILABLE:
- return GRPC_HTTP2_REFUSED_STREAM;
- default:
- return GRPC_HTTP2_INTERNAL_ERROR;
- }
-}
-
-grpc_status_code grpc_http2_error_to_grpc_status(grpc_http2_error_code error,
- grpc_millis deadline) {
- switch (error) {
- case GRPC_HTTP2_NO_ERROR:
- /* should never be received */
+/*
+ *
+ * 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/transport/status_conversion.h"
+
+grpc_http2_error_code grpc_status_to_http2_error(grpc_status_code status) {
+ switch (status) {
+ case GRPC_STATUS_OK:
+ return GRPC_HTTP2_NO_ERROR;
+ case GRPC_STATUS_CANCELLED:
+ return GRPC_HTTP2_CANCEL;
+ case GRPC_STATUS_DEADLINE_EXCEEDED:
+ return GRPC_HTTP2_CANCEL;
+ case GRPC_STATUS_RESOURCE_EXHAUSTED:
+ return GRPC_HTTP2_ENHANCE_YOUR_CALM;
+ case GRPC_STATUS_PERMISSION_DENIED:
+ return GRPC_HTTP2_INADEQUATE_SECURITY;
+ case GRPC_STATUS_UNAVAILABLE:
+ return GRPC_HTTP2_REFUSED_STREAM;
+ default:
+ return GRPC_HTTP2_INTERNAL_ERROR;
+ }
+}
+
+grpc_status_code grpc_http2_error_to_grpc_status(grpc_http2_error_code error,
+ grpc_millis deadline) {
+ switch (error) {
+ case GRPC_HTTP2_NO_ERROR:
+ /* should never be received */
+ return GRPC_STATUS_INTERNAL;
+ case GRPC_HTTP2_CANCEL:
+ /* http2 cancel translates to STATUS_CANCELLED iff deadline hasn't been
+ * exceeded */
+ return grpc_core::ExecCtx::Get()->Now() > deadline
+ ? GRPC_STATUS_DEADLINE_EXCEEDED
+ : GRPC_STATUS_CANCELLED;
+ case GRPC_HTTP2_ENHANCE_YOUR_CALM:
+ return GRPC_STATUS_RESOURCE_EXHAUSTED;
+ case GRPC_HTTP2_INADEQUATE_SECURITY:
+ return GRPC_STATUS_PERMISSION_DENIED;
+ case GRPC_HTTP2_REFUSED_STREAM:
+ return GRPC_STATUS_UNAVAILABLE;
+ default:
+ return GRPC_STATUS_INTERNAL;
+ }
+}
+
+grpc_status_code grpc_http2_status_to_grpc_status(int status) {
+ switch (status) {
+ /* these HTTP2 status codes are called out explicitly in status.proto */
+ case 200:
+ return GRPC_STATUS_OK;
+ case 400:
return GRPC_STATUS_INTERNAL;
- case GRPC_HTTP2_CANCEL:
- /* http2 cancel translates to STATUS_CANCELLED iff deadline hasn't been
- * exceeded */
- return grpc_core::ExecCtx::Get()->Now() > deadline
- ? GRPC_STATUS_DEADLINE_EXCEEDED
- : GRPC_STATUS_CANCELLED;
- case GRPC_HTTP2_ENHANCE_YOUR_CALM:
- return GRPC_STATUS_RESOURCE_EXHAUSTED;
- case GRPC_HTTP2_INADEQUATE_SECURITY:
- return GRPC_STATUS_PERMISSION_DENIED;
- case GRPC_HTTP2_REFUSED_STREAM:
- return GRPC_STATUS_UNAVAILABLE;
- default:
- return GRPC_STATUS_INTERNAL;
- }
-}
-
-grpc_status_code grpc_http2_status_to_grpc_status(int status) {
- switch (status) {
- /* these HTTP2 status codes are called out explicitly in status.proto */
- case 200:
- return GRPC_STATUS_OK;
- case 400:
- return GRPC_STATUS_INTERNAL;
- case 401:
- return GRPC_STATUS_UNAUTHENTICATED;
- case 403:
- return GRPC_STATUS_PERMISSION_DENIED;
- case 404:
+ case 401:
+ return GRPC_STATUS_UNAUTHENTICATED;
+ case 403:
+ return GRPC_STATUS_PERMISSION_DENIED;
+ case 404:
return GRPC_STATUS_UNIMPLEMENTED;
- case 429:
+ case 429:
return GRPC_STATUS_UNAVAILABLE;
case 502:
return GRPC_STATUS_UNAVAILABLE;
- case 503:
- return GRPC_STATUS_UNAVAILABLE;
- case 504:
+ case 503:
+ return GRPC_STATUS_UNAVAILABLE;
+ case 504:
return GRPC_STATUS_UNAVAILABLE;
- /* everything else is unknown */
- default:
- return GRPC_STATUS_UNKNOWN;
- }
-}
-
+ /* everything else is unknown */
+ default:
+ return GRPC_STATUS_UNKNOWN;
+ }
+}
+
int grpc_status_to_http2_status(grpc_status_code /*status*/) { return 200; }
diff --git a/contrib/libs/grpc/src/core/lib/transport/status_conversion.h b/contrib/libs/grpc/src/core/lib/transport/status_conversion.h
index 487f00c08b1..0a9f2558285 100644
--- a/contrib/libs/grpc/src/core/lib/transport/status_conversion.h
+++ b/contrib/libs/grpc/src/core/lib/transport/status_conversion.h
@@ -1,38 +1,38 @@
-/*
- *
- * 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_TRANSPORT_STATUS_CONVERSION_H
-#define GRPC_CORE_LIB_TRANSPORT_STATUS_CONVERSION_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/transport/http2_errors.h"
-
-/* Conversion of grpc status codes to http2 error codes (for RST_STREAM) */
-grpc_http2_error_code grpc_status_to_http2_error(grpc_status_code status);
-grpc_status_code grpc_http2_error_to_grpc_status(grpc_http2_error_code error,
- grpc_millis deadline);
-
-/* Conversion of HTTP status codes (:status) to grpc status codes */
-grpc_status_code grpc_http2_status_to_grpc_status(int status);
-int grpc_status_to_http2_status(grpc_status_code status);
-
-#endif /* GRPC_CORE_LIB_TRANSPORT_STATUS_CONVERSION_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_TRANSPORT_STATUS_CONVERSION_H
+#define GRPC_CORE_LIB_TRANSPORT_STATUS_CONVERSION_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/transport/http2_errors.h"
+
+/* Conversion of grpc status codes to http2 error codes (for RST_STREAM) */
+grpc_http2_error_code grpc_status_to_http2_error(grpc_status_code status);
+grpc_status_code grpc_http2_error_to_grpc_status(grpc_http2_error_code error,
+ grpc_millis deadline);
+
+/* Conversion of HTTP status codes (:status) to grpc status codes */
+grpc_status_code grpc_http2_status_to_grpc_status(int status);
+int grpc_status_to_http2_status(grpc_status_code status);
+
+#endif /* GRPC_CORE_LIB_TRANSPORT_STATUS_CONVERSION_H */
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 c83d6b0d2dc..c1fc68ea6e6 100644
--- a/contrib/libs/grpc/src/core/lib/transport/status_metadata.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/status_metadata.cc
@@ -1,57 +1,57 @@
-/*
- *
- * 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/transport/status_metadata.h"
-
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/transport/static_metadata.h"
-
-/* we offset status by a small amount when storing it into transport metadata
- as metadata cannot store a 0 value (which is used as OK for grpc_status_codes
- */
-#define STATUS_OFFSET 1
-
+/*
+ *
+ * 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/transport/status_metadata.h"
+
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/transport/static_metadata.h"
+
+/* we offset status by a small amount when storing it into transport metadata
+ as metadata cannot store a 0 value (which is used as OK for grpc_status_codes
+ */
+#define STATUS_OFFSET 1
+
static void destroy_status(void* /*ignored*/) {}
-
-grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md) {
+
+grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md) {
if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_0)) {
- return GRPC_STATUS_OK;
- }
+ return GRPC_STATUS_OK;
+ }
if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_1)) {
- return GRPC_STATUS_CANCELLED;
- }
+ return GRPC_STATUS_CANCELLED;
+ }
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);
- if (user_data != nullptr) {
- return static_cast<grpc_status_code>((intptr_t)user_data - STATUS_OFFSET);
- }
- uint32_t status;
- if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(md), &status)) {
- status = GRPC_STATUS_UNKNOWN; /* could not parse status code */
- }
- grpc_mdelem_set_user_data(
- md, destroy_status, (void*)static_cast<intptr_t>(status + STATUS_OFFSET));
- return static_cast<grpc_status_code>(status);
-}
+ return GRPC_STATUS_UNKNOWN;
+ }
+ void* user_data = grpc_mdelem_get_user_data(md, destroy_status);
+ if (user_data != nullptr) {
+ return static_cast<grpc_status_code>((intptr_t)user_data - STATUS_OFFSET);
+ }
+ uint32_t status;
+ if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(md), &status)) {
+ status = GRPC_STATUS_UNKNOWN; /* could not parse status code */
+ }
+ grpc_mdelem_set_user_data(
+ 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];
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 24022c0cf55..7ddcf3027c9 100644
--- a/contrib/libs/grpc/src/core/lib/transport/status_metadata.h
+++ b/contrib/libs/grpc/src/core/lib/transport/status_metadata.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_LIB_TRANSPORT_STATUS_METADATA_H
-#define GRPC_CORE_LIB_TRANSPORT_STATUS_METADATA_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/status.h>
-
-#include "src/core/lib/transport/metadata.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.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_TRANSPORT_STATUS_METADATA_H
+#define GRPC_CORE_LIB_TRANSPORT_STATUS_METADATA_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/status.h>
+
+#include "src/core/lib/transport/metadata.h"
#include "src/core/lib/transport/static_metadata.h"
-
-grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md);
-
+
+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.
@@ -45,4 +45,4 @@ inline grpc_mdelem grpc_get_reffed_status_elem(int status_code) {
return grpc_get_reffed_status_elem_slowpath(status_code);
}
-#endif /* GRPC_CORE_LIB_TRANSPORT_STATUS_METADATA_H */
+#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 26d4b4a426f..0c11692e551 100644
--- a/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.cc
@@ -1,151 +1,151 @@
-/*
- *
- * 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/transport/timeout_encoding.h"
-
-#include <stdio.h>
-#include <string.h>
-
-#include "src/core/lib/gpr/string.h"
-
-static int64_t round_up(int64_t x, int64_t divisor) {
- return (x / divisor + (x % divisor != 0)) * divisor;
-}
-
-/* round an integer up to the next value with three significant figures */
-static int64_t round_up_to_three_sig_figs(int64_t x) {
- if (x < 1000) return x;
- if (x < 10000) return round_up(x, 10);
- if (x < 100000) return round_up(x, 100);
- if (x < 1000000) return round_up(x, 1000);
- if (x < 10000000) return round_up(x, 10000);
- if (x < 100000000) return round_up(x, 100000);
- if (x < 1000000000) return round_up(x, 1000000);
- return round_up(x, 10000000);
-}
-
-/* encode our minimum viable timeout value */
-static void enc_tiny(char* buffer) { memcpy(buffer, "1n", 3); }
-
+/*
+ *
+ * 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/transport/timeout_encoding.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include "src/core/lib/gpr/string.h"
+
+static int64_t round_up(int64_t x, int64_t divisor) {
+ return (x / divisor + (x % divisor != 0)) * divisor;
+}
+
+/* round an integer up to the next value with three significant figures */
+static int64_t round_up_to_three_sig_figs(int64_t x) {
+ if (x < 1000) return x;
+ if (x < 10000) return round_up(x, 10);
+ if (x < 100000) return round_up(x, 100);
+ if (x < 1000000) return round_up(x, 1000);
+ if (x < 10000000) return round_up(x, 10000);
+ if (x < 100000000) return round_up(x, 100000);
+ if (x < 1000000000) return round_up(x, 1000000);
+ return round_up(x, 10000000);
+}
+
+/* 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); }
-static void enc_ext(char* buffer, int64_t value, char ext) {
- int n = int64_ttoa(value, buffer);
- buffer[n] = ext;
- buffer[n + 1] = 0;
-}
-
-static void enc_seconds(char* buffer, int64_t sec) {
+static void enc_ext(char* buffer, int64_t value, char ext) {
+ int n = int64_ttoa(value, buffer);
+ buffer[n] = ext;
+ buffer[n + 1] = 0;
+}
+
+static void enc_seconds(char* buffer, int64_t sec) {
sec = round_up_to_three_sig_figs(sec);
- if (sec % 3600 == 0) {
- enc_ext(buffer, sec / 3600, 'H');
- } else if (sec % 60 == 0) {
- enc_ext(buffer, sec / 60, 'M');
- } else {
- enc_ext(buffer, sec, 'S');
- }
-}
-
-static void enc_millis(char* buffer, int64_t x) {
- x = round_up_to_three_sig_figs(x);
- if (x < GPR_MS_PER_SEC) {
- enc_ext(buffer, x, 'm');
- } else {
- if (x % GPR_MS_PER_SEC == 0) {
- enc_seconds(buffer, x / GPR_MS_PER_SEC);
- } else {
- enc_ext(buffer, x, 'm');
- }
- }
-}
-
-void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer) {
+ if (sec % 3600 == 0) {
+ enc_ext(buffer, sec / 3600, 'H');
+ } else if (sec % 60 == 0) {
+ enc_ext(buffer, sec / 60, 'M');
+ } else {
+ enc_ext(buffer, sec, 'S');
+ }
+}
+
+static void enc_millis(char* buffer, int64_t x) {
+ x = round_up_to_three_sig_figs(x);
+ if (x < GPR_MS_PER_SEC) {
+ enc_ext(buffer, x, 'm');
+ } else {
+ if (x % GPR_MS_PER_SEC == 0) {
+ enc_seconds(buffer, x / GPR_MS_PER_SEC);
+ } else {
+ enc_ext(buffer, x, 'm');
+ }
+ }
+}
+
+void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer) {
const grpc_millis kMaxTimeout = 99999999000;
- if (timeout <= 0) {
- enc_tiny(buffer);
- } else if (timeout < 1000 * GPR_MS_PER_SEC) {
- enc_millis(buffer, timeout);
+ 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 {
- enc_seconds(buffer,
- timeout / GPR_MS_PER_SEC + (timeout % GPR_MS_PER_SEC != 0));
- }
-}
-
-static int is_all_whitespace(const char* p, const char* end) {
- while (p != end && *p == ' ') p++;
- return p == end;
-}
-
+ } else {
+ enc_seconds(buffer,
+ timeout / GPR_MS_PER_SEC + (timeout % GPR_MS_PER_SEC != 0));
+ }
+}
+
+static int is_all_whitespace(const char* p, const char* end) {
+ while (p != end && *p == ' ') p++;
+ return p == end;
+}
+
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);
- int have_digit = 0;
- /* skip whitespace */
- for (; p != end && *p == ' '; p++)
- ;
- /* decode numeric part */
- for (; p != end && *p >= '0' && *p <= '9'; p++) {
- int32_t digit = static_cast<int32_t>(*p - static_cast<uint8_t>('0'));
- have_digit = 1;
- /* spec allows max. 8 digits, but we allow values up to 1,000,000,000 */
- if (x >= (100 * 1000 * 1000)) {
- if (x != (100 * 1000 * 1000) || digit != 0) {
- *timeout = GRPC_MILLIS_INF_FUTURE;
- return 1;
- }
- }
- x = x * 10 + digit;
- }
- if (!have_digit) return 0;
- /* skip whitespace */
- for (; p != end && *p == ' '; p++)
- ;
- if (p == end) return 0;
- /* decode unit specifier */
- switch (*p) {
- case 'n':
- *timeout = x / GPR_NS_PER_MS + (x % GPR_NS_PER_MS != 0);
- break;
- case 'u':
- *timeout = x / GPR_US_PER_MS + (x % GPR_US_PER_MS != 0);
- break;
- case 'm':
- *timeout = x;
- break;
- case 'S':
- *timeout = x * GPR_MS_PER_SEC;
- break;
- case 'M':
- *timeout = x * 60 * GPR_MS_PER_SEC;
- break;
- case 'H':
- *timeout = x * 60 * 60 * GPR_MS_PER_SEC;
- break;
- default:
- return 0;
- }
- p++;
- return is_all_whitespace(reinterpret_cast<const char*>(p),
- reinterpret_cast<const char*>(end));
-}
+ grpc_millis x = 0;
+ const uint8_t* p = GRPC_SLICE_START_PTR(text);
+ const uint8_t* end = GRPC_SLICE_END_PTR(text);
+ int have_digit = 0;
+ /* skip whitespace */
+ for (; p != end && *p == ' '; p++)
+ ;
+ /* decode numeric part */
+ for (; p != end && *p >= '0' && *p <= '9'; p++) {
+ int32_t digit = static_cast<int32_t>(*p - static_cast<uint8_t>('0'));
+ have_digit = 1;
+ /* spec allows max. 8 digits, but we allow values up to 1,000,000,000 */
+ if (x >= (100 * 1000 * 1000)) {
+ if (x != (100 * 1000 * 1000) || digit != 0) {
+ *timeout = GRPC_MILLIS_INF_FUTURE;
+ return 1;
+ }
+ }
+ x = x * 10 + digit;
+ }
+ if (!have_digit) return 0;
+ /* skip whitespace */
+ for (; p != end && *p == ' '; p++)
+ ;
+ if (p == end) return 0;
+ /* decode unit specifier */
+ switch (*p) {
+ case 'n':
+ *timeout = x / GPR_NS_PER_MS + (x % GPR_NS_PER_MS != 0);
+ break;
+ case 'u':
+ *timeout = x / GPR_US_PER_MS + (x % GPR_US_PER_MS != 0);
+ break;
+ case 'm':
+ *timeout = x;
+ break;
+ case 'S':
+ *timeout = x * GPR_MS_PER_SEC;
+ break;
+ case 'M':
+ *timeout = x * 60 * GPR_MS_PER_SEC;
+ break;
+ case 'H':
+ *timeout = x * 60 * 60 * GPR_MS_PER_SEC;
+ break;
+ default:
+ return 0;
+ }
+ p++;
+ return is_all_whitespace(reinterpret_cast<const char*>(p),
+ reinterpret_cast<const char*>(end));
+}
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 c87ff39d491..8e04aee9d17 100644
--- a/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h
+++ b/contrib/libs/grpc/src/core/lib/transport/timeout_encoding.h
@@ -1,38 +1,38 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_TIMEOUT_ENCODING_H
#define GRPC_CORE_LIB_TRANSPORT_TIMEOUT_ENCODING_H
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.h>
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice.h>
#include <grpc/support/time.h>
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+
#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. */
-void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer);
+void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer);
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 99a32980aa6..7c7c4b8d3ee 100644
--- a/contrib/libs/grpc/src/core/lib/transport/transport.cc
+++ b/contrib/libs/grpc/src/core/lib/transport/transport.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/lib/transport/transport.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/atm.h>
-#include <grpc/support/log.h>
-#include <grpc/support/sync.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/transport/transport.h"
+
+#include <string.h>
+
+#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/gpr/string.h"
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/iomgr/executor.h"
+#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/transport/transport_impl.h"
-
-grpc_core::DebugOnlyTraceFlag grpc_trace_stream_refcount(false,
- "stream_refcount");
-
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/transport/transport_impl.h"
+
+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() &
@@ -54,146 +54,146 @@ void grpc_stream_destroy(grpc_stream_refcount* refcount) {
} 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));
-}
-
-#define STREAM_REF_FROM_SLICE_REF(p) \
- ((grpc_stream_refcount*)(((uint8_t*)p) - \
- offsetof(grpc_stream_refcount, slice_refcount)))
-
+}
+
+#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) {
-#ifndef NDEBUG
+#ifndef NDEBUG
grpc_stream_ref(STREAM_REF_FROM_SLICE_REF(&refcount->slice_refcount),
"slice");
-#else
+#else
grpc_stream_ref(STREAM_REF_FROM_SLICE_REF(&refcount->slice_refcount));
-#endif
- grpc_slice res;
- res.refcount = &refcount->slice_refcount;
- res.data.refcounted.bytes = static_cast<uint8_t*>(buffer);
- res.data.refcounted.length = length;
- return res;
-}
-
-#ifndef NDEBUG
+#endif
+ grpc_slice res;
+ res.refcount = &refcount->slice_refcount;
+ res.data.refcounted.bytes = static_cast<uint8_t*>(buffer);
+ res.data.refcounted.length = length;
+ return res;
+}
+
+#ifndef NDEBUG
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
+ 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*/,
- grpc_iomgr_cb_func cb, void* cb_arg) {
-#endif
- GRPC_CLOSURE_INIT(&refcount->destroy, cb, cb_arg, grpc_schedule_on_exec_ctx);
+ 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);
-}
-
-static void move64(uint64_t* from, uint64_t* to) {
- *to += *from;
- *from = 0;
-}
-
-void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats* from,
- grpc_transport_one_way_stats* to) {
- move64(&from->framing_bytes, &to->framing_bytes);
- move64(&from->data_bytes, &to->data_bytes);
- move64(&from->header_bytes, &to->header_bytes);
-}
-
-void grpc_transport_move_stats(grpc_transport_stream_stats* from,
- grpc_transport_stream_stats* to) {
- grpc_transport_move_one_way_stats(&from->incoming, &to->incoming);
- grpc_transport_move_one_way_stats(&from->outgoing, &to->outgoing);
-}
-
-size_t grpc_transport_stream_size(grpc_transport* transport) {
+}
+
+static void move64(uint64_t* from, uint64_t* to) {
+ *to += *from;
+ *from = 0;
+}
+
+void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats* from,
+ grpc_transport_one_way_stats* to) {
+ move64(&from->framing_bytes, &to->framing_bytes);
+ move64(&from->data_bytes, &to->data_bytes);
+ move64(&from->header_bytes, &to->header_bytes);
+}
+
+void grpc_transport_move_stats(grpc_transport_stream_stats* from,
+ grpc_transport_stream_stats* to) {
+ grpc_transport_move_one_way_stats(&from->incoming, &to->incoming);
+ grpc_transport_move_one_way_stats(&from->outgoing, &to->outgoing);
+}
+
+size_t grpc_transport_stream_size(grpc_transport* transport) {
return GPR_ROUND_UP_TO_ALIGNMENT_SIZE(transport->vtable->sizeof_stream);
-}
-
-void grpc_transport_destroy(grpc_transport* transport) {
- transport->vtable->destroy(transport);
-}
-
-int grpc_transport_init_stream(grpc_transport* transport, grpc_stream* stream,
- grpc_stream_refcount* refcount,
+}
+
+void grpc_transport_destroy(grpc_transport* transport) {
+ transport->vtable->destroy(transport);
+}
+
+int grpc_transport_init_stream(grpc_transport* transport, grpc_stream* stream,
+ grpc_stream_refcount* refcount,
const void* server_data,
grpc_core::Arena* arena) {
- return transport->vtable->init_stream(transport, stream, refcount,
- server_data, arena);
-}
-
-void grpc_transport_perform_stream_op(grpc_transport* transport,
- grpc_stream* stream,
- grpc_transport_stream_op_batch* op) {
- transport->vtable->perform_stream_op(transport, stream, op);
-}
-
-void grpc_transport_perform_op(grpc_transport* transport,
- grpc_transport_op* op) {
- transport->vtable->perform_op(transport, op);
-}
-
-void grpc_transport_set_pops(grpc_transport* transport, grpc_stream* stream,
- grpc_polling_entity* pollent) {
- grpc_pollset* pollset;
- grpc_pollset_set* pollset_set;
- if ((pollset = grpc_polling_entity_pollset(pollent)) != nullptr) {
- transport->vtable->set_pollset(transport, stream, pollset);
- } else if ((pollset_set = grpc_polling_entity_pollset_set(pollent)) !=
- nullptr) {
- transport->vtable->set_pollset_set(transport, stream, pollset_set);
- } else {
+ return transport->vtable->init_stream(transport, stream, refcount,
+ server_data, arena);
+}
+
+void grpc_transport_perform_stream_op(grpc_transport* transport,
+ grpc_stream* stream,
+ grpc_transport_stream_op_batch* op) {
+ transport->vtable->perform_stream_op(transport, stream, op);
+}
+
+void grpc_transport_perform_op(grpc_transport* transport,
+ grpc_transport_op* op) {
+ transport->vtable->perform_op(transport, op);
+}
+
+void grpc_transport_set_pops(grpc_transport* transport, grpc_stream* stream,
+ grpc_polling_entity* pollent) {
+ grpc_pollset* pollset;
+ grpc_pollset_set* pollset_set;
+ if ((pollset = grpc_polling_entity_pollset(pollent)) != nullptr) {
+ transport->vtable->set_pollset(transport, stream, pollset);
+ } else if ((pollset_set = grpc_polling_entity_pollset_set(pollent)) !=
+ nullptr) {
+ transport->vtable->set_pollset_set(transport, stream, pollset_set);
+ } else {
// No-op for empty pollset. Empty pollset is possible when using
// non-fd-based event engines such as CFStream.
- }
-}
-
-void grpc_transport_destroy_stream(grpc_transport* transport,
- grpc_stream* stream,
- grpc_closure* then_schedule_closure) {
- transport->vtable->destroy_stream(transport, stream, then_schedule_closure);
-}
-
-grpc_endpoint* grpc_transport_get_endpoint(grpc_transport* transport) {
- return transport->vtable->get_endpoint(transport);
-}
-
-// This comment should be sung to the tune of
-// "Supercalifragilisticexpialidocious":
-//
-// grpc_transport_stream_op_batch_finish_with_failure
-// is a function that must always unref cancel_error
-// though it lives in lib, it handles transport stream ops sure
-// 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,
+ }
+}
+
+void grpc_transport_destroy_stream(grpc_transport* transport,
+ grpc_stream* stream,
+ grpc_closure* then_schedule_closure) {
+ transport->vtable->destroy_stream(transport, stream, then_schedule_closure);
+}
+
+grpc_endpoint* grpc_transport_get_endpoint(grpc_transport* transport) {
+ return transport->vtable->get_endpoint(transport);
+}
+
+// This comment should be sung to the tune of
+// "Supercalifragilisticexpialidocious":
+//
+// grpc_transport_stream_op_batch_finish_with_failure
+// is a function that must always unref cancel_error
+// though it lives in lib, it handles transport stream ops sure
+// 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) {
- if (batch->send_message) {
- batch->payload->send_message.send_message.reset();
- }
+ if (batch->send_message) {
+ batch->payload->send_message.send_message.reset();
+ }
if (batch->cancel_stream) {
GRPC_ERROR_UNREF(batch->payload->cancel_stream.cancel_error);
- }
+ }
// Construct a list of closures to execute.
grpc_core::CallCombinerClosureList closures;
- if (batch->recv_initial_metadata) {
+ if (batch->recv_initial_metadata) {
closures.Add(
- batch->payload->recv_initial_metadata.recv_initial_metadata_ready,
- GRPC_ERROR_REF(error), "failing recv_initial_metadata_ready");
- }
+ batch->payload->recv_initial_metadata.recv_initial_metadata_ready,
+ GRPC_ERROR_REF(error), "failing recv_initial_metadata_ready");
+ }
if (batch->recv_message) {
closures.Add(batch->payload->recv_message.recv_message_ready,
GRPC_ERROR_REF(error), "failing recv_message_ready");
- }
+ }
if (batch->recv_trailing_metadata) {
closures.Add(
batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready,
@@ -206,54 +206,54 @@ void grpc_transport_stream_op_batch_finish_with_failure(
// Execute closures.
closures.RunClosures(call_combiner);
GRPC_ERROR_UNREF(error);
-}
-
+}
+
struct made_transport_op {
- grpc_closure outer_on_complete;
+ grpc_closure outer_on_complete;
grpc_closure* inner_on_complete = nullptr;
- grpc_transport_op op;
+ grpc_transport_op op;
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);
+
+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_transport_op* grpc_make_transport_op(grpc_closure* on_complete) {
+}
+
+grpc_transport_op* grpc_make_transport_op(grpc_closure* on_complete) {
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;
- op->op.on_consumed = &op->outer_on_complete;
- return &op->op;
-}
-
+ GRPC_CLOSURE_INIT(&op->outer_on_complete, destroy_made_transport_op, op,
+ grpc_schedule_on_exec_ctx);
+ op->inner_on_complete = on_complete;
+ op->op.on_consumed = &op->outer_on_complete;
+ return &op->op;
+}
+
struct made_transport_stream_op {
- grpc_closure outer_on_complete;
- grpc_closure* inner_on_complete;
- grpc_transport_stream_op_batch op;
- grpc_transport_stream_op_batch_payload payload;
+ grpc_closure outer_on_complete;
+ grpc_closure* inner_on_complete;
+ grpc_transport_stream_op_batch op;
+ grpc_transport_stream_op_batch_payload payload;
};
-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);
+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_transport_stream_op_batch* grpc_make_transport_stream_op(
- grpc_closure* on_complete) {
- made_transport_stream_op* op =
- static_cast<made_transport_stream_op*>(gpr_zalloc(sizeof(*op)));
- op->op.payload = &op->payload;
- GRPC_CLOSURE_INIT(&op->outer_on_complete, destroy_made_transport_stream_op,
- op, grpc_schedule_on_exec_ctx);
- op->inner_on_complete = on_complete;
- op->op.on_complete = &op->outer_on_complete;
- return &op->op;
-}
+}
+
+grpc_transport_stream_op_batch* grpc_make_transport_stream_op(
+ grpc_closure* on_complete) {
+ made_transport_stream_op* op =
+ static_cast<made_transport_stream_op*>(gpr_zalloc(sizeof(*op)));
+ op->op.payload = &op->payload;
+ GRPC_CLOSURE_INIT(&op->outer_on_complete, destroy_made_transport_stream_op,
+ op, grpc_schedule_on_exec_ctx);
+ op->inner_on_complete = on_complete;
+ op->op.on_complete = &op->outer_on_complete;
+ return &op->op;
+}
diff --git a/contrib/libs/grpc/src/core/lib/transport/transport.h b/contrib/libs/grpc/src/core/lib/transport/transport.h
index 2404455f9f6..4c473cbfa23 100644
--- a/contrib/libs/grpc/src/core/lib/transport/transport.h
+++ b/contrib/libs/grpc/src/core/lib/transport/transport.h
@@ -1,32 +1,32 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_TRANSPORT_H
#define GRPC_CORE_LIB_TRANSPORT_TRANSPORT_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#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/iomgr/call_combiner.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"
@@ -36,14 +36,14 @@
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/metadata_batch.h"
-/* Minimum and maximum protocol accepted versions. */
-#define GRPC_PROTOCOL_VERSION_MAX_MAJOR 2
-#define GRPC_PROTOCOL_VERSION_MAX_MINOR 1
-#define GRPC_PROTOCOL_VERSION_MIN_MAJOR 2
-#define GRPC_PROTOCOL_VERSION_MIN_MINOR 1
+/* Minimum and maximum protocol accepted versions. */
+#define GRPC_PROTOCOL_VERSION_MAX_MAJOR 2
+#define GRPC_PROTOCOL_VERSION_MAX_MINOR 1
+#define GRPC_PROTOCOL_VERSION_MIN_MAJOR 2
+#define GRPC_PROTOCOL_VERSION_MIN_MINOR 1
/* forward declarations */
-
+
typedef struct grpc_transport grpc_transport;
/* grpc_stream doesn't actually exist. It's used as a typesafe
@@ -51,26 +51,26 @@ typedef struct grpc_transport grpc_transport;
for a stream. */
typedef struct grpc_stream grpc_stream;
-extern grpc_core::DebugOnlyTraceFlag grpc_trace_stream_refcount;
+extern grpc_core::DebugOnlyTraceFlag grpc_trace_stream_refcount;
typedef struct grpc_stream_refcount {
grpc_core::RefCount refs;
grpc_closure destroy;
-#ifndef NDEBUG
- const char* object_type;
+#ifndef NDEBUG
+ const char* object_type;
#endif
- grpc_slice_refcount slice_refcount;
+ grpc_slice_refcount slice_refcount;
} grpc_stream_refcount;
-#ifndef NDEBUG
-void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs,
- grpc_iomgr_cb_func cb, void* cb_arg,
- const char* object_type);
+#ifndef NDEBUG
+void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs,
+ grpc_iomgr_cb_func cb, void* cb_arg,
+ const char* object_type);
#define GRPC_STREAM_REF_INIT(rc, ir, cb, cb_arg, objtype) \
grpc_stream_ref_init(rc, ir, cb, cb_arg, objtype)
#else
-void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs,
- grpc_iomgr_cb_func cb, void* cb_arg);
+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); \
@@ -114,11 +114,11 @@ inline void grpc_stream_unref(grpc_stream_refcount* 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,
- void* buffer, size_t length);
-
+/* 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,
+ void* buffer, size_t length);
+
struct grpc_transport_one_way_stats {
uint64_t framing_bytes = 0;
uint64_t data_bytes = 0;
@@ -130,34 +130,34 @@ struct grpc_transport_stream_stats {
grpc_transport_one_way_stats outgoing;
};
-void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats* from,
- grpc_transport_one_way_stats* to);
-
-void grpc_transport_move_stats(grpc_transport_stream_stats* from,
- grpc_transport_stream_stats* to);
-
-// This struct (which is present in both grpc_transport_stream_op_batch
-// and grpc_transport_op_batch) is a convenience to allow filters or
-// transports to schedule a closure related to a particular batch without
-// having to allocate memory. The general pattern is to initialize the
-// closure with the callback arg set to the batch and extra_arg set to
-// whatever state is associated with the handler (e.g., the call element
-// or the transport stream object).
-//
-// Note that this can only be used by the current handler of a given
-// batch on the way down the stack (i.e., whichever filter or transport is
-// 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.
+void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats* from,
+ grpc_transport_one_way_stats* to);
+
+void grpc_transport_move_stats(grpc_transport_stream_stats* from,
+ grpc_transport_stream_stats* to);
+
+// This struct (which is present in both grpc_transport_stream_op_batch
+// and grpc_transport_op_batch) is a convenience to allow filters or
+// transports to schedule a closure related to a particular batch without
+// having to allocate memory. The general pattern is to initialize the
+// closure with the callback arg set to the batch and extra_arg set to
+// whatever state is associated with the handler (e.g., the call element
+// or the transport stream object).
+//
+// Note that this can only be used by the current handler of a given
+// batch on the way down the stack (i.e., whichever filter or transport is
+// 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;
grpc_closure 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;
-
+typedef struct grpc_transport_stream_op_batch_payload
+ grpc_transport_stream_op_batch_payload;
+
/* Transport stream op: a set of operations to perform on a transport
against a single stream */
struct grpc_transport_stream_op_batch {
@@ -182,42 +182,42 @@ struct grpc_transport_stream_op_batch {
only recv ops, on_complete can be null. */
grpc_closure* on_complete = nullptr;
- /** Values for the stream op (fields set are determined by flags above) */
+ /** Values for the stream op (fields set are determined by flags above) */
grpc_transport_stream_op_batch_payload* payload = nullptr;
- /** Send initial metadata to the peer, from the provided metadata batch. */
- bool send_initial_metadata : 1;
+ /** Send initial metadata to the peer, from the provided metadata batch. */
+ bool send_initial_metadata : 1;
/** Send trailing metadata to the peer, from the provided metadata batch. */
- bool send_trailing_metadata : 1;
+ bool send_trailing_metadata : 1;
/** Send message data to the peer, from the provided byte stream. */
- bool send_message : 1;
+ bool send_message : 1;
/** Receive initial metadata from the stream, into provided metadata batch. */
- bool recv_initial_metadata : 1;
+ bool recv_initial_metadata : 1;
/** Receive message data from the stream, into provided byte stream. */
- bool recv_message : 1;
+ bool recv_message : 1;
/** Receive trailing metadata from the stream, into provided metadata batch.
*/
- bool recv_trailing_metadata : 1;
+ bool recv_trailing_metadata : 1;
- /** Cancel this stream with the provided error */
- bool cancel_stream : 1;
+ /** Cancel this stream with the provided error */
+ bool cancel_stream : 1;
/** Is this stream traced */
bool is_traced : 1;
/***************************************************************************
* remaining fields are initialized and used at the discretion of the
- * current handler of the op */
+ * current handler of the op */
- grpc_handler_private_op_data handler_private;
+ grpc_handler_private_op_data handler_private;
};
-struct grpc_transport_stream_op_batch_payload {
+struct grpc_transport_stream_op_batch_payload {
explicit grpc_transport_stream_op_batch_payload(
grpc_call_context_element* context)
: context(context) {}
@@ -227,20 +227,20 @@ struct grpc_transport_stream_op_batch_payload {
send_message.send_message.release();
}
- struct {
+ struct {
grpc_metadata_batch* send_initial_metadata = nullptr;
- /** Iff send_initial_metadata != NULL, flags associated with
- send_initial_metadata: a bitfield of GRPC_INITIAL_METADATA_xxx */
+ /** Iff send_initial_metadata != NULL, flags associated with
+ send_initial_metadata: a bitfield of GRPC_INITIAL_METADATA_xxx */
uint32_t send_initial_metadata_flags = 0;
// If non-NULL, will be set by the transport to the peer string (a char*).
// The transport retains ownership of the string.
- // Note: This pointer may be used by the transport after the
- // send_initial_metadata op is completed. It must remain valid
- // until the call is destroyed.
+ // Note: This pointer may be used by the transport after the
+ // send_initial_metadata op is completed. It must remain valid
+ // until the call is destroyed.
gpr_atm* peer_string = nullptr;
- } send_initial_metadata;
-
- struct {
+ } send_initial_metadata;
+
+ struct {
grpc_metadata_batch* send_trailing_metadata = nullptr;
// Set by the transport to true if the stream successfully wrote the
// trailing metadata. If this is not set but there was a send trailing
@@ -248,14 +248,14 @@ struct grpc_transport_stream_op_batch_payload {
// as a cancellation (since the stream was write-closed before status could
// be delivered).
bool* sent = nullptr;
- } send_trailing_metadata;
-
- struct {
- // The transport (or a filter that decides to return a failure before
- // the op gets down to the transport) takes ownership.
- // The batch's on_complete will not be called until after the byte
- // stream is orphaned.
- grpc_core::OrphanablePtr<grpc_core::ByteStream> send_message;
+ } send_trailing_metadata;
+
+ struct {
+ // The transport (or a filter that decides to return a failure before
+ // the op gets down to the transport) takes ownership.
+ // 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
@@ -268,64 +268,64 @@ struct grpc_transport_stream_op_batch_payload {
// 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 {
+ } send_message;
+
+ struct {
grpc_metadata_batch* recv_initial_metadata = nullptr;
- // Flags are used only on the server side. If non-null, will be set to
- // a bitfield of the GRPC_INITIAL_METADATA_xxx macros (e.g., to
- // indicate if the call is idempotent).
+ // Flags are used only on the server side. If non-null, will be set to
+ // a bitfield of the GRPC_INITIAL_METADATA_xxx macros (e.g., to
+ // indicate if the call is idempotent).
uint32_t* recv_flags = nullptr;
- /** Should be enqueued when initial metadata is ready to be processed. */
+ /** Should be enqueued when initial metadata is ready to be processed. */
grpc_closure* recv_initial_metadata_ready = nullptr;
- // If not NULL, will be set to true if trailing metadata is
- // immediately available. This may be a signal that we received a
- // Trailers-Only response.
+ // If not NULL, will be set to true if trailing metadata is
+ // immediately available. This may be a signal that we received a
+ // Trailers-Only response.
bool* trailing_metadata_available = nullptr;
// If non-NULL, will be set by the transport to the peer string (a char*).
// The transport retains ownership of the string.
- // Note: This pointer may be used by the transport after the
- // recv_initial_metadata op is completed. It must remain valid
- // until the call is destroyed.
+ // Note: This pointer may be used by the transport after the
+ // recv_initial_metadata op is completed. It must remain valid
+ // until the call is destroyed.
gpr_atm* peer_string = nullptr;
- } recv_initial_metadata;
-
- struct {
- // Will be set by the transport to point to the byte stream
- // containing a received message.
- // Will be NULL if trailing metadata is received instead of a message.
+ } recv_initial_metadata;
+
+ struct {
+ // Will be set by the transport to point to the byte stream
+ // containing a received message.
+ // Will be NULL if trailing metadata is received instead of a message.
grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message = nullptr;
- /** Should be enqueued when one message is ready to be processed. */
+ /** Should be enqueued when one message is ready to be processed. */
grpc_closure* recv_message_ready = nullptr;
- } recv_message;
-
- struct {
+ } recv_message;
+
+ 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. */
grpc_closure* recv_trailing_metadata_ready = nullptr;
- } recv_trailing_metadata;
-
- /** Forcefully close this stream.
- The HTTP2 semantics should be:
- - server side: if cancel_error has GRPC_ERROR_INT_GRPC_STATUS, and
- trailing metadata has not been sent, send trailing metadata with status
- and message from cancel_error (use grpc_error_get_status) followed by
- a RST_STREAM with error=GRPC_CHTTP2_NO_ERROR to force a full close
- - at all other times: use grpc_error_get_status to get a status code, and
- convert to a HTTP2 error code using
- grpc_chttp2_grpc_status_to_http2_error. Send a RST_STREAM with this
- error. */
- struct {
- // Error contract: the transport that gets this op must cause cancel_error
- // to be unref'ed after processing it
+ } recv_trailing_metadata;
+
+ /** Forcefully close this stream.
+ The HTTP2 semantics should be:
+ - server side: if cancel_error has GRPC_ERROR_INT_GRPC_STATUS, and
+ trailing metadata has not been sent, send trailing metadata with status
+ and message from cancel_error (use grpc_error_get_status) followed by
+ a RST_STREAM with error=GRPC_CHTTP2_NO_ERROR to force a full close
+ - at all other times: use grpc_error_get_status to get a status code, and
+ convert to a HTTP2 error code using
+ grpc_chttp2_grpc_status_to_http2_error. Send a RST_STREAM with this
+ error. */
+ struct {
+ // Error contract: the transport that gets this op must cause cancel_error
+ // to be unref'ed after processing it
grpc_error* cancel_error = GRPC_ERROR_NONE;
- } cancel_stream;
-
- /* Indexes correspond to grpc_context_index enum values */
- grpc_call_context_element* context;
-};
-
+ } cancel_stream;
+
+ /* Indexes correspond to grpc_context_index enum values */
+ grpc_call_context_element* context;
+};
+
/** 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. */
@@ -336,34 +336,34 @@ typedef struct grpc_transport_op {
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 */
+ /** 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;
- /** what should the goaway contain?
- * Error contract: the transport that gets this op must cause
- * goaway_error to be unref'ed after processing it */
+ /** 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;
/** 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;
- void (*set_accept_stream_fn)(void* user_data, grpc_transport* transport,
+ void (*set_accept_stream_fn)(void* user_data, grpc_transport* transport,
const void* server_data) = nullptr;
void* set_accept_stream_user_data = nullptr;
/** add this transport to a pollset */
grpc_pollset* bind_pollset = nullptr;
/** add this transport to a pollset_set */
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. */
+ /** 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;
- /** Called when the ping ack is received */
+ /** Called when the ping ack is received */
grpc_closure* on_ack = nullptr;
- } send_ping;
+ } send_ping;
// If true, will reset the channel's connection backoff.
bool reset_connect_backoff = false;
@@ -371,30 +371,30 @@ typedef struct grpc_transport_op {
* remaining fields are initialized and used at the discretion of the
* transport implementation */
- grpc_handler_private_op_data handler_private;
+ grpc_handler_private_op_data handler_private;
} grpc_transport_op;
/* Returns the amount of memory required to store a grpc_stream for this
transport */
-size_t grpc_transport_stream_size(grpc_transport* transport);
+size_t grpc_transport_stream_size(grpc_transport* transport);
/* Initialize transport data for a stream.
Returns 0 on success, any other (transport-defined) value for failure.
- May assume that stream contains all-zeros.
+ May assume that stream contains all-zeros.
Arguments:
transport - the transport on which to create this stream
stream - a pointer to uninitialized memory to initialize
server_data - either NULL for a client initiated stream, or a pointer
supplied from the accept_stream callback function */
-int grpc_transport_init_stream(grpc_transport* transport, grpc_stream* stream,
- grpc_stream_refcount* refcount,
+int grpc_transport_init_stream(grpc_transport* transport, grpc_stream* stream,
+ grpc_stream_refcount* refcount,
const void* server_data,
grpc_core::Arena* arena);
-void grpc_transport_set_pops(grpc_transport* transport, grpc_stream* stream,
- grpc_polling_entity* pollent);
+void grpc_transport_set_pops(grpc_transport* transport, grpc_stream* stream,
+ grpc_polling_entity* pollent);
/* Destroy transport data for a stream.
@@ -406,12 +406,12 @@ void grpc_transport_set_pops(grpc_transport* transport, grpc_stream* stream,
transport - the transport on which to create this stream
stream - the grpc_stream to destroy (memory is still owned by the
caller, but any child memory must be cleaned up) */
-void grpc_transport_destroy_stream(grpc_transport* transport,
- grpc_stream* stream,
- grpc_closure* then_schedule_closure);
+void grpc_transport_destroy_stream(grpc_transport* transport,
+ grpc_stream* stream,
+ grpc_closure* then_schedule_closure);
-void grpc_transport_stream_op_batch_finish_with_failure(
- grpc_transport_stream_op_batch* op, grpc_error* error,
+void grpc_transport_stream_op_batch_finish_with_failure(
+ grpc_transport_stream_op_batch* op, grpc_error* error,
grpc_core::CallCombiner* call_combiner);
TString grpc_transport_stream_op_batch_string(
@@ -426,38 +426,38 @@ TString grpc_transport_op_string(grpc_transport_op* op);
transport - the transport on which to initiate the stream
stream - the stream on which to send the operations. This must be
non-NULL and previously initialized by the same transport.
- op - a grpc_transport_stream_op_batch specifying the op to perform
- */
-void grpc_transport_perform_stream_op(grpc_transport* transport,
- grpc_stream* stream,
- grpc_transport_stream_op_batch* op);
+ op - a grpc_transport_stream_op_batch specifying the op to perform
+ */
+void grpc_transport_perform_stream_op(grpc_transport* transport,
+ grpc_stream* stream,
+ grpc_transport_stream_op_batch* op);
-void grpc_transport_perform_op(grpc_transport* transport,
- grpc_transport_op* op);
+void grpc_transport_perform_op(grpc_transport* transport,
+ grpc_transport_op* op);
/* Send a ping on a transport
Calls cb with user data when a response is received. */
-void grpc_transport_ping(grpc_transport* transport, grpc_closure* cb);
+void grpc_transport_ping(grpc_transport* transport, grpc_closure* cb);
/* Advise peer of pending connection termination. */
-void grpc_transport_goaway(grpc_transport* transport, grpc_status_code status,
+void grpc_transport_goaway(grpc_transport* transport, grpc_status_code status,
grpc_slice debug_data);
/* Destroy the transport */
-void grpc_transport_destroy(grpc_transport* transport);
+void grpc_transport_destroy(grpc_transport* transport);
/* Get the endpoint used by \a transport */
-grpc_endpoint* grpc_transport_get_endpoint(grpc_transport* transport);
+grpc_endpoint* grpc_transport_get_endpoint(grpc_transport* transport);
/* Allocate a grpc_transport_op, and preconfigure the on_consumed closure to
\a on_consumed and then delete the returned transport op */
-grpc_transport_op* grpc_make_transport_op(grpc_closure* on_consumed);
-/* Allocate a grpc_transport_stream_op_batch, and preconfigure the on_consumed
- closure
+grpc_transport_op* grpc_make_transport_op(grpc_closure* on_consumed);
+/* Allocate a grpc_transport_stream_op_batch, and preconfigure the on_consumed
+ closure
to \a on_consumed and then delete the returned transport op */
-grpc_transport_stream_op_batch* grpc_make_transport_stream_op(
- grpc_closure* on_consumed);
+grpc_transport_stream_op_batch* grpc_make_transport_stream_op(
+ grpc_closure* on_consumed);
namespace grpc_core {
// This is the key to be used for loading/storing keepalive_throttling in the
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 526cc1b1bac..f67a7f2006e 100644
--- a/contrib/libs/grpc/src/core/lib/transport/transport_impl.h
+++ b/contrib/libs/grpc/src/core/lib/transport/transport_impl.h
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_TRANSPORT_TRANSPORT_IMPL_H
#define GRPC_CORE_LIB_TRANSPORT_TRANSPORT_IMPL_H
-#include <grpc/support/port_platform.h>
-
+#include <grpc/support/port_platform.h>
+
#include "src/core/lib/transport/transport.h"
typedef struct grpc_transport_vtable {
@@ -29,43 +29,43 @@ typedef struct grpc_transport_vtable {
size_t sizeof_stream; /* = sizeof(transport stream) */
/* name of this transport implementation */
- const char* name;
+ const char* name;
/* implementation of grpc_transport_init_stream */
- int (*init_stream)(grpc_transport* self, grpc_stream* stream,
- grpc_stream_refcount* refcount, const void* server_data,
+ int (*init_stream)(grpc_transport* self, grpc_stream* stream,
+ grpc_stream_refcount* refcount, const void* server_data,
grpc_core::Arena* arena);
/* implementation of grpc_transport_set_pollset */
- void (*set_pollset)(grpc_transport* self, grpc_stream* stream,
- grpc_pollset* pollset);
+ void (*set_pollset)(grpc_transport* self, grpc_stream* stream,
+ grpc_pollset* pollset);
/* implementation of grpc_transport_set_pollset */
- void (*set_pollset_set)(grpc_transport* self, grpc_stream* stream,
- grpc_pollset_set* pollset_set);
+ void (*set_pollset_set)(grpc_transport* self, grpc_stream* stream,
+ grpc_pollset_set* pollset_set);
/* implementation of grpc_transport_perform_stream_op */
- void (*perform_stream_op)(grpc_transport* self, grpc_stream* stream,
- grpc_transport_stream_op_batch* op);
+ void (*perform_stream_op)(grpc_transport* self, grpc_stream* stream,
+ grpc_transport_stream_op_batch* op);
/* implementation of grpc_transport_perform_op */
- void (*perform_op)(grpc_transport* self, grpc_transport_op* op);
+ void (*perform_op)(grpc_transport* self, grpc_transport_op* op);
/* implementation of grpc_transport_destroy_stream */
- void (*destroy_stream)(grpc_transport* self, grpc_stream* stream,
- grpc_closure* then_schedule_closure);
+ void (*destroy_stream)(grpc_transport* self, grpc_stream* stream,
+ grpc_closure* then_schedule_closure);
/* implementation of grpc_transport_destroy */
- void (*destroy)(grpc_transport* self);
+ void (*destroy)(grpc_transport* self);
/* implementation of grpc_transport_get_endpoint */
- grpc_endpoint* (*get_endpoint)(grpc_transport* self);
+ grpc_endpoint* (*get_endpoint)(grpc_transport* self);
} grpc_transport_vtable;
/* an instance of a grpc transport */
struct grpc_transport {
/* pointer to a vtable defining operations on this transport */
- const grpc_transport_vtable* vtable;
+ const grpc_transport_vtable* vtable;
};
#endif /* GRPC_CORE_LIB_TRANSPORT_TRANSPORT_IMPL_H */
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 b26ee0a4fde..6d55a1c03fe 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
@@ -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 <grpc/support/port_platform.h>
-
-#include "src/core/lib/channel/channel_stack.h"
-
-#include <inttypes.h>
-#include <stdarg.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/lib/channel/channel_stack.h"
+
+#include <inttypes.h>
+#include <stdarg.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/string_util.h>
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/slice/slice_string_helpers.h"
-#include "src/core/lib/transport/connectivity_state.h"
-
-/* These routines are here to facilitate debugging - they produce string
- representations of various transport data structures */
-
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/gpr/string.h"
+#include "src/core/lib/slice/slice_string_helpers.h"
+#include "src/core/lib/transport/connectivity_state.h"
+
+/* These routines are here to facilitate debugging - they produce string
+ representations of various transport data structures */
+
static void put_metadata(grpc_mdelem md, std::vector<TString>* out) {
out->push_back("key=");
char* dump = grpc_dump_slice(GRPC_MDKEY(md), GPR_DUMP_HEX | GPR_DUMP_ASCII);
@@ -49,121 +49,121 @@ static void put_metadata(grpc_mdelem md, std::vector<TString>* out) {
dump = grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX | GPR_DUMP_ASCII);
out->push_back(dump);
gpr_free(dump);
-}
-
+}
+
static void put_metadata_list(grpc_metadata_batch md,
std::vector<TString>* out) {
- grpc_linked_mdelem* m;
- for (m = md.list.head; m != nullptr; m = m->next) {
+ grpc_linked_mdelem* m;
+ for (m = md.list.head; m != nullptr; m = m->next) {
if (m != md.list.head) out->push_back(", ");
put_metadata(m->md, out);
- }
- if (md.deadline != GRPC_MILLIS_INF_FUTURE) {
+ }
+ if (md.deadline != GRPC_MILLIS_INF_FUTURE) {
out->push_back(y_absl::StrFormat(" deadline=%" PRId64, md.deadline));
- }
-}
-
+ }
+}
+
TString grpc_transport_stream_op_batch_string(
- grpc_transport_stream_op_batch* op) {
+ grpc_transport_stream_op_batch* op) {
std::vector<TString> out;
-
- if (op->send_initial_metadata) {
+
+ if (op->send_initial_metadata) {
out.push_back(" SEND_INITIAL_METADATA{");
put_metadata_list(*op->payload->send_initial_metadata.send_initial_metadata,
&out);
out.push_back("}");
- }
-
- if (op->send_message) {
- if (op->payload->send_message.send_message != nullptr) {
+ }
+
+ if (op->send_message) {
+ if (op->payload->send_message.send_message != nullptr) {
out.push_back(
y_absl::StrFormat(" SEND_MESSAGE:flags=0x%08x:len=%d",
op->payload->send_message.send_message->flags(),
op->payload->send_message.send_message->length()));
- } else {
- // This can happen when we check a batch after the transport has
- // processed and cleared the send_message op.
+ } else {
+ // This can happen when we check a batch after the transport has
+ // processed and cleared the send_message op.
out.push_back(" SEND_MESSAGE(flag and length unknown, already orphaned)");
- }
- }
-
- if (op->send_trailing_metadata) {
+ }
+ }
+
+ if (op->send_trailing_metadata) {
out.push_back(" SEND_TRAILING_METADATA{");
- put_metadata_list(
+ put_metadata_list(
*op->payload->send_trailing_metadata.send_trailing_metadata, &out);
out.push_back("}");
- }
-
- if (op->recv_initial_metadata) {
+ }
+
+ if (op->recv_initial_metadata) {
out.push_back(" RECV_INITIAL_METADATA");
- }
-
- if (op->recv_message) {
+ }
+
+ if (op->recv_message) {
out.push_back(" RECV_MESSAGE");
- }
-
- if (op->recv_trailing_metadata) {
+ }
+
+ if (op->recv_trailing_metadata) {
out.push_back(" RECV_TRAILING_METADATA");
- }
-
- if (op->cancel_stream) {
+ }
+
+ if (op->cancel_stream) {
out.push_back(y_absl::StrCat(
" CANCEL:",
grpc_error_string(op->payload->cancel_stream.cancel_error)));
- }
-
+ }
+
return y_absl::StrJoin(out, "");
-}
-
+}
+
TString grpc_transport_op_string(grpc_transport_op* op) {
std::vector<TString> out;
-
+
if (op->start_connectivity_watch != nullptr) {
out.push_back(y_absl::StrFormat(
" START_CONNECTIVITY_WATCH:watcher=%p:from=%s",
op->start_connectivity_watch.get(),
grpc_core::ConnectivityStateName(op->start_connectivity_watch_state)));
- }
-
+ }
+
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) {
+ if (op->disconnect_with_error != GRPC_ERROR_NONE) {
out.push_back(y_absl::StrCat(" DISCONNECT:",
grpc_error_string(op->disconnect_with_error)));
- }
-
- if (op->goaway_error) {
+ }
+
+ if (op->goaway_error) {
out.push_back(
y_absl::StrCat(" SEND_GOAWAY:%s", grpc_error_string(op->goaway_error)));
- }
-
- if (op->set_accept_stream) {
+ }
+
+ if (op->set_accept_stream) {
out.push_back(y_absl::StrFormat(" SET_ACCEPT_STREAM:%p(%p,...)",
op->set_accept_stream_fn,
op->set_accept_stream_user_data));
- }
-
- if (op->bind_pollset != nullptr) {
+ }
+
+ if (op->bind_pollset != nullptr) {
out.push_back(" BIND_POLLSET");
- }
-
- if (op->bind_pollset_set != nullptr) {
+ }
+
+ if (op->bind_pollset_set != nullptr) {
out.push_back(" BIND_POLLSET_SET");
- }
-
- if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
+ }
+
+ if (op->send_ping.on_initiate != nullptr || op->send_ping.on_ack != nullptr) {
out.push_back(" SEND_PING");
- }
-
+ }
+
return y_absl::StrJoin(out, "");
-}
-
-void grpc_call_log_op(const char* file, int line, gpr_log_severity severity,
- grpc_call_element* elem,
- grpc_transport_stream_op_batch* op) {
+}
+
+void grpc_call_log_op(const char* file, int line, gpr_log_severity severity,
+ grpc_call_element* elem,
+ grpc_transport_stream_op_batch* op) {
gpr_log(file, line, severity, "OP[%s:%p]: %s", elem->filter->name, elem,
grpc_transport_stream_op_batch_string(op).c_str());
-}
+}
diff --git a/contrib/libs/grpc/src/core/lib/ya.make b/contrib/libs/grpc/src/core/lib/ya.make
index 93f59abe37c..6509a26489b 100644
--- a/contrib/libs/grpc/src/core/lib/ya.make
+++ b/contrib/libs/grpc/src/core/lib/ya.make
@@ -3,12 +3,12 @@
LIBRARY()
OWNER(g:cpp-contrib)
-
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-PEERDIR(
+PEERDIR(
contrib/restricted/abseil-cpp-tstring/y_absl/base/internal/spinlock_wait
contrib/restricted/abseil-cpp-tstring/y_absl/container
contrib/restricted/abseil-cpp-tstring/y_absl/memory
@@ -16,8 +16,8 @@ PEERDIR(
contrib/restricted/abseil-cpp-tstring/y_absl/strings/internal/str_format
contrib/restricted/abseil-cpp-tstring/y_absl/synchronization
contrib/restricted/abseil-cpp-tstring/y_absl/time
-)
-
+)
+
ADDINCL(
GLOBAL contrib/libs/grpc/include
${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
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 e048760c7f1..80ca2755abc 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
@@ -1,66 +1,66 @@
-/*
- *
- * 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 <grpc/grpc.h>
-
-void grpc_http_filters_init(void);
-void grpc_http_filters_shutdown(void);
-void grpc_chttp2_plugin_init(void);
-void grpc_chttp2_plugin_shutdown(void);
-void grpc_deadline_filter_init(void);
-void grpc_deadline_filter_shutdown(void);
-void grpc_client_channel_init(void);
-void grpc_client_channel_shutdown(void);
-void grpc_inproc_plugin_init(void);
-void grpc_inproc_plugin_shutdown(void);
-void grpc_resolver_fake_init(void);
-void grpc_resolver_fake_shutdown(void);
-void grpc_lb_policy_grpclb_init(void);
-void grpc_lb_policy_grpclb_shutdown(void);
+/*
+ *
+ * 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 <grpc/grpc.h>
+
+void grpc_http_filters_init(void);
+void grpc_http_filters_shutdown(void);
+void grpc_chttp2_plugin_init(void);
+void grpc_chttp2_plugin_shutdown(void);
+void grpc_deadline_filter_init(void);
+void grpc_deadline_filter_shutdown(void);
+void grpc_client_channel_init(void);
+void grpc_client_channel_shutdown(void);
+void grpc_inproc_plugin_init(void);
+void grpc_inproc_plugin_shutdown(void);
+void grpc_resolver_fake_init(void);
+void grpc_resolver_fake_shutdown(void);
+void grpc_lb_policy_grpclb_init(void);
+void grpc_lb_policy_grpclb_shutdown(void);
void grpc_lb_policy_priority_init(void);
void grpc_lb_policy_priority_shutdown(void);
void grpc_lb_policy_weighted_target_init(void);
void grpc_lb_policy_weighted_target_shutdown(void);
-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_resolver_dns_ares_init(void);
-void grpc_resolver_dns_ares_shutdown(void);
-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_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_resolver_dns_ares_init(void);
+void grpc_resolver_dns_ares_shutdown(void);
+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_max_age_filter_init(void);
-void grpc_max_age_filter_shutdown(void);
-void grpc_message_size_filter_init(void);
-void grpc_message_size_filter_shutdown(void);
+void grpc_max_age_filter_init(void);
+void grpc_max_age_filter_shutdown(void);
+void grpc_message_size_filter_init(void);
+void grpc_message_size_filter_shutdown(void);
void grpc_service_config_channel_arg_filter_init(void);
void grpc_service_config_channel_arg_filter_shutdown(void);
-void grpc_client_authority_filter_init(void);
-void grpc_client_authority_filter_shutdown(void);
-void grpc_workaround_cronet_compression_filter_init(void);
-void grpc_workaround_cronet_compression_filter_shutdown(void);
-
+void grpc_client_authority_filter_init(void);
+void grpc_client_authority_filter_shutdown(void);
+void grpc_workaround_cronet_compression_filter_init(void);
+void grpc_workaround_cronet_compression_filter_shutdown(void);
+
#ifndef GRPC_NO_XDS
namespace grpc_core {
void XdsClientGlobalInit();
@@ -80,47 +80,47 @@ void grpc_resolver_xds_init(void);
void grpc_resolver_xds_shutdown(void);
#endif
-void grpc_register_built_in_plugins(void) {
- grpc_register_plugin(grpc_http_filters_init,
- grpc_http_filters_shutdown);
- grpc_register_plugin(grpc_chttp2_plugin_init,
- grpc_chttp2_plugin_shutdown);
- grpc_register_plugin(grpc_deadline_filter_init,
- grpc_deadline_filter_shutdown);
- grpc_register_plugin(grpc_client_channel_init,
- grpc_client_channel_shutdown);
- grpc_register_plugin(grpc_inproc_plugin_init,
- grpc_inproc_plugin_shutdown);
- grpc_register_plugin(grpc_resolver_fake_init,
- grpc_resolver_fake_shutdown);
- grpc_register_plugin(grpc_lb_policy_grpclb_init,
- grpc_lb_policy_grpclb_shutdown);
+void grpc_register_built_in_plugins(void) {
+ grpc_register_plugin(grpc_http_filters_init,
+ grpc_http_filters_shutdown);
+ grpc_register_plugin(grpc_chttp2_plugin_init,
+ grpc_chttp2_plugin_shutdown);
+ grpc_register_plugin(grpc_deadline_filter_init,
+ grpc_deadline_filter_shutdown);
+ grpc_register_plugin(grpc_client_channel_init,
+ grpc_client_channel_shutdown);
+ grpc_register_plugin(grpc_inproc_plugin_init,
+ grpc_inproc_plugin_shutdown);
+ grpc_register_plugin(grpc_resolver_fake_init,
+ grpc_resolver_fake_shutdown);
+ grpc_register_plugin(grpc_lb_policy_grpclb_init,
+ grpc_lb_policy_grpclb_shutdown);
grpc_register_plugin(grpc_lb_policy_priority_init,
grpc_lb_policy_priority_shutdown);
grpc_register_plugin(grpc_lb_policy_weighted_target_init,
grpc_lb_policy_weighted_target_shutdown);
- grpc_register_plugin(grpc_lb_policy_pick_first_init,
- 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_lb_policy_pick_first_init,
+ 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_native_init,
- grpc_resolver_dns_native_shutdown);
- grpc_register_plugin(grpc_resolver_sockaddr_init,
- grpc_resolver_sockaddr_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_max_age_filter_init,
- grpc_max_age_filter_shutdown);
- grpc_register_plugin(grpc_message_size_filter_init,
- grpc_message_size_filter_shutdown);
+ grpc_register_plugin(grpc_max_age_filter_init,
+ grpc_max_age_filter_shutdown);
+ grpc_register_plugin(grpc_message_size_filter_init,
+ grpc_message_size_filter_shutdown);
grpc_register_plugin(grpc_service_config_channel_arg_filter_init,
grpc_service_config_channel_arg_filter_shutdown);
- grpc_register_plugin(grpc_client_authority_filter_init,
- grpc_client_authority_filter_shutdown);
- grpc_register_plugin(grpc_workaround_cronet_compression_filter_init,
- grpc_workaround_cronet_compression_filter_shutdown);
+ grpc_register_plugin(grpc_client_authority_filter_init,
+ grpc_client_authority_filter_shutdown);
+ grpc_register_plugin(grpc_workaround_cronet_compression_filter_init,
+ grpc_workaround_cronet_compression_filter_shutdown);
#ifndef GRPC_NO_XDS
grpc_register_plugin(grpc_core::XdsClientGlobalInit,
grpc_core::XdsClientGlobalShutdown);
@@ -137,4 +137,4 @@ void grpc_register_built_in_plugins(void) {
grpc_register_plugin(grpc_resolver_xds_init,
grpc_resolver_xds_shutdown);
#endif
-}
+}
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 fd9bf9c14d5..eb780d4cbdd 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
@@ -1,105 +1,105 @@
-/*
- *
- * 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 <grpc/grpc.h>
-
-void grpc_http_filters_init(void);
-void grpc_http_filters_shutdown(void);
-void grpc_chttp2_plugin_init(void);
-void grpc_chttp2_plugin_shutdown(void);
-void grpc_deadline_filter_init(void);
-void grpc_deadline_filter_shutdown(void);
-void grpc_client_channel_init(void);
-void grpc_client_channel_shutdown(void);
-void grpc_inproc_plugin_init(void);
-void grpc_inproc_plugin_shutdown(void);
-void grpc_resolver_dns_ares_init(void);
-void grpc_resolver_dns_ares_shutdown(void);
-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_resolver_fake_init(void);
-void grpc_resolver_fake_shutdown(void);
-void grpc_lb_policy_grpclb_init(void);
-void grpc_lb_policy_grpclb_shutdown(void);
+/*
+ *
+ * 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 <grpc/grpc.h>
+
+void grpc_http_filters_init(void);
+void grpc_http_filters_shutdown(void);
+void grpc_chttp2_plugin_init(void);
+void grpc_chttp2_plugin_shutdown(void);
+void grpc_deadline_filter_init(void);
+void grpc_deadline_filter_shutdown(void);
+void grpc_client_channel_init(void);
+void grpc_client_channel_shutdown(void);
+void grpc_inproc_plugin_init(void);
+void grpc_inproc_plugin_shutdown(void);
+void grpc_resolver_dns_ares_init(void);
+void grpc_resolver_dns_ares_shutdown(void);
+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_resolver_fake_init(void);
+void grpc_resolver_fake_shutdown(void);
+void grpc_lb_policy_grpclb_init(void);
+void grpc_lb_policy_grpclb_shutdown(void);
void grpc_lb_policy_priority_init(void);
void grpc_lb_policy_priority_shutdown(void);
void grpc_lb_policy_weighted_target_init(void);
void grpc_lb_policy_weighted_target_shutdown(void);
-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_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_max_age_filter_init(void);
-void grpc_max_age_filter_shutdown(void);
-void grpc_message_size_filter_init(void);
-void grpc_message_size_filter_shutdown(void);
+void grpc_max_age_filter_init(void);
+void grpc_max_age_filter_shutdown(void);
+void grpc_message_size_filter_init(void);
+void grpc_message_size_filter_shutdown(void);
void grpc_service_config_channel_arg_filter_init(void);
void grpc_service_config_channel_arg_filter_shutdown(void);
-void grpc_client_authority_filter_init(void);
-void grpc_client_authority_filter_shutdown(void);
-void grpc_workaround_cronet_compression_filter_init(void);
-void grpc_workaround_cronet_compression_filter_shutdown(void);
-
-void grpc_register_built_in_plugins(void) {
- grpc_register_plugin(grpc_http_filters_init,
- grpc_http_filters_shutdown);
- grpc_register_plugin(grpc_chttp2_plugin_init,
- grpc_chttp2_plugin_shutdown);
- grpc_register_plugin(grpc_deadline_filter_init,
- grpc_deadline_filter_shutdown);
- grpc_register_plugin(grpc_client_channel_init,
- grpc_client_channel_shutdown);
- grpc_register_plugin(grpc_inproc_plugin_init,
- grpc_inproc_plugin_shutdown);
+void grpc_client_authority_filter_init(void);
+void grpc_client_authority_filter_shutdown(void);
+void grpc_workaround_cronet_compression_filter_init(void);
+void grpc_workaround_cronet_compression_filter_shutdown(void);
+
+void grpc_register_built_in_plugins(void) {
+ grpc_register_plugin(grpc_http_filters_init,
+ grpc_http_filters_shutdown);
+ grpc_register_plugin(grpc_chttp2_plugin_init,
+ grpc_chttp2_plugin_shutdown);
+ grpc_register_plugin(grpc_deadline_filter_init,
+ grpc_deadline_filter_shutdown);
+ grpc_register_plugin(grpc_client_channel_init,
+ 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_native_init,
- grpc_resolver_dns_native_shutdown);
- grpc_register_plugin(grpc_resolver_sockaddr_init,
- grpc_resolver_sockaddr_shutdown);
- grpc_register_plugin(grpc_resolver_fake_init,
- grpc_resolver_fake_shutdown);
- grpc_register_plugin(grpc_lb_policy_grpclb_init,
- grpc_lb_policy_grpclb_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_resolver_fake_init,
+ grpc_resolver_fake_shutdown);
+ grpc_register_plugin(grpc_lb_policy_grpclb_init,
+ grpc_lb_policy_grpclb_shutdown);
grpc_register_plugin(grpc_lb_policy_priority_init,
grpc_lb_policy_priority_shutdown);
grpc_register_plugin(grpc_lb_policy_weighted_target_init,
grpc_lb_policy_weighted_target_shutdown);
- grpc_register_plugin(grpc_lb_policy_pick_first_init,
- 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_lb_policy_pick_first_init,
+ 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_max_age_filter_init,
- grpc_max_age_filter_shutdown);
- grpc_register_plugin(grpc_message_size_filter_init,
- grpc_message_size_filter_shutdown);
+ grpc_register_plugin(grpc_max_age_filter_init,
+ grpc_max_age_filter_shutdown);
+ grpc_register_plugin(grpc_message_size_filter_init,
+ grpc_message_size_filter_shutdown);
grpc_register_plugin(grpc_service_config_channel_arg_filter_init,
grpc_service_config_channel_arg_filter_shutdown);
- grpc_register_plugin(grpc_client_authority_filter_init,
- grpc_client_authority_filter_shutdown);
- grpc_register_plugin(grpc_workaround_cronet_compression_filter_init,
- grpc_workaround_cronet_compression_filter_shutdown);
-}
+ grpc_register_plugin(grpc_client_authority_filter_init,
+ grpc_client_authority_filter_shutdown);
+ grpc_register_plugin(grpc_workaround_cronet_compression_filter_init,
+ grpc_workaround_cronet_compression_filter_shutdown);
+}
diff --git a/contrib/libs/grpc/src/core/tsi/README.md b/contrib/libs/grpc/src/core/tsi/README.md
index 3ca3c1ef38c..30a851b4f0d 100644
--- a/contrib/libs/grpc/src/core/tsi/README.md
+++ b/contrib/libs/grpc/src/core/tsi/README.md
@@ -1,2 +1,2 @@
-# Transport Security Interface
-An abstraction library over crypto and auth modules (typically OpenSSL)
+# Transport Security Interface
+An abstraction library over crypto and auth modules (typically OpenSSL)
diff --git a/contrib/libs/grpc/src/core/tsi/alts/crypt/aes_gcm.cc b/contrib/libs/grpc/src/core/tsi/alts/crypt/aes_gcm.cc
index 02b1ac4492f..8e04f602ff2 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/crypt/aes_gcm.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/crypt/aes_gcm.cc
@@ -1,687 +1,687 @@
-/*
- *
- * 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/crypt/gsec.h"
-
-#include <openssl/bio.h>
-#include <openssl/buffer.h>
-#include <openssl/err.h>
-#include <openssl/evp.h>
-#include <openssl/hmac.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-constexpr size_t kKdfKeyLen = 32;
-constexpr size_t kKdfCounterLen = 6;
-constexpr size_t kKdfCounterOffset = 2;
-constexpr size_t kRekeyAeadKeyLen = kAes128GcmKeyLength;
-
-/* Struct for additional data required if rekeying is enabled. */
-struct gsec_aes_gcm_aead_rekey_data {
- uint8_t kdf_counter[kKdfCounterLen];
- uint8_t nonce_mask[kAesGcmNonceLength];
-};
-
-/* Main struct for AES_GCM crypter interface. */
-struct gsec_aes_gcm_aead_crypter {
- gsec_aead_crypter crypter;
- size_t key_length;
- size_t nonce_length;
- size_t tag_length;
- uint8_t* key;
- gsec_aes_gcm_aead_rekey_data* rekey_data;
- EVP_CIPHER_CTX* ctx;
-};
-
-static char* aes_gcm_get_openssl_errors() {
- BIO* bio = BIO_new(BIO_s_mem());
- ERR_print_errors(bio);
- BUF_MEM* mem = nullptr;
- char* error_msg = nullptr;
- BIO_get_mem_ptr(bio, &mem);
- if (mem != nullptr) {
- error_msg = static_cast<char*>(gpr_malloc(mem->length + 1));
- memcpy(error_msg, mem->data, mem->length);
- error_msg[mem->length] = '\0';
- }
- BIO_free_all(bio);
- return error_msg;
-}
-
-static void aes_gcm_format_errors(const char* error_msg, char** error_details) {
- if (error_details == nullptr) {
- return;
- }
- unsigned long error = ERR_get_error();
- if (error == 0 && error_msg != nullptr) {
- *error_details = static_cast<char*>(gpr_malloc(strlen(error_msg) + 1));
- memcpy(*error_details, error_msg, strlen(error_msg) + 1);
- return;
- }
- char* openssl_errors = aes_gcm_get_openssl_errors();
- if (openssl_errors != nullptr && error_msg != nullptr) {
- size_t len = strlen(error_msg) + strlen(openssl_errors) + 2; /* ", " */
- *error_details = static_cast<char*>(gpr_malloc(len + 1));
- snprintf(*error_details, len + 1, "%s, %s", error_msg, openssl_errors);
- gpr_free(openssl_errors);
- }
-}
-
-static grpc_status_code gsec_aes_gcm_aead_crypter_max_ciphertext_and_tag_length(
- const gsec_aead_crypter* crypter, size_t plaintext_length,
- size_t* max_ciphertext_and_tag_length, char** error_details) {
- if (max_ciphertext_and_tag_length == nullptr) {
- aes_gcm_format_errors("max_ciphertext_and_tag_length is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
- const_cast<gsec_aead_crypter*>(crypter));
- *max_ciphertext_and_tag_length =
- plaintext_length + aes_gcm_crypter->tag_length;
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code gsec_aes_gcm_aead_crypter_max_plaintext_length(
- const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
- size_t* max_plaintext_length, char** error_details) {
- if (max_plaintext_length == nullptr) {
- aes_gcm_format_errors("max_plaintext_length is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
- const_cast<gsec_aead_crypter*>(crypter));
- if (ciphertext_and_tag_length < aes_gcm_crypter->tag_length) {
- *max_plaintext_length = 0;
- aes_gcm_format_errors(
- "ciphertext_and_tag_length is smaller than tag_length.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- *max_plaintext_length =
- ciphertext_and_tag_length - aes_gcm_crypter->tag_length;
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code gsec_aes_gcm_aead_crypter_nonce_length(
- const gsec_aead_crypter* crypter, size_t* nonce_length,
- char** error_details) {
- if (nonce_length == nullptr) {
- aes_gcm_format_errors("nonce_length is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
- const_cast<gsec_aead_crypter*>(crypter));
- *nonce_length = aes_gcm_crypter->nonce_length;
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code gsec_aes_gcm_aead_crypter_key_length(
- const gsec_aead_crypter* crypter, size_t* key_length,
- char** error_details) {
- if (key_length == nullptr) {
- aes_gcm_format_errors("key_length is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
- const_cast<gsec_aead_crypter*>(crypter));
- *key_length = aes_gcm_crypter->key_length;
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code gsec_aes_gcm_aead_crypter_tag_length(
- const gsec_aead_crypter* crypter, size_t* tag_length,
- char** error_details) {
- if (tag_length == nullptr) {
- aes_gcm_format_errors("tag_length is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
- const_cast<gsec_aead_crypter*>(crypter));
- *tag_length = aes_gcm_crypter->tag_length;
- return GRPC_STATUS_OK;
-}
-
-static void aes_gcm_mask_nonce(uint8_t* dst, const uint8_t* nonce,
- const uint8_t* mask) {
- uint64_t mask1;
- uint32_t mask2;
- memcpy(&mask1, mask, sizeof(mask1));
- memcpy(&mask2, mask + sizeof(mask1), sizeof(mask2));
- uint64_t nonce1;
- uint32_t nonce2;
- memcpy(&nonce1, nonce, sizeof(nonce1));
- memcpy(&nonce2, nonce + sizeof(nonce1), sizeof(nonce2));
- nonce1 ^= mask1;
- nonce2 ^= mask2;
- memcpy(dst, &nonce1, sizeof(nonce1));
- memcpy(dst + sizeof(nonce1), &nonce2, sizeof(nonce2));
-}
-
-static grpc_status_code aes_gcm_derive_aead_key(uint8_t* dst,
- const uint8_t* kdf_key,
- const uint8_t* kdf_counter) {
- unsigned char buf[EVP_MAX_MD_SIZE];
- unsigned char ctr = 1;
-#if OPENSSL_VERSION_NUMBER < 0x10100000L
- HMAC_CTX hmac;
- HMAC_CTX_init(&hmac);
- if (!HMAC_Init_ex(&hmac, kdf_key, kKdfKeyLen, EVP_sha256(), nullptr) ||
- !HMAC_Update(&hmac, kdf_counter, kKdfCounterLen) ||
- !HMAC_Update(&hmac, &ctr, 1) || !HMAC_Final(&hmac, buf, nullptr)) {
- HMAC_CTX_cleanup(&hmac);
- return GRPC_STATUS_INTERNAL;
- }
- HMAC_CTX_cleanup(&hmac);
-#else
- HMAC_CTX* hmac = HMAC_CTX_new();
- if (hmac == nullptr) {
- return GRPC_STATUS_INTERNAL;
- }
- if (!HMAC_Init_ex(hmac, kdf_key, kKdfKeyLen, EVP_sha256(), nullptr) ||
- !HMAC_Update(hmac, kdf_counter, kKdfCounterLen) ||
- !HMAC_Update(hmac, &ctr, 1) || !HMAC_Final(hmac, buf, nullptr)) {
- HMAC_CTX_free(hmac);
- return GRPC_STATUS_INTERNAL;
- }
- HMAC_CTX_free(hmac);
-#endif
- memcpy(dst, buf, kRekeyAeadKeyLen);
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code aes_gcm_rekey_if_required(
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter, const uint8_t* nonce,
- char** error_details) {
- // If rekey_data is nullptr, then rekeying is not supported and not required.
- // If bytes 2-7 of kdf_counter differ from the (per message) nonce, then the
- // encryption key is recomputed from a new kdf_counter to ensure that we don't
- // encrypt more than 2^16 messages per encryption key (in each direction).
- if (aes_gcm_crypter->rekey_data == nullptr ||
- memcmp(aes_gcm_crypter->rekey_data->kdf_counter,
- nonce + kKdfCounterOffset, kKdfCounterLen) == 0) {
- return GRPC_STATUS_OK;
- }
- memcpy(aes_gcm_crypter->rekey_data->kdf_counter, nonce + kKdfCounterOffset,
- kKdfCounterLen);
- uint8_t aead_key[kRekeyAeadKeyLen];
- if (aes_gcm_derive_aead_key(aead_key, aes_gcm_crypter->key,
- aes_gcm_crypter->rekey_data->kdf_counter) !=
- GRPC_STATUS_OK) {
- aes_gcm_format_errors("Rekeying failed in key derivation.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- if (!EVP_DecryptInit_ex(aes_gcm_crypter->ctx, nullptr, nullptr, aead_key,
- nullptr)) {
- aes_gcm_format_errors("Rekeying failed in context update.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code gsec_aes_gcm_aead_crypter_encrypt_iovec(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* plaintext_vec, size_t plaintext_vec_length,
- struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
- char** error_details) {
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(crypter);
- // Input checks
- if (nonce == nullptr) {
- aes_gcm_format_errors("Nonce buffer is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (kAesGcmNonceLength != nonce_length) {
- aes_gcm_format_errors("Nonce buffer has the wrong length.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (aad_vec_length > 0 && aad_vec == nullptr) {
- aes_gcm_format_errors("Non-zero aad_vec_length but aad_vec is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (plaintext_vec_length > 0 && plaintext_vec == nullptr) {
- aes_gcm_format_errors(
- "Non-zero plaintext_vec_length but plaintext_vec is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (ciphertext_bytes_written == nullptr) {
- aes_gcm_format_errors("bytes_written is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- *ciphertext_bytes_written = 0;
- // rekey if required
- if (aes_gcm_rekey_if_required(aes_gcm_crypter, nonce, error_details) !=
- GRPC_STATUS_OK) {
- return GRPC_STATUS_INTERNAL;
- }
- // mask nonce if required
- const uint8_t* nonce_aead = nonce;
- uint8_t nonce_masked[kAesGcmNonceLength];
- if (aes_gcm_crypter->rekey_data != nullptr) {
- aes_gcm_mask_nonce(nonce_masked, aes_gcm_crypter->rekey_data->nonce_mask,
- nonce);
- nonce_aead = nonce_masked;
- }
- // init openssl context
- if (!EVP_EncryptInit_ex(aes_gcm_crypter->ctx, nullptr, nullptr, nullptr,
- nonce_aead)) {
- aes_gcm_format_errors("Initializing nonce failed", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- // process aad
- size_t i;
- for (i = 0; i < aad_vec_length; i++) {
- const uint8_t* aad = static_cast<uint8_t*>(aad_vec[i].iov_base);
- size_t aad_length = aad_vec[i].iov_len;
- if (aad_length == 0) {
- continue;
- }
- size_t aad_bytes_read = 0;
- if (aad == nullptr) {
- aes_gcm_format_errors("aad is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (!EVP_EncryptUpdate(aes_gcm_crypter->ctx, nullptr,
- reinterpret_cast<int*>(&aad_bytes_read), aad,
- static_cast<int>(aad_length)) ||
- aad_bytes_read != aad_length) {
- aes_gcm_format_errors("Setting authenticated associated data failed",
- error_details);
- return GRPC_STATUS_INTERNAL;
- }
- }
- uint8_t* ciphertext = static_cast<uint8_t*>(ciphertext_vec.iov_base);
- size_t ciphertext_length = ciphertext_vec.iov_len;
- if (ciphertext == nullptr) {
- aes_gcm_format_errors("ciphertext is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- // process plaintext
- for (i = 0; i < plaintext_vec_length; i++) {
- const uint8_t* plaintext = static_cast<uint8_t*>(plaintext_vec[i].iov_base);
- size_t plaintext_length = plaintext_vec[i].iov_len;
- if (plaintext == nullptr) {
- if (plaintext_length == 0) {
- continue;
- }
- aes_gcm_format_errors("plaintext is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (ciphertext_length < plaintext_length) {
- aes_gcm_format_errors(
- "ciphertext is not large enough to hold the result.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- int bytes_written = 0;
- int bytes_to_write = static_cast<int>(plaintext_length);
- if (!EVP_EncryptUpdate(aes_gcm_crypter->ctx, ciphertext, &bytes_written,
- plaintext, bytes_to_write)) {
- aes_gcm_format_errors("Encrypting plaintext failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- if (bytes_written > bytes_to_write) {
- aes_gcm_format_errors("More bytes written than expected.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- ciphertext += bytes_written;
- ciphertext_length -= bytes_written;
- }
- int bytes_written_temp = 0;
- if (!EVP_EncryptFinal_ex(aes_gcm_crypter->ctx, nullptr,
- &bytes_written_temp)) {
- aes_gcm_format_errors("Finalizing encryption failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- if (bytes_written_temp != 0) {
- aes_gcm_format_errors("Openssl wrote some unexpected bytes.",
- error_details);
- return GRPC_STATUS_INTERNAL;
- }
- if (ciphertext_length < kAesGcmTagLength) {
- aes_gcm_format_errors("ciphertext is too small to hold a tag.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
-
- if (!EVP_CIPHER_CTX_ctrl(aes_gcm_crypter->ctx, EVP_CTRL_GCM_GET_TAG,
- kAesGcmTagLength, ciphertext)) {
- aes_gcm_format_errors("Writing tag failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- ciphertext += kAesGcmTagLength;
- ciphertext_length -= kAesGcmTagLength;
- *ciphertext_bytes_written = ciphertext_vec.iov_len - ciphertext_length;
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code gsec_aes_gcm_aead_crypter_decrypt_iovec(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
- struct iovec plaintext_vec, size_t* plaintext_bytes_written,
- char** error_details) {
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
- const_cast<gsec_aead_crypter*>(crypter));
- if (nonce == nullptr) {
- aes_gcm_format_errors("Nonce buffer is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (kAesGcmNonceLength != nonce_length) {
- aes_gcm_format_errors("Nonce buffer has the wrong length.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (aad_vec_length > 0 && aad_vec == nullptr) {
- aes_gcm_format_errors("Non-zero aad_vec_length but aad_vec is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (ciphertext_vec_length > 0 && ciphertext_vec == nullptr) {
- aes_gcm_format_errors(
- "Non-zero plaintext_vec_length but plaintext_vec is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- // Compute the total length so we can ensure we don't pass the tag into
- // EVP_decrypt.
- size_t total_ciphertext_length = 0;
- size_t i;
- for (i = 0; i < ciphertext_vec_length; i++) {
- total_ciphertext_length += ciphertext_vec[i].iov_len;
- }
- if (total_ciphertext_length < kAesGcmTagLength) {
- aes_gcm_format_errors("ciphertext is too small to hold a tag.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (plaintext_bytes_written == nullptr) {
- aes_gcm_format_errors("bytes_written is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- *plaintext_bytes_written = 0;
- // rekey if required
- if (aes_gcm_rekey_if_required(aes_gcm_crypter, nonce, error_details) !=
- GRPC_STATUS_OK) {
- aes_gcm_format_errors("Rekeying failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- // mask nonce if required
- const uint8_t* nonce_aead = nonce;
- uint8_t nonce_masked[kAesGcmNonceLength];
- if (aes_gcm_crypter->rekey_data != nullptr) {
- aes_gcm_mask_nonce(nonce_masked, aes_gcm_crypter->rekey_data->nonce_mask,
- nonce);
- nonce_aead = nonce_masked;
- }
- // init openssl context
- if (!EVP_DecryptInit_ex(aes_gcm_crypter->ctx, nullptr, nullptr, nullptr,
- nonce_aead)) {
- aes_gcm_format_errors("Initializing nonce failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- // process aad
- for (i = 0; i < aad_vec_length; i++) {
- const uint8_t* aad = static_cast<uint8_t*>(aad_vec[i].iov_base);
- size_t aad_length = aad_vec[i].iov_len;
- if (aad_length == 0) {
- continue;
- }
- size_t aad_bytes_read = 0;
- if (aad == nullptr) {
- aes_gcm_format_errors("aad is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (!EVP_DecryptUpdate(aes_gcm_crypter->ctx, nullptr,
- reinterpret_cast<int*>(&aad_bytes_read), aad,
- static_cast<int>(aad_length)) ||
- aad_bytes_read != aad_length) {
- aes_gcm_format_errors("Setting authenticated associated data failed.",
- error_details);
- return GRPC_STATUS_INTERNAL;
- }
- }
- // process ciphertext
- uint8_t* plaintext = static_cast<uint8_t*>(plaintext_vec.iov_base);
- size_t plaintext_length = plaintext_vec.iov_len;
- if (plaintext_length > 0 && plaintext == nullptr) {
- aes_gcm_format_errors(
- "plaintext is nullptr, but plaintext_length is positive.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- const uint8_t* ciphertext = nullptr;
- size_t ciphertext_length = 0;
- for (i = 0;
- i < ciphertext_vec_length && total_ciphertext_length > kAesGcmTagLength;
- i++) {
- ciphertext = static_cast<uint8_t*>(ciphertext_vec[i].iov_base);
- ciphertext_length = ciphertext_vec[i].iov_len;
- if (ciphertext == nullptr) {
- if (ciphertext_length == 0) {
- continue;
- }
- aes_gcm_format_errors("ciphertext is nullptr.", error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- size_t bytes_written = 0;
- size_t bytes_to_write = ciphertext_length;
- // Don't include the tag
- if (bytes_to_write > total_ciphertext_length - kAesGcmTagLength) {
- bytes_to_write = total_ciphertext_length - kAesGcmTagLength;
- }
- if (plaintext_length < bytes_to_write) {
- aes_gcm_format_errors(
- "Not enough plaintext buffer to hold encrypted ciphertext.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (!EVP_DecryptUpdate(aes_gcm_crypter->ctx, plaintext,
- reinterpret_cast<int*>(&bytes_written), ciphertext,
- static_cast<int>(bytes_to_write))) {
- aes_gcm_format_errors("Decrypting ciphertext failed.", error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_INTERNAL;
- }
- if (bytes_written > ciphertext_length) {
- aes_gcm_format_errors("More bytes written than expected.", error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_INTERNAL;
- }
- ciphertext += bytes_written;
- ciphertext_length -= bytes_written;
- total_ciphertext_length -= bytes_written;
- plaintext += bytes_written;
- plaintext_length -= bytes_written;
- }
- if (total_ciphertext_length > kAesGcmTagLength) {
- aes_gcm_format_errors(
- "Not enough plaintext buffer to hold encrypted ciphertext.",
- error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- uint8_t tag[kAesGcmTagLength];
- uint8_t* tag_tmp = tag;
- if (ciphertext_length > 0) {
- memcpy(tag_tmp, ciphertext, ciphertext_length);
- tag_tmp += ciphertext_length;
- total_ciphertext_length -= ciphertext_length;
- }
- for (; i < ciphertext_vec_length; i++) {
- ciphertext = static_cast<uint8_t*>(ciphertext_vec[i].iov_base);
- ciphertext_length = ciphertext_vec[i].iov_len;
- if (ciphertext == nullptr) {
- if (ciphertext_length == 0) {
- continue;
- }
- aes_gcm_format_errors("ciphertext is nullptr.", error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- memcpy(tag_tmp, ciphertext, ciphertext_length);
- tag_tmp += ciphertext_length;
- total_ciphertext_length -= ciphertext_length;
- }
- if (!EVP_CIPHER_CTX_ctrl(aes_gcm_crypter->ctx, EVP_CTRL_GCM_SET_TAG,
- kAesGcmTagLength, reinterpret_cast<void*>(tag))) {
- aes_gcm_format_errors("Setting tag failed.", error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_INTERNAL;
- }
- int bytes_written_temp = 0;
- if (!EVP_DecryptFinal_ex(aes_gcm_crypter->ctx, nullptr,
- &bytes_written_temp)) {
- aes_gcm_format_errors("Checking tag failed.", error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- if (bytes_written_temp != 0) {
- aes_gcm_format_errors("Openssl wrote some unexpected bytes.",
- error_details);
- memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
- return GRPC_STATUS_INTERNAL;
- }
- *plaintext_bytes_written = plaintext_vec.iov_len - plaintext_length;
- return GRPC_STATUS_OK;
-}
-
-static void gsec_aes_gcm_aead_crypter_destroy(gsec_aead_crypter* crypter) {
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
- const_cast<gsec_aead_crypter*>(crypter));
- gpr_free(aes_gcm_crypter->key);
- gpr_free(aes_gcm_crypter->rekey_data);
- EVP_CIPHER_CTX_free(aes_gcm_crypter->ctx);
-}
-
-static const gsec_aead_crypter_vtable vtable = {
- gsec_aes_gcm_aead_crypter_encrypt_iovec,
- gsec_aes_gcm_aead_crypter_decrypt_iovec,
- gsec_aes_gcm_aead_crypter_max_ciphertext_and_tag_length,
- gsec_aes_gcm_aead_crypter_max_plaintext_length,
- gsec_aes_gcm_aead_crypter_nonce_length,
- gsec_aes_gcm_aead_crypter_key_length,
- gsec_aes_gcm_aead_crypter_tag_length,
- gsec_aes_gcm_aead_crypter_destroy};
-
-static grpc_status_code aes_gcm_new_evp_cipher_ctx(
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter, char** error_details) {
- const EVP_CIPHER* cipher = nullptr;
- bool is_rekey = aes_gcm_crypter->rekey_data != nullptr;
- switch (is_rekey ? kRekeyAeadKeyLen : aes_gcm_crypter->key_length) {
- case kAes128GcmKeyLength:
- cipher = EVP_aes_128_gcm();
- break;
- case kAes256GcmKeyLength:
- cipher = EVP_aes_256_gcm();
- break;
- }
- const uint8_t* aead_key = aes_gcm_crypter->key;
- uint8_t aead_key_rekey[kRekeyAeadKeyLen];
- if (is_rekey) {
- if (aes_gcm_derive_aead_key(aead_key_rekey, aes_gcm_crypter->key,
- aes_gcm_crypter->rekey_data->kdf_counter) !=
- GRPC_STATUS_OK) {
- aes_gcm_format_errors("Deriving key failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- aead_key = aead_key_rekey;
- }
- if (!EVP_DecryptInit_ex(aes_gcm_crypter->ctx, cipher, nullptr, aead_key,
- nullptr)) {
- aes_gcm_format_errors("Setting key failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- if (!EVP_CIPHER_CTX_ctrl(aes_gcm_crypter->ctx, EVP_CTRL_GCM_SET_IVLEN,
- static_cast<int>(aes_gcm_crypter->nonce_length),
- nullptr)) {
- aes_gcm_format_errors("Setting nonce length failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- return GRPC_STATUS_OK;
-}
-
-grpc_status_code gsec_aes_gcm_aead_crypter_create(const uint8_t* key,
- size_t key_length,
- size_t nonce_length,
- size_t tag_length, bool rekey,
- gsec_aead_crypter** crypter,
- char** error_details) {
- if (key == nullptr) {
- aes_gcm_format_errors("key is nullptr.", error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- if (crypter == nullptr) {
- aes_gcm_format_errors("crypter is nullptr.", error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- *crypter = nullptr;
- if ((rekey && key_length != kAes128GcmRekeyKeyLength) ||
- (!rekey && key_length != kAes128GcmKeyLength &&
- key_length != kAes256GcmKeyLength) ||
- (tag_length != kAesGcmTagLength) ||
- (nonce_length != kAesGcmNonceLength)) {
- aes_gcm_format_errors(
- "Invalid key and/or nonce and/or tag length are provided at AEAD "
- "crypter instance construction time.",
- error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
- static_cast<gsec_aes_gcm_aead_crypter*>(
- gpr_malloc(sizeof(gsec_aes_gcm_aead_crypter)));
- aes_gcm_crypter->crypter.vtable = &vtable;
- aes_gcm_crypter->nonce_length = nonce_length;
- aes_gcm_crypter->tag_length = tag_length;
- if (rekey) {
- aes_gcm_crypter->key_length = kKdfKeyLen;
- aes_gcm_crypter->rekey_data = static_cast<gsec_aes_gcm_aead_rekey_data*>(
- gpr_malloc(sizeof(gsec_aes_gcm_aead_rekey_data)));
- memcpy(aes_gcm_crypter->rekey_data->nonce_mask, key + kKdfKeyLen,
- kAesGcmNonceLength);
- // Set kdf_counter to all-zero for initial key derivation.
- memset(aes_gcm_crypter->rekey_data->kdf_counter, 0, kKdfCounterLen);
- } else {
- aes_gcm_crypter->key_length = key_length;
- aes_gcm_crypter->rekey_data = nullptr;
- }
- aes_gcm_crypter->key =
- static_cast<uint8_t*>(gpr_malloc(aes_gcm_crypter->key_length));
- memcpy(aes_gcm_crypter->key, key, aes_gcm_crypter->key_length);
- aes_gcm_crypter->ctx = EVP_CIPHER_CTX_new();
- grpc_status_code status =
- aes_gcm_new_evp_cipher_ctx(aes_gcm_crypter, error_details);
- if (status != GRPC_STATUS_OK) {
- gsec_aes_gcm_aead_crypter_destroy(&aes_gcm_crypter->crypter);
- gpr_free(aes_gcm_crypter);
- return status;
- }
- *crypter = &aes_gcm_crypter->crypter;
- return GRPC_STATUS_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/crypt/gsec.h"
+
+#include <openssl/bio.h>
+#include <openssl/buffer.h>
+#include <openssl/err.h>
+#include <openssl/evp.h>
+#include <openssl/hmac.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+constexpr size_t kKdfKeyLen = 32;
+constexpr size_t kKdfCounterLen = 6;
+constexpr size_t kKdfCounterOffset = 2;
+constexpr size_t kRekeyAeadKeyLen = kAes128GcmKeyLength;
+
+/* Struct for additional data required if rekeying is enabled. */
+struct gsec_aes_gcm_aead_rekey_data {
+ uint8_t kdf_counter[kKdfCounterLen];
+ uint8_t nonce_mask[kAesGcmNonceLength];
+};
+
+/* Main struct for AES_GCM crypter interface. */
+struct gsec_aes_gcm_aead_crypter {
+ gsec_aead_crypter crypter;
+ size_t key_length;
+ size_t nonce_length;
+ size_t tag_length;
+ uint8_t* key;
+ gsec_aes_gcm_aead_rekey_data* rekey_data;
+ EVP_CIPHER_CTX* ctx;
+};
+
+static char* aes_gcm_get_openssl_errors() {
+ BIO* bio = BIO_new(BIO_s_mem());
+ ERR_print_errors(bio);
+ BUF_MEM* mem = nullptr;
+ char* error_msg = nullptr;
+ BIO_get_mem_ptr(bio, &mem);
+ if (mem != nullptr) {
+ error_msg = static_cast<char*>(gpr_malloc(mem->length + 1));
+ memcpy(error_msg, mem->data, mem->length);
+ error_msg[mem->length] = '\0';
+ }
+ BIO_free_all(bio);
+ return error_msg;
+}
+
+static void aes_gcm_format_errors(const char* error_msg, char** error_details) {
+ if (error_details == nullptr) {
+ return;
+ }
+ unsigned long error = ERR_get_error();
+ if (error == 0 && error_msg != nullptr) {
+ *error_details = static_cast<char*>(gpr_malloc(strlen(error_msg) + 1));
+ memcpy(*error_details, error_msg, strlen(error_msg) + 1);
+ return;
+ }
+ char* openssl_errors = aes_gcm_get_openssl_errors();
+ if (openssl_errors != nullptr && error_msg != nullptr) {
+ size_t len = strlen(error_msg) + strlen(openssl_errors) + 2; /* ", " */
+ *error_details = static_cast<char*>(gpr_malloc(len + 1));
+ snprintf(*error_details, len + 1, "%s, %s", error_msg, openssl_errors);
+ gpr_free(openssl_errors);
+ }
+}
+
+static grpc_status_code gsec_aes_gcm_aead_crypter_max_ciphertext_and_tag_length(
+ const gsec_aead_crypter* crypter, size_t plaintext_length,
+ size_t* max_ciphertext_and_tag_length, char** error_details) {
+ if (max_ciphertext_and_tag_length == nullptr) {
+ aes_gcm_format_errors("max_ciphertext_and_tag_length is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
+ const_cast<gsec_aead_crypter*>(crypter));
+ *max_ciphertext_and_tag_length =
+ plaintext_length + aes_gcm_crypter->tag_length;
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code gsec_aes_gcm_aead_crypter_max_plaintext_length(
+ const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
+ size_t* max_plaintext_length, char** error_details) {
+ if (max_plaintext_length == nullptr) {
+ aes_gcm_format_errors("max_plaintext_length is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
+ const_cast<gsec_aead_crypter*>(crypter));
+ if (ciphertext_and_tag_length < aes_gcm_crypter->tag_length) {
+ *max_plaintext_length = 0;
+ aes_gcm_format_errors(
+ "ciphertext_and_tag_length is smaller than tag_length.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ *max_plaintext_length =
+ ciphertext_and_tag_length - aes_gcm_crypter->tag_length;
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code gsec_aes_gcm_aead_crypter_nonce_length(
+ const gsec_aead_crypter* crypter, size_t* nonce_length,
+ char** error_details) {
+ if (nonce_length == nullptr) {
+ aes_gcm_format_errors("nonce_length is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
+ const_cast<gsec_aead_crypter*>(crypter));
+ *nonce_length = aes_gcm_crypter->nonce_length;
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code gsec_aes_gcm_aead_crypter_key_length(
+ const gsec_aead_crypter* crypter, size_t* key_length,
+ char** error_details) {
+ if (key_length == nullptr) {
+ aes_gcm_format_errors("key_length is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
+ const_cast<gsec_aead_crypter*>(crypter));
+ *key_length = aes_gcm_crypter->key_length;
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code gsec_aes_gcm_aead_crypter_tag_length(
+ const gsec_aead_crypter* crypter, size_t* tag_length,
+ char** error_details) {
+ if (tag_length == nullptr) {
+ aes_gcm_format_errors("tag_length is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
+ const_cast<gsec_aead_crypter*>(crypter));
+ *tag_length = aes_gcm_crypter->tag_length;
+ return GRPC_STATUS_OK;
+}
+
+static void aes_gcm_mask_nonce(uint8_t* dst, const uint8_t* nonce,
+ const uint8_t* mask) {
+ uint64_t mask1;
+ uint32_t mask2;
+ memcpy(&mask1, mask, sizeof(mask1));
+ memcpy(&mask2, mask + sizeof(mask1), sizeof(mask2));
+ uint64_t nonce1;
+ uint32_t nonce2;
+ memcpy(&nonce1, nonce, sizeof(nonce1));
+ memcpy(&nonce2, nonce + sizeof(nonce1), sizeof(nonce2));
+ nonce1 ^= mask1;
+ nonce2 ^= mask2;
+ memcpy(dst, &nonce1, sizeof(nonce1));
+ memcpy(dst + sizeof(nonce1), &nonce2, sizeof(nonce2));
+}
+
+static grpc_status_code aes_gcm_derive_aead_key(uint8_t* dst,
+ const uint8_t* kdf_key,
+ const uint8_t* kdf_counter) {
+ unsigned char buf[EVP_MAX_MD_SIZE];
+ unsigned char ctr = 1;
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ HMAC_CTX hmac;
+ HMAC_CTX_init(&hmac);
+ if (!HMAC_Init_ex(&hmac, kdf_key, kKdfKeyLen, EVP_sha256(), nullptr) ||
+ !HMAC_Update(&hmac, kdf_counter, kKdfCounterLen) ||
+ !HMAC_Update(&hmac, &ctr, 1) || !HMAC_Final(&hmac, buf, nullptr)) {
+ HMAC_CTX_cleanup(&hmac);
+ return GRPC_STATUS_INTERNAL;
+ }
+ HMAC_CTX_cleanup(&hmac);
+#else
+ HMAC_CTX* hmac = HMAC_CTX_new();
+ if (hmac == nullptr) {
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (!HMAC_Init_ex(hmac, kdf_key, kKdfKeyLen, EVP_sha256(), nullptr) ||
+ !HMAC_Update(hmac, kdf_counter, kKdfCounterLen) ||
+ !HMAC_Update(hmac, &ctr, 1) || !HMAC_Final(hmac, buf, nullptr)) {
+ HMAC_CTX_free(hmac);
+ return GRPC_STATUS_INTERNAL;
+ }
+ HMAC_CTX_free(hmac);
+#endif
+ memcpy(dst, buf, kRekeyAeadKeyLen);
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code aes_gcm_rekey_if_required(
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter, const uint8_t* nonce,
+ char** error_details) {
+ // If rekey_data is nullptr, then rekeying is not supported and not required.
+ // If bytes 2-7 of kdf_counter differ from the (per message) nonce, then the
+ // encryption key is recomputed from a new kdf_counter to ensure that we don't
+ // encrypt more than 2^16 messages per encryption key (in each direction).
+ if (aes_gcm_crypter->rekey_data == nullptr ||
+ memcmp(aes_gcm_crypter->rekey_data->kdf_counter,
+ nonce + kKdfCounterOffset, kKdfCounterLen) == 0) {
+ return GRPC_STATUS_OK;
+ }
+ memcpy(aes_gcm_crypter->rekey_data->kdf_counter, nonce + kKdfCounterOffset,
+ kKdfCounterLen);
+ uint8_t aead_key[kRekeyAeadKeyLen];
+ if (aes_gcm_derive_aead_key(aead_key, aes_gcm_crypter->key,
+ aes_gcm_crypter->rekey_data->kdf_counter) !=
+ GRPC_STATUS_OK) {
+ aes_gcm_format_errors("Rekeying failed in key derivation.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (!EVP_DecryptInit_ex(aes_gcm_crypter->ctx, nullptr, nullptr, aead_key,
+ nullptr)) {
+ aes_gcm_format_errors("Rekeying failed in context update.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code gsec_aes_gcm_aead_crypter_encrypt_iovec(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* plaintext_vec, size_t plaintext_vec_length,
+ struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
+ char** error_details) {
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(crypter);
+ // Input checks
+ if (nonce == nullptr) {
+ aes_gcm_format_errors("Nonce buffer is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (kAesGcmNonceLength != nonce_length) {
+ aes_gcm_format_errors("Nonce buffer has the wrong length.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (aad_vec_length > 0 && aad_vec == nullptr) {
+ aes_gcm_format_errors("Non-zero aad_vec_length but aad_vec is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (plaintext_vec_length > 0 && plaintext_vec == nullptr) {
+ aes_gcm_format_errors(
+ "Non-zero plaintext_vec_length but plaintext_vec is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (ciphertext_bytes_written == nullptr) {
+ aes_gcm_format_errors("bytes_written is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ *ciphertext_bytes_written = 0;
+ // rekey if required
+ if (aes_gcm_rekey_if_required(aes_gcm_crypter, nonce, error_details) !=
+ GRPC_STATUS_OK) {
+ return GRPC_STATUS_INTERNAL;
+ }
+ // mask nonce if required
+ const uint8_t* nonce_aead = nonce;
+ uint8_t nonce_masked[kAesGcmNonceLength];
+ if (aes_gcm_crypter->rekey_data != nullptr) {
+ aes_gcm_mask_nonce(nonce_masked, aes_gcm_crypter->rekey_data->nonce_mask,
+ nonce);
+ nonce_aead = nonce_masked;
+ }
+ // init openssl context
+ if (!EVP_EncryptInit_ex(aes_gcm_crypter->ctx, nullptr, nullptr, nullptr,
+ nonce_aead)) {
+ aes_gcm_format_errors("Initializing nonce failed", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ // process aad
+ size_t i;
+ for (i = 0; i < aad_vec_length; i++) {
+ const uint8_t* aad = static_cast<uint8_t*>(aad_vec[i].iov_base);
+ size_t aad_length = aad_vec[i].iov_len;
+ if (aad_length == 0) {
+ continue;
+ }
+ size_t aad_bytes_read = 0;
+ if (aad == nullptr) {
+ aes_gcm_format_errors("aad is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (!EVP_EncryptUpdate(aes_gcm_crypter->ctx, nullptr,
+ reinterpret_cast<int*>(&aad_bytes_read), aad,
+ static_cast<int>(aad_length)) ||
+ aad_bytes_read != aad_length) {
+ aes_gcm_format_errors("Setting authenticated associated data failed",
+ error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ }
+ uint8_t* ciphertext = static_cast<uint8_t*>(ciphertext_vec.iov_base);
+ size_t ciphertext_length = ciphertext_vec.iov_len;
+ if (ciphertext == nullptr) {
+ aes_gcm_format_errors("ciphertext is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ // process plaintext
+ for (i = 0; i < plaintext_vec_length; i++) {
+ const uint8_t* plaintext = static_cast<uint8_t*>(plaintext_vec[i].iov_base);
+ size_t plaintext_length = plaintext_vec[i].iov_len;
+ if (plaintext == nullptr) {
+ if (plaintext_length == 0) {
+ continue;
+ }
+ aes_gcm_format_errors("plaintext is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (ciphertext_length < plaintext_length) {
+ aes_gcm_format_errors(
+ "ciphertext is not large enough to hold the result.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ int bytes_written = 0;
+ int bytes_to_write = static_cast<int>(plaintext_length);
+ if (!EVP_EncryptUpdate(aes_gcm_crypter->ctx, ciphertext, &bytes_written,
+ plaintext, bytes_to_write)) {
+ aes_gcm_format_errors("Encrypting plaintext failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (bytes_written > bytes_to_write) {
+ aes_gcm_format_errors("More bytes written than expected.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ ciphertext += bytes_written;
+ ciphertext_length -= bytes_written;
+ }
+ int bytes_written_temp = 0;
+ if (!EVP_EncryptFinal_ex(aes_gcm_crypter->ctx, nullptr,
+ &bytes_written_temp)) {
+ aes_gcm_format_errors("Finalizing encryption failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (bytes_written_temp != 0) {
+ aes_gcm_format_errors("Openssl wrote some unexpected bytes.",
+ error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (ciphertext_length < kAesGcmTagLength) {
+ aes_gcm_format_errors("ciphertext is too small to hold a tag.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+
+ if (!EVP_CIPHER_CTX_ctrl(aes_gcm_crypter->ctx, EVP_CTRL_GCM_GET_TAG,
+ kAesGcmTagLength, ciphertext)) {
+ aes_gcm_format_errors("Writing tag failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ ciphertext += kAesGcmTagLength;
+ ciphertext_length -= kAesGcmTagLength;
+ *ciphertext_bytes_written = ciphertext_vec.iov_len - ciphertext_length;
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code gsec_aes_gcm_aead_crypter_decrypt_iovec(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
+ struct iovec plaintext_vec, size_t* plaintext_bytes_written,
+ char** error_details) {
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
+ const_cast<gsec_aead_crypter*>(crypter));
+ if (nonce == nullptr) {
+ aes_gcm_format_errors("Nonce buffer is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (kAesGcmNonceLength != nonce_length) {
+ aes_gcm_format_errors("Nonce buffer has the wrong length.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (aad_vec_length > 0 && aad_vec == nullptr) {
+ aes_gcm_format_errors("Non-zero aad_vec_length but aad_vec is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (ciphertext_vec_length > 0 && ciphertext_vec == nullptr) {
+ aes_gcm_format_errors(
+ "Non-zero plaintext_vec_length but plaintext_vec is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ // Compute the total length so we can ensure we don't pass the tag into
+ // EVP_decrypt.
+ size_t total_ciphertext_length = 0;
+ size_t i;
+ for (i = 0; i < ciphertext_vec_length; i++) {
+ total_ciphertext_length += ciphertext_vec[i].iov_len;
+ }
+ if (total_ciphertext_length < kAesGcmTagLength) {
+ aes_gcm_format_errors("ciphertext is too small to hold a tag.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (plaintext_bytes_written == nullptr) {
+ aes_gcm_format_errors("bytes_written is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ *plaintext_bytes_written = 0;
+ // rekey if required
+ if (aes_gcm_rekey_if_required(aes_gcm_crypter, nonce, error_details) !=
+ GRPC_STATUS_OK) {
+ aes_gcm_format_errors("Rekeying failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ // mask nonce if required
+ const uint8_t* nonce_aead = nonce;
+ uint8_t nonce_masked[kAesGcmNonceLength];
+ if (aes_gcm_crypter->rekey_data != nullptr) {
+ aes_gcm_mask_nonce(nonce_masked, aes_gcm_crypter->rekey_data->nonce_mask,
+ nonce);
+ nonce_aead = nonce_masked;
+ }
+ // init openssl context
+ if (!EVP_DecryptInit_ex(aes_gcm_crypter->ctx, nullptr, nullptr, nullptr,
+ nonce_aead)) {
+ aes_gcm_format_errors("Initializing nonce failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ // process aad
+ for (i = 0; i < aad_vec_length; i++) {
+ const uint8_t* aad = static_cast<uint8_t*>(aad_vec[i].iov_base);
+ size_t aad_length = aad_vec[i].iov_len;
+ if (aad_length == 0) {
+ continue;
+ }
+ size_t aad_bytes_read = 0;
+ if (aad == nullptr) {
+ aes_gcm_format_errors("aad is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (!EVP_DecryptUpdate(aes_gcm_crypter->ctx, nullptr,
+ reinterpret_cast<int*>(&aad_bytes_read), aad,
+ static_cast<int>(aad_length)) ||
+ aad_bytes_read != aad_length) {
+ aes_gcm_format_errors("Setting authenticated associated data failed.",
+ error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ }
+ // process ciphertext
+ uint8_t* plaintext = static_cast<uint8_t*>(plaintext_vec.iov_base);
+ size_t plaintext_length = plaintext_vec.iov_len;
+ if (plaintext_length > 0 && plaintext == nullptr) {
+ aes_gcm_format_errors(
+ "plaintext is nullptr, but plaintext_length is positive.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ const uint8_t* ciphertext = nullptr;
+ size_t ciphertext_length = 0;
+ for (i = 0;
+ i < ciphertext_vec_length && total_ciphertext_length > kAesGcmTagLength;
+ i++) {
+ ciphertext = static_cast<uint8_t*>(ciphertext_vec[i].iov_base);
+ ciphertext_length = ciphertext_vec[i].iov_len;
+ if (ciphertext == nullptr) {
+ if (ciphertext_length == 0) {
+ continue;
+ }
+ aes_gcm_format_errors("ciphertext is nullptr.", error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ size_t bytes_written = 0;
+ size_t bytes_to_write = ciphertext_length;
+ // Don't include the tag
+ if (bytes_to_write > total_ciphertext_length - kAesGcmTagLength) {
+ bytes_to_write = total_ciphertext_length - kAesGcmTagLength;
+ }
+ if (plaintext_length < bytes_to_write) {
+ aes_gcm_format_errors(
+ "Not enough plaintext buffer to hold encrypted ciphertext.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (!EVP_DecryptUpdate(aes_gcm_crypter->ctx, plaintext,
+ reinterpret_cast<int*>(&bytes_written), ciphertext,
+ static_cast<int>(bytes_to_write))) {
+ aes_gcm_format_errors("Decrypting ciphertext failed.", error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (bytes_written > ciphertext_length) {
+ aes_gcm_format_errors("More bytes written than expected.", error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_INTERNAL;
+ }
+ ciphertext += bytes_written;
+ ciphertext_length -= bytes_written;
+ total_ciphertext_length -= bytes_written;
+ plaintext += bytes_written;
+ plaintext_length -= bytes_written;
+ }
+ if (total_ciphertext_length > kAesGcmTagLength) {
+ aes_gcm_format_errors(
+ "Not enough plaintext buffer to hold encrypted ciphertext.",
+ error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ uint8_t tag[kAesGcmTagLength];
+ uint8_t* tag_tmp = tag;
+ if (ciphertext_length > 0) {
+ memcpy(tag_tmp, ciphertext, ciphertext_length);
+ tag_tmp += ciphertext_length;
+ total_ciphertext_length -= ciphertext_length;
+ }
+ for (; i < ciphertext_vec_length; i++) {
+ ciphertext = static_cast<uint8_t*>(ciphertext_vec[i].iov_base);
+ ciphertext_length = ciphertext_vec[i].iov_len;
+ if (ciphertext == nullptr) {
+ if (ciphertext_length == 0) {
+ continue;
+ }
+ aes_gcm_format_errors("ciphertext is nullptr.", error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ memcpy(tag_tmp, ciphertext, ciphertext_length);
+ tag_tmp += ciphertext_length;
+ total_ciphertext_length -= ciphertext_length;
+ }
+ if (!EVP_CIPHER_CTX_ctrl(aes_gcm_crypter->ctx, EVP_CTRL_GCM_SET_TAG,
+ kAesGcmTagLength, reinterpret_cast<void*>(tag))) {
+ aes_gcm_format_errors("Setting tag failed.", error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_INTERNAL;
+ }
+ int bytes_written_temp = 0;
+ if (!EVP_DecryptFinal_ex(aes_gcm_crypter->ctx, nullptr,
+ &bytes_written_temp)) {
+ aes_gcm_format_errors("Checking tag failed.", error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ if (bytes_written_temp != 0) {
+ aes_gcm_format_errors("Openssl wrote some unexpected bytes.",
+ error_details);
+ memset(plaintext_vec.iov_base, 0x00, plaintext_vec.iov_len);
+ return GRPC_STATUS_INTERNAL;
+ }
+ *plaintext_bytes_written = plaintext_vec.iov_len - plaintext_length;
+ return GRPC_STATUS_OK;
+}
+
+static void gsec_aes_gcm_aead_crypter_destroy(gsec_aead_crypter* crypter) {
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ reinterpret_cast<gsec_aes_gcm_aead_crypter*>(
+ const_cast<gsec_aead_crypter*>(crypter));
+ gpr_free(aes_gcm_crypter->key);
+ gpr_free(aes_gcm_crypter->rekey_data);
+ EVP_CIPHER_CTX_free(aes_gcm_crypter->ctx);
+}
+
+static const gsec_aead_crypter_vtable vtable = {
+ gsec_aes_gcm_aead_crypter_encrypt_iovec,
+ gsec_aes_gcm_aead_crypter_decrypt_iovec,
+ gsec_aes_gcm_aead_crypter_max_ciphertext_and_tag_length,
+ gsec_aes_gcm_aead_crypter_max_plaintext_length,
+ gsec_aes_gcm_aead_crypter_nonce_length,
+ gsec_aes_gcm_aead_crypter_key_length,
+ gsec_aes_gcm_aead_crypter_tag_length,
+ gsec_aes_gcm_aead_crypter_destroy};
+
+static grpc_status_code aes_gcm_new_evp_cipher_ctx(
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter, char** error_details) {
+ const EVP_CIPHER* cipher = nullptr;
+ bool is_rekey = aes_gcm_crypter->rekey_data != nullptr;
+ switch (is_rekey ? kRekeyAeadKeyLen : aes_gcm_crypter->key_length) {
+ case kAes128GcmKeyLength:
+ cipher = EVP_aes_128_gcm();
+ break;
+ case kAes256GcmKeyLength:
+ cipher = EVP_aes_256_gcm();
+ break;
+ }
+ const uint8_t* aead_key = aes_gcm_crypter->key;
+ uint8_t aead_key_rekey[kRekeyAeadKeyLen];
+ if (is_rekey) {
+ if (aes_gcm_derive_aead_key(aead_key_rekey, aes_gcm_crypter->key,
+ aes_gcm_crypter->rekey_data->kdf_counter) !=
+ GRPC_STATUS_OK) {
+ aes_gcm_format_errors("Deriving key failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ aead_key = aead_key_rekey;
+ }
+ if (!EVP_DecryptInit_ex(aes_gcm_crypter->ctx, cipher, nullptr, aead_key,
+ nullptr)) {
+ aes_gcm_format_errors("Setting key failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (!EVP_CIPHER_CTX_ctrl(aes_gcm_crypter->ctx, EVP_CTRL_GCM_SET_IVLEN,
+ static_cast<int>(aes_gcm_crypter->nonce_length),
+ nullptr)) {
+ aes_gcm_format_errors("Setting nonce length failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ return GRPC_STATUS_OK;
+}
+
+grpc_status_code gsec_aes_gcm_aead_crypter_create(const uint8_t* key,
+ size_t key_length,
+ size_t nonce_length,
+ size_t tag_length, bool rekey,
+ gsec_aead_crypter** crypter,
+ char** error_details) {
+ if (key == nullptr) {
+ aes_gcm_format_errors("key is nullptr.", error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ if (crypter == nullptr) {
+ aes_gcm_format_errors("crypter is nullptr.", error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ *crypter = nullptr;
+ if ((rekey && key_length != kAes128GcmRekeyKeyLength) ||
+ (!rekey && key_length != kAes128GcmKeyLength &&
+ key_length != kAes256GcmKeyLength) ||
+ (tag_length != kAesGcmTagLength) ||
+ (nonce_length != kAesGcmNonceLength)) {
+ aes_gcm_format_errors(
+ "Invalid key and/or nonce and/or tag length are provided at AEAD "
+ "crypter instance construction time.",
+ error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ gsec_aes_gcm_aead_crypter* aes_gcm_crypter =
+ static_cast<gsec_aes_gcm_aead_crypter*>(
+ gpr_malloc(sizeof(gsec_aes_gcm_aead_crypter)));
+ aes_gcm_crypter->crypter.vtable = &vtable;
+ aes_gcm_crypter->nonce_length = nonce_length;
+ aes_gcm_crypter->tag_length = tag_length;
+ if (rekey) {
+ aes_gcm_crypter->key_length = kKdfKeyLen;
+ aes_gcm_crypter->rekey_data = static_cast<gsec_aes_gcm_aead_rekey_data*>(
+ gpr_malloc(sizeof(gsec_aes_gcm_aead_rekey_data)));
+ memcpy(aes_gcm_crypter->rekey_data->nonce_mask, key + kKdfKeyLen,
+ kAesGcmNonceLength);
+ // Set kdf_counter to all-zero for initial key derivation.
+ memset(aes_gcm_crypter->rekey_data->kdf_counter, 0, kKdfCounterLen);
+ } else {
+ aes_gcm_crypter->key_length = key_length;
+ aes_gcm_crypter->rekey_data = nullptr;
+ }
+ aes_gcm_crypter->key =
+ static_cast<uint8_t*>(gpr_malloc(aes_gcm_crypter->key_length));
+ memcpy(aes_gcm_crypter->key, key, aes_gcm_crypter->key_length);
+ aes_gcm_crypter->ctx = EVP_CIPHER_CTX_new();
+ grpc_status_code status =
+ aes_gcm_new_evp_cipher_ctx(aes_gcm_crypter, error_details);
+ if (status != GRPC_STATUS_OK) {
+ gsec_aes_gcm_aead_crypter_destroy(&aes_gcm_crypter->crypter);
+ gpr_free(aes_gcm_crypter);
+ return status;
+ }
+ *crypter = &aes_gcm_crypter->crypter;
+ return GRPC_STATUS_OK;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.cc b/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.cc
index 6236591a97c..8c2f84bf5d1 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.cc
@@ -1,189 +1,189 @@
-/*
- *
- * 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/crypt/gsec.h"
-
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-static const char vtable_error_msg[] =
- "crypter or crypter->vtable has not been initialized properly";
-
-static void maybe_copy_error_msg(const char* src, char** dst) {
- if (dst != nullptr && src != nullptr) {
- *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
- memcpy(*dst, src, strlen(src) + 1);
- }
-}
-
-grpc_status_code gsec_aead_crypter_encrypt(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const uint8_t* aad, size_t aad_length, const uint8_t* plaintext,
- size_t plaintext_length, uint8_t* ciphertext_and_tag,
- size_t ciphertext_and_tag_length, size_t* bytes_written,
- char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->encrypt_iovec != nullptr) {
- struct iovec aad_vec = {(void*)aad, aad_length};
- struct iovec plaintext_vec = {(void*)plaintext, plaintext_length};
- struct iovec ciphertext_vec = {ciphertext_and_tag,
- ciphertext_and_tag_length};
- return crypter->vtable->encrypt_iovec(
- crypter, nonce, nonce_length, &aad_vec, 1, &plaintext_vec, 1,
- ciphertext_vec, bytes_written, error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_encrypt_iovec(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* plaintext_vec, size_t plaintext_vec_length,
- struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
- char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->encrypt_iovec != nullptr) {
- return crypter->vtable->encrypt_iovec(
- crypter, nonce, nonce_length, aad_vec, aad_vec_length, plaintext_vec,
- plaintext_vec_length, ciphertext_vec, ciphertext_bytes_written,
- error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_decrypt(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const uint8_t* aad, size_t aad_length, const uint8_t* ciphertext_and_tag,
- size_t ciphertext_and_tag_length, uint8_t* plaintext,
- size_t plaintext_length, size_t* bytes_written, char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->decrypt_iovec != nullptr) {
- struct iovec aad_vec = {(void*)aad, aad_length};
- struct iovec ciphertext_vec = {(void*)ciphertext_and_tag,
- ciphertext_and_tag_length};
- struct iovec plaintext_vec = {plaintext, plaintext_length};
- return crypter->vtable->decrypt_iovec(
- crypter, nonce, nonce_length, &aad_vec, 1, &ciphertext_vec, 1,
- plaintext_vec, bytes_written, error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_decrypt_iovec(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
- struct iovec plaintext_vec, size_t* plaintext_bytes_written,
- char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->encrypt_iovec != nullptr) {
- return crypter->vtable->decrypt_iovec(
- crypter, nonce, nonce_length, aad_vec, aad_vec_length, ciphertext_vec,
- ciphertext_vec_length, plaintext_vec, plaintext_bytes_written,
- error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_max_ciphertext_and_tag_length(
- const gsec_aead_crypter* crypter, size_t plaintext_length,
- size_t* max_ciphertext_and_tag_length_to_return, char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->max_ciphertext_and_tag_length != nullptr) {
- return crypter->vtable->max_ciphertext_and_tag_length(
- crypter, plaintext_length, max_ciphertext_and_tag_length_to_return,
- error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_max_plaintext_length(
- const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
- size_t* max_plaintext_length_to_return, char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->max_plaintext_length != nullptr) {
- return crypter->vtable->max_plaintext_length(
- crypter, ciphertext_and_tag_length, max_plaintext_length_to_return,
- error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_nonce_length(
- const gsec_aead_crypter* crypter, size_t* nonce_length_to_return,
- char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->nonce_length != nullptr) {
- return crypter->vtable->nonce_length(crypter, nonce_length_to_return,
- error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_key_length(const gsec_aead_crypter* crypter,
- size_t* key_length_to_return,
- char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->key_length != nullptr) {
- return crypter->vtable->key_length(crypter, key_length_to_return,
- error_details);
- }
- /* An error occurred */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-grpc_status_code gsec_aead_crypter_tag_length(const gsec_aead_crypter* crypter,
- size_t* tag_length_to_return,
- char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->tag_length != nullptr) {
- return crypter->vtable->tag_length(crypter, tag_length_to_return,
- error_details);
- }
- /* An error occurred. */
- maybe_copy_error_msg(vtable_error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-void gsec_aead_crypter_destroy(gsec_aead_crypter* crypter) {
- if (crypter != nullptr) {
- if (crypter->vtable != nullptr && crypter->vtable->destruct != nullptr) {
- crypter->vtable->destruct(crypter);
- }
- gpr_free(crypter);
- }
-}
+/*
+ *
+ * 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/crypt/gsec.h"
+
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+static const char vtable_error_msg[] =
+ "crypter or crypter->vtable has not been initialized properly";
+
+static void maybe_copy_error_msg(const char* src, char** dst) {
+ if (dst != nullptr && src != nullptr) {
+ *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
+ memcpy(*dst, src, strlen(src) + 1);
+ }
+}
+
+grpc_status_code gsec_aead_crypter_encrypt(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const uint8_t* aad, size_t aad_length, const uint8_t* plaintext,
+ size_t plaintext_length, uint8_t* ciphertext_and_tag,
+ size_t ciphertext_and_tag_length, size_t* bytes_written,
+ char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->encrypt_iovec != nullptr) {
+ struct iovec aad_vec = {(void*)aad, aad_length};
+ struct iovec plaintext_vec = {(void*)plaintext, plaintext_length};
+ struct iovec ciphertext_vec = {ciphertext_and_tag,
+ ciphertext_and_tag_length};
+ return crypter->vtable->encrypt_iovec(
+ crypter, nonce, nonce_length, &aad_vec, 1, &plaintext_vec, 1,
+ ciphertext_vec, bytes_written, error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_encrypt_iovec(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* plaintext_vec, size_t plaintext_vec_length,
+ struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
+ char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->encrypt_iovec != nullptr) {
+ return crypter->vtable->encrypt_iovec(
+ crypter, nonce, nonce_length, aad_vec, aad_vec_length, plaintext_vec,
+ plaintext_vec_length, ciphertext_vec, ciphertext_bytes_written,
+ error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_decrypt(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const uint8_t* aad, size_t aad_length, const uint8_t* ciphertext_and_tag,
+ size_t ciphertext_and_tag_length, uint8_t* plaintext,
+ size_t plaintext_length, size_t* bytes_written, char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->decrypt_iovec != nullptr) {
+ struct iovec aad_vec = {(void*)aad, aad_length};
+ struct iovec ciphertext_vec = {(void*)ciphertext_and_tag,
+ ciphertext_and_tag_length};
+ struct iovec plaintext_vec = {plaintext, plaintext_length};
+ return crypter->vtable->decrypt_iovec(
+ crypter, nonce, nonce_length, &aad_vec, 1, &ciphertext_vec, 1,
+ plaintext_vec, bytes_written, error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_decrypt_iovec(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
+ struct iovec plaintext_vec, size_t* plaintext_bytes_written,
+ char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->encrypt_iovec != nullptr) {
+ return crypter->vtable->decrypt_iovec(
+ crypter, nonce, nonce_length, aad_vec, aad_vec_length, ciphertext_vec,
+ ciphertext_vec_length, plaintext_vec, plaintext_bytes_written,
+ error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_max_ciphertext_and_tag_length(
+ const gsec_aead_crypter* crypter, size_t plaintext_length,
+ size_t* max_ciphertext_and_tag_length_to_return, char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->max_ciphertext_and_tag_length != nullptr) {
+ return crypter->vtable->max_ciphertext_and_tag_length(
+ crypter, plaintext_length, max_ciphertext_and_tag_length_to_return,
+ error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_max_plaintext_length(
+ const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
+ size_t* max_plaintext_length_to_return, char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->max_plaintext_length != nullptr) {
+ return crypter->vtable->max_plaintext_length(
+ crypter, ciphertext_and_tag_length, max_plaintext_length_to_return,
+ error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_nonce_length(
+ const gsec_aead_crypter* crypter, size_t* nonce_length_to_return,
+ char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->nonce_length != nullptr) {
+ return crypter->vtable->nonce_length(crypter, nonce_length_to_return,
+ error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_key_length(const gsec_aead_crypter* crypter,
+ size_t* key_length_to_return,
+ char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->key_length != nullptr) {
+ return crypter->vtable->key_length(crypter, key_length_to_return,
+ error_details);
+ }
+ /* An error occurred */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+grpc_status_code gsec_aead_crypter_tag_length(const gsec_aead_crypter* crypter,
+ size_t* tag_length_to_return,
+ char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->tag_length != nullptr) {
+ return crypter->vtable->tag_length(crypter, tag_length_to_return,
+ error_details);
+ }
+ /* An error occurred. */
+ maybe_copy_error_msg(vtable_error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+void gsec_aead_crypter_destroy(gsec_aead_crypter* crypter) {
+ if (crypter != nullptr) {
+ if (crypter->vtable != nullptr && crypter->vtable->destruct != nullptr) {
+ crypter->vtable->destruct(crypter);
+ }
+ gpr_free(crypter);
+ }
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.h b/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.h
index 5a28c1b9d48..11c78c4aa88 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/crypt/gsec.h
@@ -1,458 +1,458 @@
-/*
- *
- * 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_TSI_ALTS_CRYPT_GSEC_H
-#define GRPC_CORE_TSI_ALTS_CRYPT_GSEC_H
-
-#include <grpc/support/port_platform.h>
-
-#include <assert.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-#include <grpc/grpc.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_TSI_ALTS_CRYPT_GSEC_H
+#define GRPC_CORE_TSI_ALTS_CRYPT_GSEC_H
+
+#include <grpc/support/port_platform.h>
+
+#include <assert.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include <grpc/grpc.h>
+
#if !defined(_STRUCT_IOVEC) && !defined(__DEFINED_struct_iovec)
#define _STRUCT_IOVEC
#define __DEFINED_struct_iovec
-struct iovec {
- void* iov_base;
- size_t iov_len;
-};
+struct iovec {
+ void* iov_base;
+ size_t iov_len;
+};
#endif // _STRUCT_IOVEC
-
-/**
- * A gsec interface for AEAD encryption schemes. The API is thread-compatible.
- * Each implementation of this interface should specify supported values for
- * key, nonce, and tag lengths.
- */
-
-/* Key, nonce, and tag length in bytes */
-const size_t kAesGcmNonceLength = 12;
-const size_t kAesGcmTagLength = 16;
-const size_t kAes128GcmKeyLength = 16;
-const size_t kAes256GcmKeyLength = 32;
-
-// The first 32 bytes are used as a KDF key and the remaining 12 bytes are used
-// to mask the nonce.
-const size_t kAes128GcmRekeyKeyLength = 44;
-
-typedef struct gsec_aead_crypter gsec_aead_crypter;
-
-/**
- * The gsec_aead_crypter is an API for different AEAD implementations such as
- * AES_GCM. It encapsulates all AEAD-related operations in the format of
- * V-table that stores pointers to functions implementing those operations.
- * It also provides helper functions to wrap each of those function pointers.
- *
- * A typical usage of this object would be:
- *
- *------------------------------------------------------------------------------
- * // Declare a gsec_aead_crypter object, and create and assign an instance
- * // of specific AEAD implementation e.g., AES_GCM to it. We assume both
- * // key and nonce contain cryptographically secure random bytes, and the key
- * // can be derived from an upper-layer application.
- * gsec_aead_crypter* crypter;
- * char* error_in_creation;
- * // User can populate the message with any 100 bytes data.
- * uint8_t* message = gpr_malloc(100);
- * grpc_status_code creation_status = gsec_aes_gcm_aead_crypter_create(key,
- * kAes128GcmKeyLength,
- * kAesGcmNonceLength,
- * kAesGcmTagLength,
- * &crypter,
- * false,
- * 0
- * &error_in_creation);
- *
- * if (creation_status == GRPC_STATUS_OK) {
- * // Allocate a correct amount of memory to hold a ciphertext.
- * size_t clength = 0;
- * gsec_aead_crypter_max_ciphertext_and_tag_length(crypter, 100, &clength,
- * nullptr);
- * uint8_t* ciphertext = gpr_malloc(clength);
- *
- * // Perform encryption
- * size_t num_encrypted_bytes = 0;
- * char* error_in_encryption = nullptr;
- * grpc_status_code status = gsec_aead_crypter_encrypt(crypter, nonce,
- * kAesGcmNonceLength,
- * nullptr, 0, message,
- * 100, ciphertext,
- * clength,
- * &num_encrypted_bytes,
- * &error_in_encryption);
- * if (status == GRPC_STATUS_OK) {
- * // Allocate a correct amount of memory to hold a plaintext.
- * size_t plength = 0;
- * gsec_aead_crypter_max_plaintext_length(crypter, num_encrypted_bytes,
- * &plength, nullptr);
- * uint8_t* plaintext = gpr_malloc(plength);
- *
- * // Perform decryption.
- * size_t num_decrypted_bytes = 0;
- * char* error_in_decryption = nullptr;
- * status = gsec_aead_crypter_decrypt(crypter, nonce,
- * kAesGcmNonceLength, nullptr, 0,
- * ciphertext, num_encrypted_bytes,
- * plaintext, plength,
- * &num_decrypted_bytes,
- * &error_in_decryption);
- * if (status != GRPC_STATUS_OK) {
- * fprintf(stderr, "AEAD decrypt operation failed with error code:"
- * "%d, message: %s\n", status, error_in_decryption);
- * }
- * ...
- * gpr_free(plaintext);
- * gpr_free(error_in_decryption);
- * } else {
- * fprintf(stderr, "AEAD encrypt operation failed with error code:"
- * "%d, message: %s\n", status, error_in_encryption);
- * }
- * ...
- * gpr_free(ciphertext);
- * gpr_free(error_in_encryption);
- * } else {
- * fprintf(stderr, "Creation of AEAD crypter instance failed with error code:"
- * "%d, message: %s\n", creation_status, error_in_creation);
- * }
- *
- * // Destruct AEAD crypter instance.
- * if (creation_status == GRPC_STATUS_OK) {
- * gsec_aead_crypter_destroy(crypter);
- * }
- * gpr_free(error_in_creation);
- * gpr_free(message);
- * -----------------------------------------------------------------------------
- */
-
-/* V-table for gsec AEAD operations */
-typedef struct gsec_aead_crypter_vtable {
- grpc_status_code (*encrypt_iovec)(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* plaintext_vec, size_t plaintext_vec_length,
- struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
- char** error_details);
- grpc_status_code (*decrypt_iovec)(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
- struct iovec plaintext_vec, size_t* plaintext_bytes_written,
- char** error_details);
- grpc_status_code (*max_ciphertext_and_tag_length)(
- const gsec_aead_crypter* crypter, size_t plaintext_length,
- size_t* max_ciphertext_and_tag_length_to_return, char** error_details);
- grpc_status_code (*max_plaintext_length)(
- const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
- size_t* max_plaintext_length_to_return, char** error_details);
- grpc_status_code (*nonce_length)(const gsec_aead_crypter* crypter,
- size_t* nonce_length_to_return,
- char** error_details);
- grpc_status_code (*key_length)(const gsec_aead_crypter* crypter,
- size_t* key_length_to_return,
- char** error_details);
- grpc_status_code (*tag_length)(const gsec_aead_crypter* crypter,
- size_t* tag_length_to_return,
- char** error_details);
- void (*destruct)(gsec_aead_crypter* crypter);
-} gsec_aead_crypter_vtable;
-
-/* Main struct for gsec interface */
-struct gsec_aead_crypter {
- const struct gsec_aead_crypter_vtable* vtable;
-};
-
-/**
- * This method performs an AEAD encrypt operation.
- *
- * - crypter: AEAD crypter instance.
- * - nonce: buffer containing a nonce with its size equal to nonce_length.
- * - nonce_length: size of nonce buffer, and must be equal to the value returned
- * from method gsec_aead_crypter_nonce_length.
- * - aad: buffer containing data that needs to be authenticated but not
- * encrypted with its size equal to aad_length.
- * - aad_length: size of aad buffer, which should be zero if the buffer is
- * nullptr.
- * - plaintext: buffer containing data that needs to be both encrypted and
- * authenticated with its size equal to plaintext_length.
- * - plaintext_length: size of plaintext buffer, which should be zero if
- * plaintext is nullptr.
- * - ciphertext_and_tag: buffer that will contain ciphertext and tags the method
- * produced. The buffer should not overlap the plaintext buffer, and pointers
- * to those buffers should not be equal. Also if the ciphertext+tag buffer is
- * nullptr, the plaintext_length should be zero.
- * - ciphertext_and_tag_length: size of ciphertext+tag buffer, which should be
- * at least as long as the one returned from method
- * gsec_aead_crypter_max_ciphertext_and_tag_length.
- * - bytes_written: the actual number of bytes written to the ciphertext+tag
- * buffer. If bytes_written is nullptr, the plaintext_length should be zero.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of encryption, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- *
- */
-grpc_status_code gsec_aead_crypter_encrypt(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const uint8_t* aad, size_t aad_length, const uint8_t* plaintext,
- size_t plaintext_length, uint8_t* ciphertext_and_tag,
- size_t ciphertext_and_tag_length, size_t* bytes_written,
- char** error_details);
-
-/**
- * This method performs an AEAD encrypt operation.
- *
- * - crypter: AEAD crypter instance.
- * - nonce: buffer containing a nonce with its size equal to nonce_length.
- * - nonce_length: size of nonce buffer, and must be equal to the value returned
- * from method gsec_aead_crypter_nonce_length.
- * - aad_vec: an iovec array containing data that needs to be authenticated but
- * not encrypted.
- * - aad_vec_length: the array length of aad_vec.
- * - plaintext_vec: an iovec array containing data that needs to be both
- * encrypted and authenticated.
- * - plaintext_vec_length: the array length of plaintext_vec.
- * - ciphertext_vec: an iovec containing a ciphertext buffer. The buffer should
- * not overlap the plaintext buffer.
- * - ciphertext_bytes_written: the actual number of bytes written to
- * ciphertext_vec.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of encryption, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- *
- */
-grpc_status_code gsec_aead_crypter_encrypt_iovec(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* plaintext_vec, size_t plaintext_vec_length,
- struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
- char** error_details);
-
-/**
- * This method performs an AEAD decrypt operation.
- *
- * - crypter: AEAD crypter instance.
- * - nonce: buffer containing a nonce with its size equal to nonce_length.
- * - nonce_length: size of nonce buffer, and must be equal to the value returned
- * from method gsec_aead_crypter_nonce_length.
- * - aad: buffer containing data that needs to be authenticated only.
- * - aad_length: size of aad buffer, which should be zero if the buffer is
- * nullptr.
- * - ciphertext_and_tag: buffer containing ciphertext and tag.
- * - ciphertext_and_tag_length: length of ciphertext and tag. It should be zero
- * if any of plaintext, ciphertext_and_tag, or bytes_written is nullptr. Also,
- * ciphertext_and_tag_length should be at least as large as the tag length set
- * at AEAD crypter instance construction time.
- * - plaintext: buffer containing decrypted and authenticated data the method
- * produced. The buffer should not overlap with the ciphertext+tag buffer, and
- * pointers to those buffers should not be equal.
- * - plaintext_length: size of plaintext buffer, which should be at least as
- * long as the one returned from gsec_aead_crypter_max_plaintext_length
- * method.
- * - bytes_written: the actual number of bytes written to the plaintext
- * buffer.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of decryption, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code gsec_aead_crypter_decrypt(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const uint8_t* aad, size_t aad_length, const uint8_t* ciphertext_and_tag,
- size_t ciphertext_and_tag_length, uint8_t* plaintext,
- size_t plaintext_length, size_t* bytes_written, char** error_details);
-
-/**
- * This method performs an AEAD decrypt operation.
- *
- * - crypter: AEAD crypter instance.
- * - nonce: buffer containing a nonce with its size equal to nonce_length.
- * - nonce_length: size of nonce buffer, and must be equal to the value returned
- * from method gsec_aead_crypter_nonce_length.
- * - aad_vec: an iovec array containing data that needs to be authenticated but
- * not encrypted.
- * - aad_vec_length: the array length of aad_vec.
- * - ciphertext_vec: an iovec array containing the ciphertext and tag.
- * - ciphertext_vec_length: the array length of ciphertext_vec.
- * - plaintext_vec: an iovec containing a plaintext buffer. The buffer should
- * not overlap the ciphertext buffer.
- * - plaintext_bytes_written: the actual number of bytes written to
- * plaintext_vec.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of decryption, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code gsec_aead_crypter_decrypt_iovec(
- gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
- const struct iovec* aad_vec, size_t aad_vec_length,
- const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
- struct iovec plaintext_vec, size_t* plaintext_bytes_written,
- char** error_details);
-
-/**
- * This method computes the size of ciphertext+tag buffer that must be passed to
- * gsec_aead_crypter_encrypt function to ensure correct encryption of a
- * plaintext. The actual size of ciphertext+tag written to the buffer could be
- * smaller.
- *
- * - crypter: AEAD crypter instance.
- * - plaintext_length: length of plaintext.
- * - max_ciphertext_and_tag_length_to_return: the size of ciphertext+tag buffer
- * the method returns.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code gsec_aead_crypter_max_ciphertext_and_tag_length(
- const gsec_aead_crypter* crypter, size_t plaintext_length,
- size_t* max_ciphertext_and_tag_length_to_return, char** error_details);
-
-/**
- * This method computes the size of plaintext buffer that must be passed to
- * gsec_aead_crypter_decrypt function to ensure correct decryption of a
- * ciphertext. The actual size of plaintext written to the buffer could be
- * smaller.
- *
- * - crypter: AEAD crypter instance.
- * - ciphertext_and_tag_length: length of ciphertext and tag.
- * - max_plaintext_length_to_return: the size of plaintext buffer the method
- * returns.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code gsec_aead_crypter_max_plaintext_length(
- const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
- size_t* max_plaintext_length_to_return, char** error_details);
-
-/**
- * This method returns a valid size of nonce array used at the construction of
- * AEAD crypter instance. It is also the size that should be passed to encrypt
- * and decrypt methods executed on the instance.
- *
- * - crypter: AEAD crypter instance.
- * - nonce_length_to_return: the length of nonce array the method returns.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code gsec_aead_crypter_nonce_length(
- const gsec_aead_crypter* crypter, size_t* nonce_length_to_return,
- char** error_details);
-
-/**
- * This method returns a valid size of key array used at the construction of
- * AEAD crypter instance. It is also the size that should be passed to encrypt
- * and decrypt methods executed on the instance.
- *
- * - crypter: AEAD crypter instance.
- * - key_length_to_return: the length of key array the method returns.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code gsec_aead_crypter_key_length(const gsec_aead_crypter* crypter,
- size_t* key_length_to_return,
- char** error_details);
-/**
- * This method returns a valid size of tag array used at the construction of
- * AEAD crypter instance. It is also the size that should be passed to encrypt
- * and decrypt methods executed on the instance.
- *
- * - crypter: AEAD crypter instance.
- * - tag_length_to_return: the length of tag array the method returns.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code gsec_aead_crypter_tag_length(const gsec_aead_crypter* crypter,
- size_t* tag_length_to_return,
- char** error_details);
-
-/**
- * This method destroys an AEAD crypter instance by de-allocating all of its
- * occupied memory.
- *
- * - crypter: AEAD crypter instance that needs to be destroyed.
- */
-void gsec_aead_crypter_destroy(gsec_aead_crypter* crypter);
-
-/**
- * This method creates an AEAD crypter instance of AES-GCM encryption scheme
- * which supports 16 and 32 bytes long keys, 12 and 16 bytes long nonces, and
- * 16 bytes long tags. It should be noted that once the lengths of key, nonce,
- * and tag are determined at construction time, they cannot be modified later.
- *
- * - key: buffer containing a key which is binded with AEAD crypter instance.
- * - key_length: length of a key in bytes, which should be 44 if rekeying is
- * enabled and 16 or 32 otherwise.
- * - nonce_length: length of a nonce in bytes, which should be either 12 or 16.
- * - tag_length: length of a tag in bytes, which should be always 16.
- * - rekey: enable nonce-based rekeying and nonce-masking.
- * - crypter: address of AES_GCM crypter instance returned from the method.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success of instance creation, it stores the address of instance at
- * crypter. Otherwise, it returns an error status code together with its details
- * specified in error_details.
- */
-grpc_status_code gsec_aes_gcm_aead_crypter_create(const uint8_t* key,
- size_t key_length,
- size_t nonce_length,
- size_t tag_length, bool rekey,
- gsec_aead_crypter** crypter,
- char** error_details);
-
-#endif /* GRPC_CORE_TSI_ALTS_CRYPT_GSEC_H */
+
+/**
+ * A gsec interface for AEAD encryption schemes. The API is thread-compatible.
+ * Each implementation of this interface should specify supported values for
+ * key, nonce, and tag lengths.
+ */
+
+/* Key, nonce, and tag length in bytes */
+const size_t kAesGcmNonceLength = 12;
+const size_t kAesGcmTagLength = 16;
+const size_t kAes128GcmKeyLength = 16;
+const size_t kAes256GcmKeyLength = 32;
+
+// The first 32 bytes are used as a KDF key and the remaining 12 bytes are used
+// to mask the nonce.
+const size_t kAes128GcmRekeyKeyLength = 44;
+
+typedef struct gsec_aead_crypter gsec_aead_crypter;
+
+/**
+ * The gsec_aead_crypter is an API for different AEAD implementations such as
+ * AES_GCM. It encapsulates all AEAD-related operations in the format of
+ * V-table that stores pointers to functions implementing those operations.
+ * It also provides helper functions to wrap each of those function pointers.
+ *
+ * A typical usage of this object would be:
+ *
+ *------------------------------------------------------------------------------
+ * // Declare a gsec_aead_crypter object, and create and assign an instance
+ * // of specific AEAD implementation e.g., AES_GCM to it. We assume both
+ * // key and nonce contain cryptographically secure random bytes, and the key
+ * // can be derived from an upper-layer application.
+ * gsec_aead_crypter* crypter;
+ * char* error_in_creation;
+ * // User can populate the message with any 100 bytes data.
+ * uint8_t* message = gpr_malloc(100);
+ * grpc_status_code creation_status = gsec_aes_gcm_aead_crypter_create(key,
+ * kAes128GcmKeyLength,
+ * kAesGcmNonceLength,
+ * kAesGcmTagLength,
+ * &crypter,
+ * false,
+ * 0
+ * &error_in_creation);
+ *
+ * if (creation_status == GRPC_STATUS_OK) {
+ * // Allocate a correct amount of memory to hold a ciphertext.
+ * size_t clength = 0;
+ * gsec_aead_crypter_max_ciphertext_and_tag_length(crypter, 100, &clength,
+ * nullptr);
+ * uint8_t* ciphertext = gpr_malloc(clength);
+ *
+ * // Perform encryption
+ * size_t num_encrypted_bytes = 0;
+ * char* error_in_encryption = nullptr;
+ * grpc_status_code status = gsec_aead_crypter_encrypt(crypter, nonce,
+ * kAesGcmNonceLength,
+ * nullptr, 0, message,
+ * 100, ciphertext,
+ * clength,
+ * &num_encrypted_bytes,
+ * &error_in_encryption);
+ * if (status == GRPC_STATUS_OK) {
+ * // Allocate a correct amount of memory to hold a plaintext.
+ * size_t plength = 0;
+ * gsec_aead_crypter_max_plaintext_length(crypter, num_encrypted_bytes,
+ * &plength, nullptr);
+ * uint8_t* plaintext = gpr_malloc(plength);
+ *
+ * // Perform decryption.
+ * size_t num_decrypted_bytes = 0;
+ * char* error_in_decryption = nullptr;
+ * status = gsec_aead_crypter_decrypt(crypter, nonce,
+ * kAesGcmNonceLength, nullptr, 0,
+ * ciphertext, num_encrypted_bytes,
+ * plaintext, plength,
+ * &num_decrypted_bytes,
+ * &error_in_decryption);
+ * if (status != GRPC_STATUS_OK) {
+ * fprintf(stderr, "AEAD decrypt operation failed with error code:"
+ * "%d, message: %s\n", status, error_in_decryption);
+ * }
+ * ...
+ * gpr_free(plaintext);
+ * gpr_free(error_in_decryption);
+ * } else {
+ * fprintf(stderr, "AEAD encrypt operation failed with error code:"
+ * "%d, message: %s\n", status, error_in_encryption);
+ * }
+ * ...
+ * gpr_free(ciphertext);
+ * gpr_free(error_in_encryption);
+ * } else {
+ * fprintf(stderr, "Creation of AEAD crypter instance failed with error code:"
+ * "%d, message: %s\n", creation_status, error_in_creation);
+ * }
+ *
+ * // Destruct AEAD crypter instance.
+ * if (creation_status == GRPC_STATUS_OK) {
+ * gsec_aead_crypter_destroy(crypter);
+ * }
+ * gpr_free(error_in_creation);
+ * gpr_free(message);
+ * -----------------------------------------------------------------------------
+ */
+
+/* V-table for gsec AEAD operations */
+typedef struct gsec_aead_crypter_vtable {
+ grpc_status_code (*encrypt_iovec)(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* plaintext_vec, size_t plaintext_vec_length,
+ struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
+ char** error_details);
+ grpc_status_code (*decrypt_iovec)(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
+ struct iovec plaintext_vec, size_t* plaintext_bytes_written,
+ char** error_details);
+ grpc_status_code (*max_ciphertext_and_tag_length)(
+ const gsec_aead_crypter* crypter, size_t plaintext_length,
+ size_t* max_ciphertext_and_tag_length_to_return, char** error_details);
+ grpc_status_code (*max_plaintext_length)(
+ const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
+ size_t* max_plaintext_length_to_return, char** error_details);
+ grpc_status_code (*nonce_length)(const gsec_aead_crypter* crypter,
+ size_t* nonce_length_to_return,
+ char** error_details);
+ grpc_status_code (*key_length)(const gsec_aead_crypter* crypter,
+ size_t* key_length_to_return,
+ char** error_details);
+ grpc_status_code (*tag_length)(const gsec_aead_crypter* crypter,
+ size_t* tag_length_to_return,
+ char** error_details);
+ void (*destruct)(gsec_aead_crypter* crypter);
+} gsec_aead_crypter_vtable;
+
+/* Main struct for gsec interface */
+struct gsec_aead_crypter {
+ const struct gsec_aead_crypter_vtable* vtable;
+};
+
+/**
+ * This method performs an AEAD encrypt operation.
+ *
+ * - crypter: AEAD crypter instance.
+ * - nonce: buffer containing a nonce with its size equal to nonce_length.
+ * - nonce_length: size of nonce buffer, and must be equal to the value returned
+ * from method gsec_aead_crypter_nonce_length.
+ * - aad: buffer containing data that needs to be authenticated but not
+ * encrypted with its size equal to aad_length.
+ * - aad_length: size of aad buffer, which should be zero if the buffer is
+ * nullptr.
+ * - plaintext: buffer containing data that needs to be both encrypted and
+ * authenticated with its size equal to plaintext_length.
+ * - plaintext_length: size of plaintext buffer, which should be zero if
+ * plaintext is nullptr.
+ * - ciphertext_and_tag: buffer that will contain ciphertext and tags the method
+ * produced. The buffer should not overlap the plaintext buffer, and pointers
+ * to those buffers should not be equal. Also if the ciphertext+tag buffer is
+ * nullptr, the plaintext_length should be zero.
+ * - ciphertext_and_tag_length: size of ciphertext+tag buffer, which should be
+ * at least as long as the one returned from method
+ * gsec_aead_crypter_max_ciphertext_and_tag_length.
+ * - bytes_written: the actual number of bytes written to the ciphertext+tag
+ * buffer. If bytes_written is nullptr, the plaintext_length should be zero.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of encryption, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ *
+ */
+grpc_status_code gsec_aead_crypter_encrypt(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const uint8_t* aad, size_t aad_length, const uint8_t* plaintext,
+ size_t plaintext_length, uint8_t* ciphertext_and_tag,
+ size_t ciphertext_and_tag_length, size_t* bytes_written,
+ char** error_details);
+
+/**
+ * This method performs an AEAD encrypt operation.
+ *
+ * - crypter: AEAD crypter instance.
+ * - nonce: buffer containing a nonce with its size equal to nonce_length.
+ * - nonce_length: size of nonce buffer, and must be equal to the value returned
+ * from method gsec_aead_crypter_nonce_length.
+ * - aad_vec: an iovec array containing data that needs to be authenticated but
+ * not encrypted.
+ * - aad_vec_length: the array length of aad_vec.
+ * - plaintext_vec: an iovec array containing data that needs to be both
+ * encrypted and authenticated.
+ * - plaintext_vec_length: the array length of plaintext_vec.
+ * - ciphertext_vec: an iovec containing a ciphertext buffer. The buffer should
+ * not overlap the plaintext buffer.
+ * - ciphertext_bytes_written: the actual number of bytes written to
+ * ciphertext_vec.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of encryption, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ *
+ */
+grpc_status_code gsec_aead_crypter_encrypt_iovec(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* plaintext_vec, size_t plaintext_vec_length,
+ struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
+ char** error_details);
+
+/**
+ * This method performs an AEAD decrypt operation.
+ *
+ * - crypter: AEAD crypter instance.
+ * - nonce: buffer containing a nonce with its size equal to nonce_length.
+ * - nonce_length: size of nonce buffer, and must be equal to the value returned
+ * from method gsec_aead_crypter_nonce_length.
+ * - aad: buffer containing data that needs to be authenticated only.
+ * - aad_length: size of aad buffer, which should be zero if the buffer is
+ * nullptr.
+ * - ciphertext_and_tag: buffer containing ciphertext and tag.
+ * - ciphertext_and_tag_length: length of ciphertext and tag. It should be zero
+ * if any of plaintext, ciphertext_and_tag, or bytes_written is nullptr. Also,
+ * ciphertext_and_tag_length should be at least as large as the tag length set
+ * at AEAD crypter instance construction time.
+ * - plaintext: buffer containing decrypted and authenticated data the method
+ * produced. The buffer should not overlap with the ciphertext+tag buffer, and
+ * pointers to those buffers should not be equal.
+ * - plaintext_length: size of plaintext buffer, which should be at least as
+ * long as the one returned from gsec_aead_crypter_max_plaintext_length
+ * method.
+ * - bytes_written: the actual number of bytes written to the plaintext
+ * buffer.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of decryption, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code gsec_aead_crypter_decrypt(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const uint8_t* aad, size_t aad_length, const uint8_t* ciphertext_and_tag,
+ size_t ciphertext_and_tag_length, uint8_t* plaintext,
+ size_t plaintext_length, size_t* bytes_written, char** error_details);
+
+/**
+ * This method performs an AEAD decrypt operation.
+ *
+ * - crypter: AEAD crypter instance.
+ * - nonce: buffer containing a nonce with its size equal to nonce_length.
+ * - nonce_length: size of nonce buffer, and must be equal to the value returned
+ * from method gsec_aead_crypter_nonce_length.
+ * - aad_vec: an iovec array containing data that needs to be authenticated but
+ * not encrypted.
+ * - aad_vec_length: the array length of aad_vec.
+ * - ciphertext_vec: an iovec array containing the ciphertext and tag.
+ * - ciphertext_vec_length: the array length of ciphertext_vec.
+ * - plaintext_vec: an iovec containing a plaintext buffer. The buffer should
+ * not overlap the ciphertext buffer.
+ * - plaintext_bytes_written: the actual number of bytes written to
+ * plaintext_vec.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of decryption, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code gsec_aead_crypter_decrypt_iovec(
+ gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
+ const struct iovec* aad_vec, size_t aad_vec_length,
+ const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
+ struct iovec plaintext_vec, size_t* plaintext_bytes_written,
+ char** error_details);
+
+/**
+ * This method computes the size of ciphertext+tag buffer that must be passed to
+ * gsec_aead_crypter_encrypt function to ensure correct encryption of a
+ * plaintext. The actual size of ciphertext+tag written to the buffer could be
+ * smaller.
+ *
+ * - crypter: AEAD crypter instance.
+ * - plaintext_length: length of plaintext.
+ * - max_ciphertext_and_tag_length_to_return: the size of ciphertext+tag buffer
+ * the method returns.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code gsec_aead_crypter_max_ciphertext_and_tag_length(
+ const gsec_aead_crypter* crypter, size_t plaintext_length,
+ size_t* max_ciphertext_and_tag_length_to_return, char** error_details);
+
+/**
+ * This method computes the size of plaintext buffer that must be passed to
+ * gsec_aead_crypter_decrypt function to ensure correct decryption of a
+ * ciphertext. The actual size of plaintext written to the buffer could be
+ * smaller.
+ *
+ * - crypter: AEAD crypter instance.
+ * - ciphertext_and_tag_length: length of ciphertext and tag.
+ * - max_plaintext_length_to_return: the size of plaintext buffer the method
+ * returns.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code gsec_aead_crypter_max_plaintext_length(
+ const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
+ size_t* max_plaintext_length_to_return, char** error_details);
+
+/**
+ * This method returns a valid size of nonce array used at the construction of
+ * AEAD crypter instance. It is also the size that should be passed to encrypt
+ * and decrypt methods executed on the instance.
+ *
+ * - crypter: AEAD crypter instance.
+ * - nonce_length_to_return: the length of nonce array the method returns.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code gsec_aead_crypter_nonce_length(
+ const gsec_aead_crypter* crypter, size_t* nonce_length_to_return,
+ char** error_details);
+
+/**
+ * This method returns a valid size of key array used at the construction of
+ * AEAD crypter instance. It is also the size that should be passed to encrypt
+ * and decrypt methods executed on the instance.
+ *
+ * - crypter: AEAD crypter instance.
+ * - key_length_to_return: the length of key array the method returns.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code gsec_aead_crypter_key_length(const gsec_aead_crypter* crypter,
+ size_t* key_length_to_return,
+ char** error_details);
+/**
+ * This method returns a valid size of tag array used at the construction of
+ * AEAD crypter instance. It is also the size that should be passed to encrypt
+ * and decrypt methods executed on the instance.
+ *
+ * - crypter: AEAD crypter instance.
+ * - tag_length_to_return: the length of tag array the method returns.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On the success of execution, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code gsec_aead_crypter_tag_length(const gsec_aead_crypter* crypter,
+ size_t* tag_length_to_return,
+ char** error_details);
+
+/**
+ * This method destroys an AEAD crypter instance by de-allocating all of its
+ * occupied memory.
+ *
+ * - crypter: AEAD crypter instance that needs to be destroyed.
+ */
+void gsec_aead_crypter_destroy(gsec_aead_crypter* crypter);
+
+/**
+ * This method creates an AEAD crypter instance of AES-GCM encryption scheme
+ * which supports 16 and 32 bytes long keys, 12 and 16 bytes long nonces, and
+ * 16 bytes long tags. It should be noted that once the lengths of key, nonce,
+ * and tag are determined at construction time, they cannot be modified later.
+ *
+ * - key: buffer containing a key which is binded with AEAD crypter instance.
+ * - key_length: length of a key in bytes, which should be 44 if rekeying is
+ * enabled and 16 or 32 otherwise.
+ * - nonce_length: length of a nonce in bytes, which should be either 12 or 16.
+ * - tag_length: length of a tag in bytes, which should be always 16.
+ * - rekey: enable nonce-based rekeying and nonce-masking.
+ * - crypter: address of AES_GCM crypter instance returned from the method.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success of instance creation, it stores the address of instance at
+ * crypter. Otherwise, it returns an error status code together with its details
+ * specified in error_details.
+ */
+grpc_status_code gsec_aes_gcm_aead_crypter_create(const uint8_t* key,
+ size_t key_length,
+ size_t nonce_length,
+ size_t tag_length, bool rekey,
+ gsec_aead_crypter** crypter,
+ char** error_details);
+
+#endif /* GRPC_CORE_TSI_ALTS_CRYPT_GSEC_H */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.cc b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.cc
index de163e3e08c..2ed3c2c3650 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.cc
@@ -1,118 +1,118 @@
-/*
- *
- * 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/frame_protector/alts_counter.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-static void maybe_copy_error_msg(const char* src, char** dst) {
- if (dst != nullptr && src != nullptr) {
- *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
- memcpy(*dst, src, strlen(src) + 1);
- }
-}
-
-grpc_status_code alts_counter_create(bool is_client, size_t counter_size,
- size_t overflow_size,
- alts_counter** crypter_counter,
- char** error_details) {
- /* Perform input sanity check. */
- if (counter_size == 0) {
- const char error_msg[] = "counter_size is invalid.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (overflow_size == 0 || overflow_size >= counter_size) {
- const char error_msg[] = "overflow_size is invalid.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (crypter_counter == nullptr) {
- const char error_msg[] = "crypter_counter is nullptr.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- *crypter_counter =
- static_cast<alts_counter*>(gpr_malloc(sizeof(**crypter_counter)));
- (*crypter_counter)->size = counter_size;
- (*crypter_counter)->overflow_size = overflow_size;
- (*crypter_counter)->counter =
- static_cast<unsigned char*>(gpr_zalloc(counter_size));
- if (is_client) {
- ((*crypter_counter)->counter)[counter_size - 1] = 0x80;
- }
- return GRPC_STATUS_OK;
-}
-
-grpc_status_code alts_counter_increment(alts_counter* crypter_counter,
- bool* is_overflow,
- char** error_details) {
- /* Perform input sanity check. */
- if (crypter_counter == nullptr) {
- const char error_msg[] = "crypter_counter is nullptr.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (is_overflow == nullptr) {
- const char error_msg[] = "is_overflow is nullptr.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- /* Increment the internal counter. */
- size_t i = 0;
- for (; i < crypter_counter->overflow_size; i++) {
- (crypter_counter->counter)[i]++;
- if ((crypter_counter->counter)[i] != 0x00) {
- break;
- }
- }
- /**
- * If the lower overflow_size bytes are all zero, the counter has overflowed.
- */
- if (i == crypter_counter->overflow_size) {
- *is_overflow = true;
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- *is_overflow = false;
- return GRPC_STATUS_OK;
-}
-
-size_t alts_counter_get_size(alts_counter* crypter_counter) {
- if (crypter_counter == nullptr) {
- return 0;
- }
- return crypter_counter->size;
-}
-
-unsigned char* alts_counter_get_counter(alts_counter* crypter_counter) {
- if (crypter_counter == nullptr) {
- return nullptr;
- }
- return crypter_counter->counter;
-}
-
-void alts_counter_destroy(alts_counter* crypter_counter) {
- if (crypter_counter != nullptr) {
- gpr_free(crypter_counter->counter);
- gpr_free(crypter_counter);
- }
-}
+/*
+ *
+ * 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/frame_protector/alts_counter.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+static void maybe_copy_error_msg(const char* src, char** dst) {
+ if (dst != nullptr && src != nullptr) {
+ *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
+ memcpy(*dst, src, strlen(src) + 1);
+ }
+}
+
+grpc_status_code alts_counter_create(bool is_client, size_t counter_size,
+ size_t overflow_size,
+ alts_counter** crypter_counter,
+ char** error_details) {
+ /* Perform input sanity check. */
+ if (counter_size == 0) {
+ const char error_msg[] = "counter_size is invalid.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (overflow_size == 0 || overflow_size >= counter_size) {
+ const char error_msg[] = "overflow_size is invalid.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (crypter_counter == nullptr) {
+ const char error_msg[] = "crypter_counter is nullptr.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ *crypter_counter =
+ static_cast<alts_counter*>(gpr_malloc(sizeof(**crypter_counter)));
+ (*crypter_counter)->size = counter_size;
+ (*crypter_counter)->overflow_size = overflow_size;
+ (*crypter_counter)->counter =
+ static_cast<unsigned char*>(gpr_zalloc(counter_size));
+ if (is_client) {
+ ((*crypter_counter)->counter)[counter_size - 1] = 0x80;
+ }
+ return GRPC_STATUS_OK;
+}
+
+grpc_status_code alts_counter_increment(alts_counter* crypter_counter,
+ bool* is_overflow,
+ char** error_details) {
+ /* Perform input sanity check. */
+ if (crypter_counter == nullptr) {
+ const char error_msg[] = "crypter_counter is nullptr.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (is_overflow == nullptr) {
+ const char error_msg[] = "is_overflow is nullptr.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ /* Increment the internal counter. */
+ size_t i = 0;
+ for (; i < crypter_counter->overflow_size; i++) {
+ (crypter_counter->counter)[i]++;
+ if ((crypter_counter->counter)[i] != 0x00) {
+ break;
+ }
+ }
+ /**
+ * If the lower overflow_size bytes are all zero, the counter has overflowed.
+ */
+ if (i == crypter_counter->overflow_size) {
+ *is_overflow = true;
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ *is_overflow = false;
+ return GRPC_STATUS_OK;
+}
+
+size_t alts_counter_get_size(alts_counter* crypter_counter) {
+ if (crypter_counter == nullptr) {
+ return 0;
+ }
+ return crypter_counter->size;
+}
+
+unsigned char* alts_counter_get_counter(alts_counter* crypter_counter) {
+ if (crypter_counter == nullptr) {
+ return nullptr;
+ }
+ return crypter_counter->counter;
+}
+
+void alts_counter_destroy(alts_counter* crypter_counter) {
+ if (crypter_counter != nullptr) {
+ gpr_free(crypter_counter->counter);
+ gpr_free(crypter_counter);
+ }
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.h b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.h
index d705638fa8c..f759480ee01 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_counter.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_COUNTER_H
-#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_COUNTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-#include <stdlib.h>
-
-#include <grpc/grpc.h>
-
-/* Main struct for a crypter counter managed within seal/unseal operations. */
-typedef struct alts_counter {
- size_t size;
- size_t overflow_size;
- unsigned char* counter;
-} alts_counter;
-
-/**
- * This method creates and initializes an alts_counter instance.
- *
- * - is_client: a flag indicating if the alts_counter instance will be used
- * at client (is_client = true) or server (is_client = false) side.
- * - counter_size: size of buffer holding the counter value.
- * - overflow_size: overflow size in bytes. The counter instance can be used
- * to produce at most 2^(overflow_size*8) frames.
- * - crypter_counter: an alts_counter instance to be returned from the method.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code alts_counter_create(bool is_client, size_t counter_size,
- size_t overflow_size,
- alts_counter** crypter_counter,
- char** error_details);
-
-/**
- * This method increments the internal counter.
- *
- * - crypter_counter: an alts_counter instance.
- * - is_overflow: after incrementing the internal counter, if an overflow
- * occurs, is_overflow is set to true, and no further calls to
- * alts_counter_increment() should be made. Otherwise, is_overflow is set to
- * false.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code alts_counter_increment(alts_counter* crypter_counter,
- bool* is_overflow,
- char** error_details);
-
-/**
- * This method returns the size of counter buffer.
- *
- * - crypter_counter: an alts_counter instance.
- */
-size_t alts_counter_get_size(alts_counter* crypter_counter);
-
-/**
- * This method returns the counter buffer.
- *
- * - crypter_counter: an alts_counter instance.
- */
-unsigned char* alts_counter_get_counter(alts_counter* crypter_counter);
-
-/**
- * This method de-allocates all memory allocated to an alts_coutner instance.
- * - crypter_counter: an alts_counter instance.
- */
-void alts_counter_destroy(alts_counter* crypter_counter);
-
-#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_COUNTER_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_TSI_ALTS_FRAME_PROTECTOR_ALTS_COUNTER_H
+#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_COUNTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+#include <stdlib.h>
+
+#include <grpc/grpc.h>
+
+/* Main struct for a crypter counter managed within seal/unseal operations. */
+typedef struct alts_counter {
+ size_t size;
+ size_t overflow_size;
+ unsigned char* counter;
+} alts_counter;
+
+/**
+ * This method creates and initializes an alts_counter instance.
+ *
+ * - is_client: a flag indicating if the alts_counter instance will be used
+ * at client (is_client = true) or server (is_client = false) side.
+ * - counter_size: size of buffer holding the counter value.
+ * - overflow_size: overflow size in bytes. The counter instance can be used
+ * to produce at most 2^(overflow_size*8) frames.
+ * - crypter_counter: an alts_counter instance to be returned from the method.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code alts_counter_create(bool is_client, size_t counter_size,
+ size_t overflow_size,
+ alts_counter** crypter_counter,
+ char** error_details);
+
+/**
+ * This method increments the internal counter.
+ *
+ * - crypter_counter: an alts_counter instance.
+ * - is_overflow: after incrementing the internal counter, if an overflow
+ * occurs, is_overflow is set to true, and no further calls to
+ * alts_counter_increment() should be made. Otherwise, is_overflow is set to
+ * false.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code alts_counter_increment(alts_counter* crypter_counter,
+ bool* is_overflow,
+ char** error_details);
+
+/**
+ * This method returns the size of counter buffer.
+ *
+ * - crypter_counter: an alts_counter instance.
+ */
+size_t alts_counter_get_size(alts_counter* crypter_counter);
+
+/**
+ * This method returns the counter buffer.
+ *
+ * - crypter_counter: an alts_counter instance.
+ */
+unsigned char* alts_counter_get_counter(alts_counter* crypter_counter);
+
+/**
+ * This method de-allocates all memory allocated to an alts_coutner instance.
+ * - crypter_counter: an alts_counter instance.
+ */
+void alts_counter_destroy(alts_counter* crypter_counter);
+
+#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_COUNTER_H */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.cc b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.cc
index 56f05121863..164b058db5b 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.cc
@@ -1,66 +1,66 @@
-/*
- *
- * 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/frame_protector/alts_crypter.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-
-static void maybe_copy_error_msg(const char* src, char** dst) {
- if (dst != nullptr && src != nullptr) {
- *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
- memcpy(*dst, src, strlen(src) + 1);
- }
-}
-
-grpc_status_code alts_crypter_process_in_place(
- alts_crypter* crypter, unsigned char* data, size_t data_allocated_size,
- size_t data_size, size_t* output_size, char** error_details) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->process_in_place != nullptr) {
- return crypter->vtable->process_in_place(crypter, data, data_allocated_size,
- data_size, output_size,
- error_details);
- }
- /* An error occurred. */
- const char error_msg[] =
- "crypter or crypter->vtable has not been initialized properly.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
-}
-
-size_t alts_crypter_num_overhead_bytes(const alts_crypter* crypter) {
- if (crypter != nullptr && crypter->vtable != nullptr &&
- crypter->vtable->num_overhead_bytes != nullptr) {
- return crypter->vtable->num_overhead_bytes(crypter);
- }
- /* An error occurred. */
- return 0;
-}
-
-void alts_crypter_destroy(alts_crypter* crypter) {
- if (crypter != nullptr) {
- if (crypter->vtable != nullptr && crypter->vtable->destruct != nullptr) {
- crypter->vtable->destruct(crypter);
- }
- gpr_free(crypter);
- }
-}
+/*
+ *
+ * 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/frame_protector/alts_crypter.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+static void maybe_copy_error_msg(const char* src, char** dst) {
+ if (dst != nullptr && src != nullptr) {
+ *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
+ memcpy(*dst, src, strlen(src) + 1);
+ }
+}
+
+grpc_status_code alts_crypter_process_in_place(
+ alts_crypter* crypter, unsigned char* data, size_t data_allocated_size,
+ size_t data_size, size_t* output_size, char** error_details) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->process_in_place != nullptr) {
+ return crypter->vtable->process_in_place(crypter, data, data_allocated_size,
+ data_size, output_size,
+ error_details);
+ }
+ /* An error occurred. */
+ const char error_msg[] =
+ "crypter or crypter->vtable has not been initialized properly.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+}
+
+size_t alts_crypter_num_overhead_bytes(const alts_crypter* crypter) {
+ if (crypter != nullptr && crypter->vtable != nullptr &&
+ crypter->vtable->num_overhead_bytes != nullptr) {
+ return crypter->vtable->num_overhead_bytes(crypter);
+ }
+ /* An error occurred. */
+ return 0;
+}
+
+void alts_crypter_destroy(alts_crypter* crypter) {
+ if (crypter != nullptr) {
+ if (crypter->vtable != nullptr && crypter->vtable->destruct != nullptr) {
+ crypter->vtable->destruct(crypter);
+ }
+ gpr_free(crypter);
+ }
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.h b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.h
index 3140778f4fc..6b410152947 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_crypter.h
@@ -1,255 +1,255 @@
-/*
- *
- * 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_TSI_ALTS_FRAME_PROTECTOR_ALTS_CRYPTER_H
-#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_CRYPTER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-#include <string.h>
-
-#include <grpc/grpc.h>
-
-#include "src/core/tsi/alts/crypt/gsec.h"
-
-/**
- * An alts_crypter interface for an ALTS record protocol providing
- * seal/unseal functionality. The interface is thread-compatible.
- */
-
-typedef struct alts_crypter alts_crypter;
-
-/**
- * A typical usage of the interface would be
- *------------------------------------------------------------------------------
- * // Perform a seal operation. We assume the gsec_aead_crypter instance -
- * // client_aead_crypter is created beforehand with a 16-byte key and 12-byte
- * // nonce length.
- *
- * alts_crypter* client = nullptr;
- * char* client_error_in_creation = nullptr;
- * unsigned char* data = nullptr;
- * grpc_status_code client_status =
- * alts_seal_crypter_create(client_aead_crypter, 1, 5, &client,
- * &client_error_in_creation);
- * if (client_status == GRPC_STATUS_OK) {
- * size_t data_size = 100;
- * size_t num_overhead_bytes = alts_crypter_num_overhead_bytes(client);
- * size_t data_allocated_size = data_size + num_overhead_bytes;
- * data = gpr_malloc(data_allocated_size);
- * char* client_error_in_seal = nullptr;
- * // Client performs a seal operation.
- * client_status = alts_crypter_process_in_place(client, data,
- * data_allocated_size,
- * &data_size,
- * &client_error_in_seal);
- * if (client_status != GRPC_STATUS_OK) {
- * fprintf(stderr, "seal operation failed with error code:"
- * "%d, message: %s\n", client_status,
- * client_error_in_seal);
- * }
- * gpr_free(client_error_in_seal);
- * } else {
- * fprintf(stderr, "alts_crypter instance creation failed with error"
- * "code: %d, message: %s\n", client_status,
- * client_error_in_creation);
- * }
- *
- * ...
- *
- * gpr_free(client_error_in_creation);
- * alts_crypter_destroy(client);
- *
- * ...
- *
- * // Perform an unseal operation. We assume the gsec_aead_crypter instance -
- * // server_aead_crypter is created beforehand with a 16-byte key and 12-byte
- * // nonce length. The key used in the creation of gsec_aead_crypter instances
- * // at server and client sides should be identical.
- *
- * alts_crypter* server = nullptr;
- * char* server_error_in_creation = nullptr;
- * grpc_status_code server_status =
- * alts_unseal_crypter_create(server_aead_crypter, 0, 5, &server,
- * &server_error_in_creation);
- * if (server_status == GRPC_STATUS_OK) {
- * size_t num_overhead_bytes = alts_crypter_num_overhead_bytes(server);
- * size_t data_size = 100 + num_overhead_bytes;
- * size_t data_allocated_size = data_size;
- * char* server_error_in_unseal = nullptr;
- * // Server performs an unseal operation.
- * server_status = alts_crypter_process_in_place(server, data,
- * data_allocated_size,
- * &data_size,
- * &server_error_in_unseal);
- * if (server_status != GRPC_STATUS_OK) {
- * fprintf(stderr, "unseal operation failed with error code:"
- * "%d, message: %s\n", server_status,
- * server_error_in_unseal);
- * }
- * gpr_free(server_error_in_unseal);
- * } else {
- * fprintf(stderr, "alts_crypter instance creation failed with error"
- * "code: %d, message: %s\n", server_status,
- * server_error_in_creation);
- * }
- *
- * ...
- *
- * gpr_free(data);
- * gpr_free(server_error_in_creation);
- * alts_crypter_destroy(server);
- *
- * ...
- *------------------------------------------------------------------------------
- */
-
-/* V-table for alts_crypter operations */
-typedef struct alts_crypter_vtable {
- size_t (*num_overhead_bytes)(const alts_crypter* crypter);
- grpc_status_code (*process_in_place)(alts_crypter* crypter,
- unsigned char* data,
- size_t data_allocated_size,
- size_t data_size, size_t* output_size,
- char** error_details);
- void (*destruct)(alts_crypter* crypter);
-} alts_crypter_vtable;
-
-/* Main struct for alts_crypter interface */
-struct alts_crypter {
- const alts_crypter_vtable* vtable;
-};
-
-/**
- * This method gets the number of overhead bytes needed for sealing data that
- * is the difference in size between the protected and raw data. The counter
- * value used in a seal or unseal operation is locally maintained (not sent or
- * received from the other peer) and therefore, will not be counted as part of
- * overhead bytes.
- *
- * - crypter: an alts_crypter instance.
- *
- * On success, the method returns the number of overhead bytes. Otherwise, it
- * returns zero.
- *
- */
-size_t alts_crypter_num_overhead_bytes(const alts_crypter* crypter);
-
-/**
- * This method performs either a seal or an unseal operation depending on the
- * alts_crypter instance - crypter passed to the method. If the crypter is
- * an instance implementing a seal operation, the method will perform a seal
- * operation. That is, it seals raw data and stores the result in-place, and the
- * memory allocated for data must be at least data_length +
- * alts_crypter_num_overhead_bytes(). If the crypter is an instance
- * implementing an unseal operation, the method will perform an unseal
- * operation. That is, it unseals protected data and stores the result in-place.
- * The size of unsealed data will be data_length -
- * alts_crypter_num_overhead_bytes(). Integrity tag will be verified during
- * the unseal operation, and if verification fails, the data will be wiped.
- * The counters used in both seal and unseal operations are managed internally.
- *
- * - crypter: an alts_crypter instance.
- * - data: if the method performs a seal operation, the data represents raw data
- * that needs to be sealed. It also plays the role of buffer to hold the
- * protected data as a result of seal. If the method performs an unseal
- * operation, the data represents protected data that needs to be unsealed. It
- * also plays the role of buffer to hold raw data as a result of unseal.
- * - data_allocated_size: the size of data buffer. The parameter is used to
- * check whether the result of either seal or unseal can be safely written to
- * the data buffer.
- * - data_size: if the method performs a seal operation, data_size
- * represents the size of raw data that needs to be sealed, and if the method
- * performs an unseal operation, data_size represents the size of protected
- * data that needs to be unsealed.
- * - output_size: size of data written to the data buffer after a seal or an
- * unseal operation.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is legal to pass nullptr into error_details and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code alts_crypter_process_in_place(
- alts_crypter* crypter, unsigned char* data, size_t data_allocated_size,
- size_t data_size, size_t* output_size, char** error_details);
-
-/**
- * This method creates an alts_crypter instance to be used to perform a seal
- * operation, given a gsec_aead_crypter instance and a flag indicating if the
- * created instance will be used at the client or server side. It takes
- * ownership of gsec_aead_crypter instance.
- *
- * - gc: a gsec_aead_crypter instance used to perform AEAD encryption.
- * - is_client: a flag indicating if the alts_crypter instance will be
- * used at the client (is_client = true) or server (is_client =
- * false) side.
- * - overflow_size: overflow size of counter in bytes.
- * - crypter: an alts_crypter instance to be returned from the method.
- * - error_details: a buffer containing an error message if the method does
- * not function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success of creation, the method returns GRPC_STATUS_OK.
- * Otherwise, it returns an error status code along with its details specified
- * in error_details (if error_details is not nullptr).
- */
-grpc_status_code alts_seal_crypter_create(gsec_aead_crypter* gc, bool is_client,
- size_t overflow_size,
- alts_crypter** crypter,
- char** error_details);
-
-/**
- * This method creates an alts_crypter instance used to perform an unseal
- * operation, given a gsec_aead_crypter instance and a flag indicating if the
- * created instance will be used at the client or server side. It takes
- * ownership of gsec_aead_crypter instance.
- *
- * - gc: a gsec_aead_crypter instance used to perform AEAD decryption.
- * - is_client: a flag indicating if the alts_crypter instance will be
- * used at the client (is_client = true) or server (is_client =
- * false) side.
- * - overflow_size: overflow size of counter in bytes.
- * - crypter: an alts_crypter instance to be returned from the method.
- * - error_details: a buffer containing an error message if the method does
- * not function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success of creation, the method returns GRPC_STATUS_OK.
- * Otherwise, it returns an error status code along with its details specified
- * in error_details (if error_details is not nullptr).
- */
-grpc_status_code alts_unseal_crypter_create(gsec_aead_crypter* gc,
- bool is_client,
- size_t overflow_size,
- alts_crypter** crypter,
- char** error_details);
-
-/**
- * This method destroys an alts_crypter instance by de-allocating all of its
- * occupied memory. A gsec_aead_crypter instance passed in at alts_crypter
- * instance creation time will be destroyed in this method.
- *
- * - crypter: an alts_crypter instance.
- */
-void alts_crypter_destroy(alts_crypter* crypter);
-
-#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_CRYPTER_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_TSI_ALTS_FRAME_PROTECTOR_ALTS_CRYPTER_H
+#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_CRYPTER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+#include <string.h>
+
+#include <grpc/grpc.h>
+
+#include "src/core/tsi/alts/crypt/gsec.h"
+
+/**
+ * An alts_crypter interface for an ALTS record protocol providing
+ * seal/unseal functionality. The interface is thread-compatible.
+ */
+
+typedef struct alts_crypter alts_crypter;
+
+/**
+ * A typical usage of the interface would be
+ *------------------------------------------------------------------------------
+ * // Perform a seal operation. We assume the gsec_aead_crypter instance -
+ * // client_aead_crypter is created beforehand with a 16-byte key and 12-byte
+ * // nonce length.
+ *
+ * alts_crypter* client = nullptr;
+ * char* client_error_in_creation = nullptr;
+ * unsigned char* data = nullptr;
+ * grpc_status_code client_status =
+ * alts_seal_crypter_create(client_aead_crypter, 1, 5, &client,
+ * &client_error_in_creation);
+ * if (client_status == GRPC_STATUS_OK) {
+ * size_t data_size = 100;
+ * size_t num_overhead_bytes = alts_crypter_num_overhead_bytes(client);
+ * size_t data_allocated_size = data_size + num_overhead_bytes;
+ * data = gpr_malloc(data_allocated_size);
+ * char* client_error_in_seal = nullptr;
+ * // Client performs a seal operation.
+ * client_status = alts_crypter_process_in_place(client, data,
+ * data_allocated_size,
+ * &data_size,
+ * &client_error_in_seal);
+ * if (client_status != GRPC_STATUS_OK) {
+ * fprintf(stderr, "seal operation failed with error code:"
+ * "%d, message: %s\n", client_status,
+ * client_error_in_seal);
+ * }
+ * gpr_free(client_error_in_seal);
+ * } else {
+ * fprintf(stderr, "alts_crypter instance creation failed with error"
+ * "code: %d, message: %s\n", client_status,
+ * client_error_in_creation);
+ * }
+ *
+ * ...
+ *
+ * gpr_free(client_error_in_creation);
+ * alts_crypter_destroy(client);
+ *
+ * ...
+ *
+ * // Perform an unseal operation. We assume the gsec_aead_crypter instance -
+ * // server_aead_crypter is created beforehand with a 16-byte key and 12-byte
+ * // nonce length. The key used in the creation of gsec_aead_crypter instances
+ * // at server and client sides should be identical.
+ *
+ * alts_crypter* server = nullptr;
+ * char* server_error_in_creation = nullptr;
+ * grpc_status_code server_status =
+ * alts_unseal_crypter_create(server_aead_crypter, 0, 5, &server,
+ * &server_error_in_creation);
+ * if (server_status == GRPC_STATUS_OK) {
+ * size_t num_overhead_bytes = alts_crypter_num_overhead_bytes(server);
+ * size_t data_size = 100 + num_overhead_bytes;
+ * size_t data_allocated_size = data_size;
+ * char* server_error_in_unseal = nullptr;
+ * // Server performs an unseal operation.
+ * server_status = alts_crypter_process_in_place(server, data,
+ * data_allocated_size,
+ * &data_size,
+ * &server_error_in_unseal);
+ * if (server_status != GRPC_STATUS_OK) {
+ * fprintf(stderr, "unseal operation failed with error code:"
+ * "%d, message: %s\n", server_status,
+ * server_error_in_unseal);
+ * }
+ * gpr_free(server_error_in_unseal);
+ * } else {
+ * fprintf(stderr, "alts_crypter instance creation failed with error"
+ * "code: %d, message: %s\n", server_status,
+ * server_error_in_creation);
+ * }
+ *
+ * ...
+ *
+ * gpr_free(data);
+ * gpr_free(server_error_in_creation);
+ * alts_crypter_destroy(server);
+ *
+ * ...
+ *------------------------------------------------------------------------------
+ */
+
+/* V-table for alts_crypter operations */
+typedef struct alts_crypter_vtable {
+ size_t (*num_overhead_bytes)(const alts_crypter* crypter);
+ grpc_status_code (*process_in_place)(alts_crypter* crypter,
+ unsigned char* data,
+ size_t data_allocated_size,
+ size_t data_size, size_t* output_size,
+ char** error_details);
+ void (*destruct)(alts_crypter* crypter);
+} alts_crypter_vtable;
+
+/* Main struct for alts_crypter interface */
+struct alts_crypter {
+ const alts_crypter_vtable* vtable;
+};
+
+/**
+ * This method gets the number of overhead bytes needed for sealing data that
+ * is the difference in size between the protected and raw data. The counter
+ * value used in a seal or unseal operation is locally maintained (not sent or
+ * received from the other peer) and therefore, will not be counted as part of
+ * overhead bytes.
+ *
+ * - crypter: an alts_crypter instance.
+ *
+ * On success, the method returns the number of overhead bytes. Otherwise, it
+ * returns zero.
+ *
+ */
+size_t alts_crypter_num_overhead_bytes(const alts_crypter* crypter);
+
+/**
+ * This method performs either a seal or an unseal operation depending on the
+ * alts_crypter instance - crypter passed to the method. If the crypter is
+ * an instance implementing a seal operation, the method will perform a seal
+ * operation. That is, it seals raw data and stores the result in-place, and the
+ * memory allocated for data must be at least data_length +
+ * alts_crypter_num_overhead_bytes(). If the crypter is an instance
+ * implementing an unseal operation, the method will perform an unseal
+ * operation. That is, it unseals protected data and stores the result in-place.
+ * The size of unsealed data will be data_length -
+ * alts_crypter_num_overhead_bytes(). Integrity tag will be verified during
+ * the unseal operation, and if verification fails, the data will be wiped.
+ * The counters used in both seal and unseal operations are managed internally.
+ *
+ * - crypter: an alts_crypter instance.
+ * - data: if the method performs a seal operation, the data represents raw data
+ * that needs to be sealed. It also plays the role of buffer to hold the
+ * protected data as a result of seal. If the method performs an unseal
+ * operation, the data represents protected data that needs to be unsealed. It
+ * also plays the role of buffer to hold raw data as a result of unseal.
+ * - data_allocated_size: the size of data buffer. The parameter is used to
+ * check whether the result of either seal or unseal can be safely written to
+ * the data buffer.
+ * - data_size: if the method performs a seal operation, data_size
+ * represents the size of raw data that needs to be sealed, and if the method
+ * performs an unseal operation, data_size represents the size of protected
+ * data that needs to be unsealed.
+ * - output_size: size of data written to the data buffer after a seal or an
+ * unseal operation.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is legal to pass nullptr into error_details and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code alts_crypter_process_in_place(
+ alts_crypter* crypter, unsigned char* data, size_t data_allocated_size,
+ size_t data_size, size_t* output_size, char** error_details);
+
+/**
+ * This method creates an alts_crypter instance to be used to perform a seal
+ * operation, given a gsec_aead_crypter instance and a flag indicating if the
+ * created instance will be used at the client or server side. It takes
+ * ownership of gsec_aead_crypter instance.
+ *
+ * - gc: a gsec_aead_crypter instance used to perform AEAD encryption.
+ * - is_client: a flag indicating if the alts_crypter instance will be
+ * used at the client (is_client = true) or server (is_client =
+ * false) side.
+ * - overflow_size: overflow size of counter in bytes.
+ * - crypter: an alts_crypter instance to be returned from the method.
+ * - error_details: a buffer containing an error message if the method does
+ * not function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success of creation, the method returns GRPC_STATUS_OK.
+ * Otherwise, it returns an error status code along with its details specified
+ * in error_details (if error_details is not nullptr).
+ */
+grpc_status_code alts_seal_crypter_create(gsec_aead_crypter* gc, bool is_client,
+ size_t overflow_size,
+ alts_crypter** crypter,
+ char** error_details);
+
+/**
+ * This method creates an alts_crypter instance used to perform an unseal
+ * operation, given a gsec_aead_crypter instance and a flag indicating if the
+ * created instance will be used at the client or server side. It takes
+ * ownership of gsec_aead_crypter instance.
+ *
+ * - gc: a gsec_aead_crypter instance used to perform AEAD decryption.
+ * - is_client: a flag indicating if the alts_crypter instance will be
+ * used at the client (is_client = true) or server (is_client =
+ * false) side.
+ * - overflow_size: overflow size of counter in bytes.
+ * - crypter: an alts_crypter instance to be returned from the method.
+ * - error_details: a buffer containing an error message if the method does
+ * not function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success of creation, the method returns GRPC_STATUS_OK.
+ * Otherwise, it returns an error status code along with its details specified
+ * in error_details (if error_details is not nullptr).
+ */
+grpc_status_code alts_unseal_crypter_create(gsec_aead_crypter* gc,
+ bool is_client,
+ size_t overflow_size,
+ alts_crypter** crypter,
+ char** error_details);
+
+/**
+ * This method destroys an alts_crypter instance by de-allocating all of its
+ * occupied memory. A gsec_aead_crypter instance passed in at alts_crypter
+ * instance creation time will be destroyed in this method.
+ *
+ * - crypter: an alts_crypter instance.
+ */
+void alts_crypter_destroy(alts_crypter* crypter);
+
+#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_CRYPTER_H */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.cc b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.cc
index bfa0b7a720f..74473ad811f 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.cc
@@ -1,407 +1,407 @@
-/*
- *
- * 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/frame_protector/alts_frame_protector.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/tsi/alts/crypt/gsec.h"
-#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
-#include "src/core/tsi/alts/frame_protector/frame_handler.h"
-#include "src/core/tsi/transport_security.h"
-
-constexpr size_t kMinFrameLength = 1024;
-constexpr size_t kDefaultFrameLength = 16 * 1024;
-constexpr size_t kMaxFrameLength = 1024 * 1024;
-
-// Limit k on number of frames such that at most 2^(8 * k) frames can be sent.
-constexpr size_t kAltsRecordProtocolRekeyFrameLimit = 8;
-constexpr size_t kAltsRecordProtocolFrameLimit = 5;
-
-/* Main struct for alts_frame_protector. */
-struct alts_frame_protector {
- tsi_frame_protector base;
- alts_crypter* seal_crypter;
- alts_crypter* unseal_crypter;
- alts_frame_writer* writer;
- alts_frame_reader* reader;
- unsigned char* in_place_protect_buffer;
- unsigned char* in_place_unprotect_buffer;
- size_t in_place_protect_bytes_buffered;
- size_t in_place_unprotect_bytes_processed;
- size_t max_protected_frame_size;
- size_t max_unprotected_frame_size;
- size_t overhead_length;
- size_t counter_overflow;
-};
-
-static tsi_result seal(alts_frame_protector* impl) {
- char* error_details = nullptr;
- size_t output_size = 0;
- grpc_status_code status = alts_crypter_process_in_place(
- impl->seal_crypter, impl->in_place_protect_buffer,
- impl->max_protected_frame_size, impl->in_place_protect_bytes_buffered,
- &output_size, &error_details);
- impl->in_place_protect_bytes_buffered = output_size;
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "%s", error_details);
- gpr_free(error_details);
- return TSI_INTERNAL_ERROR;
- }
- return TSI_OK;
-}
-
-static size_t max_encrypted_payload_bytes(alts_frame_protector* impl) {
- return impl->max_protected_frame_size - kFrameHeaderSize;
-}
-
-static tsi_result alts_protect_flush(tsi_frame_protector* self,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size,
- size_t* still_pending_size) {
- if (self == nullptr || protected_output_frames == nullptr ||
- protected_output_frames_size == nullptr ||
- still_pending_size == nullptr) {
- gpr_log(GPR_ERROR, "Invalid nullptr arguments to alts_protect_flush().");
- return TSI_INVALID_ARGUMENT;
- }
- alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
- /**
- * If there's nothing to flush (i.e., in_place_protect_buffer is empty),
- * we're done.
- */
- if (impl->in_place_protect_bytes_buffered == 0) {
- *protected_output_frames_size = 0;
- *still_pending_size = 0;
- return TSI_OK;
- }
- /**
- * If a new frame can start being processed, we encrypt the payload and reset
- * the frame writer to point to in_place_protect_buffer that holds the newly
- * sealed frame.
- */
- if (alts_is_frame_writer_done(impl->writer)) {
- tsi_result result = seal(impl);
- if (result != TSI_OK) {
- return result;
- }
- if (!alts_reset_frame_writer(impl->writer, impl->in_place_protect_buffer,
- impl->in_place_protect_bytes_buffered)) {
- gpr_log(GPR_ERROR, "Couldn't reset frame writer.");
- return TSI_INTERNAL_ERROR;
- }
- }
- /**
- * Write the sealed frame as much as possible to protected_output_frames. It's
- * possible a frame will not be written out completely by a single flush
- * (i.e., still_pending_size != 0), in which case the flush should be called
- * iteratively until a complete frame has been written out.
- */
- size_t written_frame_bytes = *protected_output_frames_size;
- if (!alts_write_frame_bytes(impl->writer, protected_output_frames,
- &written_frame_bytes)) {
- gpr_log(GPR_ERROR, "Couldn't write frame bytes.");
- return TSI_INTERNAL_ERROR;
- }
- *protected_output_frames_size = written_frame_bytes;
- *still_pending_size = alts_get_num_writer_bytes_remaining(impl->writer);
- /**
- * If the current frame has been finished processing (i.e., sealed and written
- * out completely), we empty in_place_protect_buffer.
- */
- if (alts_is_frame_writer_done(impl->writer)) {
- impl->in_place_protect_bytes_buffered = 0;
- }
- return TSI_OK;
-}
-
-static tsi_result alts_protect(tsi_frame_protector* self,
- const unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size) {
- if (self == nullptr || unprotected_bytes == nullptr ||
- unprotected_bytes_size == nullptr || protected_output_frames == nullptr ||
- protected_output_frames_size == nullptr) {
- gpr_log(GPR_ERROR, "Invalid nullptr arguments to alts_protect().");
- return TSI_INVALID_ARGUMENT;
- }
- alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
-
- /**
- * If more payload can be buffered, we buffer it as much as possible to
- * in_place_protect_buffer.
- */
- if (impl->in_place_protect_bytes_buffered + impl->overhead_length <
- max_encrypted_payload_bytes(impl)) {
- size_t bytes_to_buffer = GPR_MIN(*unprotected_bytes_size,
- max_encrypted_payload_bytes(impl) -
- impl->in_place_protect_bytes_buffered -
- impl->overhead_length);
- *unprotected_bytes_size = bytes_to_buffer;
- if (bytes_to_buffer > 0) {
- memcpy(
- impl->in_place_protect_buffer + impl->in_place_protect_bytes_buffered,
- unprotected_bytes, bytes_to_buffer);
- impl->in_place_protect_bytes_buffered += bytes_to_buffer;
- }
- } else {
- *unprotected_bytes_size = 0;
- }
- /**
- * If a full frame has been buffered, we output it. If the first condition
- * holds, then there exists an unencrypted full frame. If the second
- * condition holds, then there exists a full frame that has already been
- * encrypted.
- */
- if (max_encrypted_payload_bytes(impl) ==
- impl->in_place_protect_bytes_buffered + impl->overhead_length ||
- max_encrypted_payload_bytes(impl) ==
- impl->in_place_protect_bytes_buffered) {
- size_t still_pending_size = 0;
- return alts_protect_flush(self, protected_output_frames,
- protected_output_frames_size,
- &still_pending_size);
- } else {
- *protected_output_frames_size = 0;
- return TSI_OK;
- }
-}
-
-static tsi_result unseal(alts_frame_protector* impl) {
- char* error_details = nullptr;
- size_t output_size = 0;
- grpc_status_code status = alts_crypter_process_in_place(
- impl->unseal_crypter, impl->in_place_unprotect_buffer,
- impl->max_unprotected_frame_size,
- alts_get_output_bytes_read(impl->reader), &output_size, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "%s", error_details);
- gpr_free(error_details);
- return TSI_DATA_CORRUPTED;
- }
- return TSI_OK;
-}
-
-static void ensure_buffer_size(alts_frame_protector* impl) {
- if (!alts_has_read_frame_length(impl->reader)) {
- return;
- }
- size_t buffer_space_remaining = impl->max_unprotected_frame_size -
- alts_get_output_bytes_read(impl->reader);
- /**
- * Check if we need to resize in_place_unprotect_buffer in order to hold
- * remaining bytes of a full frame.
- */
- if (buffer_space_remaining < alts_get_reader_bytes_remaining(impl->reader)) {
- size_t buffer_len = alts_get_output_bytes_read(impl->reader) +
- alts_get_reader_bytes_remaining(impl->reader);
- unsigned char* buffer = static_cast<unsigned char*>(gpr_malloc(buffer_len));
- memcpy(buffer, impl->in_place_unprotect_buffer,
- alts_get_output_bytes_read(impl->reader));
- impl->max_unprotected_frame_size = buffer_len;
- gpr_free(impl->in_place_unprotect_buffer);
- impl->in_place_unprotect_buffer = buffer;
- alts_reset_reader_output_buffer(
- impl->reader, buffer + alts_get_output_bytes_read(impl->reader));
- }
-}
-
-static tsi_result alts_unprotect(tsi_frame_protector* self,
- const unsigned char* protected_frames_bytes,
- size_t* protected_frames_bytes_size,
- unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size) {
- if (self == nullptr || protected_frames_bytes == nullptr ||
- protected_frames_bytes_size == nullptr || unprotected_bytes == nullptr ||
- unprotected_bytes_size == nullptr) {
- gpr_log(GPR_ERROR, "Invalid nullptr arguments to alts_unprotect().");
- return TSI_INVALID_ARGUMENT;
- }
- alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
- /**
- * If a new frame can start being processed, we reset the frame reader to
- * point to in_place_unprotect_buffer that will be used to hold deframed
- * result.
- */
- if (alts_is_frame_reader_done(impl->reader) &&
- ((alts_get_output_buffer(impl->reader) == nullptr) ||
- (alts_get_output_bytes_read(impl->reader) ==
- impl->in_place_unprotect_bytes_processed + impl->overhead_length))) {
- if (!alts_reset_frame_reader(impl->reader,
- impl->in_place_unprotect_buffer)) {
- gpr_log(GPR_ERROR, "Couldn't reset frame reader.");
- return TSI_INTERNAL_ERROR;
- }
- impl->in_place_unprotect_bytes_processed = 0;
- }
- /**
- * If a full frame has not yet been read, we read more bytes from
- * protected_frames_bytes until a full frame has been read. We also need to
- * make sure in_place_unprotect_buffer is large enough to hold a complete
- * frame.
- */
- if (!alts_is_frame_reader_done(impl->reader)) {
- ensure_buffer_size(impl);
- *protected_frames_bytes_size =
- GPR_MIN(impl->max_unprotected_frame_size -
- alts_get_output_bytes_read(impl->reader),
- *protected_frames_bytes_size);
- size_t read_frames_bytes_size = *protected_frames_bytes_size;
- if (!alts_read_frame_bytes(impl->reader, protected_frames_bytes,
- &read_frames_bytes_size)) {
- gpr_log(GPR_ERROR, "Failed to process frame.");
- return TSI_INTERNAL_ERROR;
- }
- *protected_frames_bytes_size = read_frames_bytes_size;
- } else {
- *protected_frames_bytes_size = 0;
- }
- /**
- * If a full frame has been read, we unseal it, and write out the
- * deframed result to unprotected_bytes.
- */
- if (alts_is_frame_reader_done(impl->reader)) {
- if (impl->in_place_unprotect_bytes_processed == 0) {
- tsi_result result = unseal(impl);
- if (result != TSI_OK) {
- return result;
- }
- }
- size_t bytes_to_write = GPR_MIN(
- *unprotected_bytes_size, alts_get_output_bytes_read(impl->reader) -
- impl->in_place_unprotect_bytes_processed -
- impl->overhead_length);
- if (bytes_to_write > 0) {
- memcpy(unprotected_bytes,
- impl->in_place_unprotect_buffer +
- impl->in_place_unprotect_bytes_processed,
- bytes_to_write);
- }
- *unprotected_bytes_size = bytes_to_write;
- impl->in_place_unprotect_bytes_processed += bytes_to_write;
- return TSI_OK;
- } else {
- *unprotected_bytes_size = 0;
- return TSI_OK;
- }
-}
-
-static void alts_destroy(tsi_frame_protector* self) {
- alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
- if (impl != nullptr) {
- alts_crypter_destroy(impl->seal_crypter);
- alts_crypter_destroy(impl->unseal_crypter);
- gpr_free(impl->in_place_protect_buffer);
- gpr_free(impl->in_place_unprotect_buffer);
- alts_destroy_frame_writer(impl->writer);
- alts_destroy_frame_reader(impl->reader);
- gpr_free(impl);
- }
-}
-
-static const tsi_frame_protector_vtable alts_frame_protector_vtable = {
- alts_protect, alts_protect_flush, alts_unprotect, alts_destroy};
-
-static grpc_status_code create_alts_crypters(const uint8_t* key,
- size_t key_size, bool is_client,
- bool is_rekey,
- alts_frame_protector* impl,
- char** error_details) {
- grpc_status_code status;
- gsec_aead_crypter* aead_crypter_seal = nullptr;
- gsec_aead_crypter* aead_crypter_unseal = nullptr;
- status = gsec_aes_gcm_aead_crypter_create(key, key_size, kAesGcmNonceLength,
- kAesGcmTagLength, is_rekey,
- &aead_crypter_seal, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- status = gsec_aes_gcm_aead_crypter_create(
- key, key_size, kAesGcmNonceLength, kAesGcmTagLength, is_rekey,
- &aead_crypter_unseal, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- size_t overflow_size = is_rekey ? kAltsRecordProtocolRekeyFrameLimit
- : kAltsRecordProtocolFrameLimit;
- status = alts_seal_crypter_create(aead_crypter_seal, is_client, overflow_size,
- &impl->seal_crypter, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- status =
- alts_unseal_crypter_create(aead_crypter_unseal, is_client, overflow_size,
- &impl->unseal_crypter, error_details);
- return status;
-}
-
-tsi_result alts_create_frame_protector(const uint8_t* key, size_t key_size,
- bool is_client, bool is_rekey,
- size_t* max_protected_frame_size,
- tsi_frame_protector** self) {
- if (key == nullptr || self == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to alts_create_frame_protector().");
- return TSI_INTERNAL_ERROR;
- }
- char* error_details = nullptr;
- alts_frame_protector* impl =
- static_cast<alts_frame_protector*>(gpr_zalloc(sizeof(*impl)));
- grpc_status_code status = create_alts_crypters(
- key, key_size, is_client, is_rekey, impl, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to create ALTS crypters, %s.", error_details);
- gpr_free(error_details);
- return TSI_INTERNAL_ERROR;
- }
- /**
- * Set maximum frame size to be used by a frame protector. If it is nullptr, a
- * default frame size will be used. Otherwise, the provided frame size will be
- * adjusted (if not falling into a valid frame range) and used.
- */
- size_t max_protected_frame_size_to_set = kDefaultFrameLength;
- if (max_protected_frame_size != nullptr) {
- *max_protected_frame_size =
- GPR_MIN(*max_protected_frame_size, kMaxFrameLength);
- *max_protected_frame_size =
- GPR_MAX(*max_protected_frame_size, kMinFrameLength);
- max_protected_frame_size_to_set = *max_protected_frame_size;
- }
- impl->max_protected_frame_size = max_protected_frame_size_to_set;
- impl->max_unprotected_frame_size = max_protected_frame_size_to_set;
- impl->in_place_protect_bytes_buffered = 0;
- impl->in_place_unprotect_bytes_processed = 0;
- impl->in_place_protect_buffer = static_cast<unsigned char*>(
- gpr_malloc(sizeof(unsigned char) * max_protected_frame_size_to_set));
- impl->in_place_unprotect_buffer = static_cast<unsigned char*>(
- gpr_malloc(sizeof(unsigned char) * max_protected_frame_size_to_set));
- impl->overhead_length = alts_crypter_num_overhead_bytes(impl->seal_crypter);
- impl->writer = alts_create_frame_writer();
- impl->reader = alts_create_frame_reader();
- impl->base.vtable = &alts_frame_protector_vtable;
- *self = &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/frame_protector/alts_frame_protector.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/tsi/alts/crypt/gsec.h"
+#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
+#include "src/core/tsi/alts/frame_protector/frame_handler.h"
+#include "src/core/tsi/transport_security.h"
+
+constexpr size_t kMinFrameLength = 1024;
+constexpr size_t kDefaultFrameLength = 16 * 1024;
+constexpr size_t kMaxFrameLength = 1024 * 1024;
+
+// Limit k on number of frames such that at most 2^(8 * k) frames can be sent.
+constexpr size_t kAltsRecordProtocolRekeyFrameLimit = 8;
+constexpr size_t kAltsRecordProtocolFrameLimit = 5;
+
+/* Main struct for alts_frame_protector. */
+struct alts_frame_protector {
+ tsi_frame_protector base;
+ alts_crypter* seal_crypter;
+ alts_crypter* unseal_crypter;
+ alts_frame_writer* writer;
+ alts_frame_reader* reader;
+ unsigned char* in_place_protect_buffer;
+ unsigned char* in_place_unprotect_buffer;
+ size_t in_place_protect_bytes_buffered;
+ size_t in_place_unprotect_bytes_processed;
+ size_t max_protected_frame_size;
+ size_t max_unprotected_frame_size;
+ size_t overhead_length;
+ size_t counter_overflow;
+};
+
+static tsi_result seal(alts_frame_protector* impl) {
+ char* error_details = nullptr;
+ size_t output_size = 0;
+ grpc_status_code status = alts_crypter_process_in_place(
+ impl->seal_crypter, impl->in_place_protect_buffer,
+ impl->max_protected_frame_size, impl->in_place_protect_bytes_buffered,
+ &output_size, &error_details);
+ impl->in_place_protect_bytes_buffered = output_size;
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "%s", error_details);
+ gpr_free(error_details);
+ return TSI_INTERNAL_ERROR;
+ }
+ return TSI_OK;
+}
+
+static size_t max_encrypted_payload_bytes(alts_frame_protector* impl) {
+ return impl->max_protected_frame_size - kFrameHeaderSize;
+}
+
+static tsi_result alts_protect_flush(tsi_frame_protector* self,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size,
+ size_t* still_pending_size) {
+ if (self == nullptr || protected_output_frames == nullptr ||
+ protected_output_frames_size == nullptr ||
+ still_pending_size == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid nullptr arguments to alts_protect_flush().");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
+ /**
+ * If there's nothing to flush (i.e., in_place_protect_buffer is empty),
+ * we're done.
+ */
+ if (impl->in_place_protect_bytes_buffered == 0) {
+ *protected_output_frames_size = 0;
+ *still_pending_size = 0;
+ return TSI_OK;
+ }
+ /**
+ * If a new frame can start being processed, we encrypt the payload and reset
+ * the frame writer to point to in_place_protect_buffer that holds the newly
+ * sealed frame.
+ */
+ if (alts_is_frame_writer_done(impl->writer)) {
+ tsi_result result = seal(impl);
+ if (result != TSI_OK) {
+ return result;
+ }
+ if (!alts_reset_frame_writer(impl->writer, impl->in_place_protect_buffer,
+ impl->in_place_protect_bytes_buffered)) {
+ gpr_log(GPR_ERROR, "Couldn't reset frame writer.");
+ return TSI_INTERNAL_ERROR;
+ }
+ }
+ /**
+ * Write the sealed frame as much as possible to protected_output_frames. It's
+ * possible a frame will not be written out completely by a single flush
+ * (i.e., still_pending_size != 0), in which case the flush should be called
+ * iteratively until a complete frame has been written out.
+ */
+ size_t written_frame_bytes = *protected_output_frames_size;
+ if (!alts_write_frame_bytes(impl->writer, protected_output_frames,
+ &written_frame_bytes)) {
+ gpr_log(GPR_ERROR, "Couldn't write frame bytes.");
+ return TSI_INTERNAL_ERROR;
+ }
+ *protected_output_frames_size = written_frame_bytes;
+ *still_pending_size = alts_get_num_writer_bytes_remaining(impl->writer);
+ /**
+ * If the current frame has been finished processing (i.e., sealed and written
+ * out completely), we empty in_place_protect_buffer.
+ */
+ if (alts_is_frame_writer_done(impl->writer)) {
+ impl->in_place_protect_bytes_buffered = 0;
+ }
+ return TSI_OK;
+}
+
+static tsi_result alts_protect(tsi_frame_protector* self,
+ const unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size) {
+ if (self == nullptr || unprotected_bytes == nullptr ||
+ unprotected_bytes_size == nullptr || protected_output_frames == nullptr ||
+ protected_output_frames_size == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid nullptr arguments to alts_protect().");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
+
+ /**
+ * If more payload can be buffered, we buffer it as much as possible to
+ * in_place_protect_buffer.
+ */
+ if (impl->in_place_protect_bytes_buffered + impl->overhead_length <
+ max_encrypted_payload_bytes(impl)) {
+ size_t bytes_to_buffer = GPR_MIN(*unprotected_bytes_size,
+ max_encrypted_payload_bytes(impl) -
+ impl->in_place_protect_bytes_buffered -
+ impl->overhead_length);
+ *unprotected_bytes_size = bytes_to_buffer;
+ if (bytes_to_buffer > 0) {
+ memcpy(
+ impl->in_place_protect_buffer + impl->in_place_protect_bytes_buffered,
+ unprotected_bytes, bytes_to_buffer);
+ impl->in_place_protect_bytes_buffered += bytes_to_buffer;
+ }
+ } else {
+ *unprotected_bytes_size = 0;
+ }
+ /**
+ * If a full frame has been buffered, we output it. If the first condition
+ * holds, then there exists an unencrypted full frame. If the second
+ * condition holds, then there exists a full frame that has already been
+ * encrypted.
+ */
+ if (max_encrypted_payload_bytes(impl) ==
+ impl->in_place_protect_bytes_buffered + impl->overhead_length ||
+ max_encrypted_payload_bytes(impl) ==
+ impl->in_place_protect_bytes_buffered) {
+ size_t still_pending_size = 0;
+ return alts_protect_flush(self, protected_output_frames,
+ protected_output_frames_size,
+ &still_pending_size);
+ } else {
+ *protected_output_frames_size = 0;
+ return TSI_OK;
+ }
+}
+
+static tsi_result unseal(alts_frame_protector* impl) {
+ char* error_details = nullptr;
+ size_t output_size = 0;
+ grpc_status_code status = alts_crypter_process_in_place(
+ impl->unseal_crypter, impl->in_place_unprotect_buffer,
+ impl->max_unprotected_frame_size,
+ alts_get_output_bytes_read(impl->reader), &output_size, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "%s", error_details);
+ gpr_free(error_details);
+ return TSI_DATA_CORRUPTED;
+ }
+ return TSI_OK;
+}
+
+static void ensure_buffer_size(alts_frame_protector* impl) {
+ if (!alts_has_read_frame_length(impl->reader)) {
+ return;
+ }
+ size_t buffer_space_remaining = impl->max_unprotected_frame_size -
+ alts_get_output_bytes_read(impl->reader);
+ /**
+ * Check if we need to resize in_place_unprotect_buffer in order to hold
+ * remaining bytes of a full frame.
+ */
+ if (buffer_space_remaining < alts_get_reader_bytes_remaining(impl->reader)) {
+ size_t buffer_len = alts_get_output_bytes_read(impl->reader) +
+ alts_get_reader_bytes_remaining(impl->reader);
+ unsigned char* buffer = static_cast<unsigned char*>(gpr_malloc(buffer_len));
+ memcpy(buffer, impl->in_place_unprotect_buffer,
+ alts_get_output_bytes_read(impl->reader));
+ impl->max_unprotected_frame_size = buffer_len;
+ gpr_free(impl->in_place_unprotect_buffer);
+ impl->in_place_unprotect_buffer = buffer;
+ alts_reset_reader_output_buffer(
+ impl->reader, buffer + alts_get_output_bytes_read(impl->reader));
+ }
+}
+
+static tsi_result alts_unprotect(tsi_frame_protector* self,
+ const unsigned char* protected_frames_bytes,
+ size_t* protected_frames_bytes_size,
+ unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size) {
+ if (self == nullptr || protected_frames_bytes == nullptr ||
+ protected_frames_bytes_size == nullptr || unprotected_bytes == nullptr ||
+ unprotected_bytes_size == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid nullptr arguments to alts_unprotect().");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
+ /**
+ * If a new frame can start being processed, we reset the frame reader to
+ * point to in_place_unprotect_buffer that will be used to hold deframed
+ * result.
+ */
+ if (alts_is_frame_reader_done(impl->reader) &&
+ ((alts_get_output_buffer(impl->reader) == nullptr) ||
+ (alts_get_output_bytes_read(impl->reader) ==
+ impl->in_place_unprotect_bytes_processed + impl->overhead_length))) {
+ if (!alts_reset_frame_reader(impl->reader,
+ impl->in_place_unprotect_buffer)) {
+ gpr_log(GPR_ERROR, "Couldn't reset frame reader.");
+ return TSI_INTERNAL_ERROR;
+ }
+ impl->in_place_unprotect_bytes_processed = 0;
+ }
+ /**
+ * If a full frame has not yet been read, we read more bytes from
+ * protected_frames_bytes until a full frame has been read. We also need to
+ * make sure in_place_unprotect_buffer is large enough to hold a complete
+ * frame.
+ */
+ if (!alts_is_frame_reader_done(impl->reader)) {
+ ensure_buffer_size(impl);
+ *protected_frames_bytes_size =
+ GPR_MIN(impl->max_unprotected_frame_size -
+ alts_get_output_bytes_read(impl->reader),
+ *protected_frames_bytes_size);
+ size_t read_frames_bytes_size = *protected_frames_bytes_size;
+ if (!alts_read_frame_bytes(impl->reader, protected_frames_bytes,
+ &read_frames_bytes_size)) {
+ gpr_log(GPR_ERROR, "Failed to process frame.");
+ return TSI_INTERNAL_ERROR;
+ }
+ *protected_frames_bytes_size = read_frames_bytes_size;
+ } else {
+ *protected_frames_bytes_size = 0;
+ }
+ /**
+ * If a full frame has been read, we unseal it, and write out the
+ * deframed result to unprotected_bytes.
+ */
+ if (alts_is_frame_reader_done(impl->reader)) {
+ if (impl->in_place_unprotect_bytes_processed == 0) {
+ tsi_result result = unseal(impl);
+ if (result != TSI_OK) {
+ return result;
+ }
+ }
+ size_t bytes_to_write = GPR_MIN(
+ *unprotected_bytes_size, alts_get_output_bytes_read(impl->reader) -
+ impl->in_place_unprotect_bytes_processed -
+ impl->overhead_length);
+ if (bytes_to_write > 0) {
+ memcpy(unprotected_bytes,
+ impl->in_place_unprotect_buffer +
+ impl->in_place_unprotect_bytes_processed,
+ bytes_to_write);
+ }
+ *unprotected_bytes_size = bytes_to_write;
+ impl->in_place_unprotect_bytes_processed += bytes_to_write;
+ return TSI_OK;
+ } else {
+ *unprotected_bytes_size = 0;
+ return TSI_OK;
+ }
+}
+
+static void alts_destroy(tsi_frame_protector* self) {
+ alts_frame_protector* impl = reinterpret_cast<alts_frame_protector*>(self);
+ if (impl != nullptr) {
+ alts_crypter_destroy(impl->seal_crypter);
+ alts_crypter_destroy(impl->unseal_crypter);
+ gpr_free(impl->in_place_protect_buffer);
+ gpr_free(impl->in_place_unprotect_buffer);
+ alts_destroy_frame_writer(impl->writer);
+ alts_destroy_frame_reader(impl->reader);
+ gpr_free(impl);
+ }
+}
+
+static const tsi_frame_protector_vtable alts_frame_protector_vtable = {
+ alts_protect, alts_protect_flush, alts_unprotect, alts_destroy};
+
+static grpc_status_code create_alts_crypters(const uint8_t* key,
+ size_t key_size, bool is_client,
+ bool is_rekey,
+ alts_frame_protector* impl,
+ char** error_details) {
+ grpc_status_code status;
+ gsec_aead_crypter* aead_crypter_seal = nullptr;
+ gsec_aead_crypter* aead_crypter_unseal = nullptr;
+ status = gsec_aes_gcm_aead_crypter_create(key, key_size, kAesGcmNonceLength,
+ kAesGcmTagLength, is_rekey,
+ &aead_crypter_seal, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ status = gsec_aes_gcm_aead_crypter_create(
+ key, key_size, kAesGcmNonceLength, kAesGcmTagLength, is_rekey,
+ &aead_crypter_unseal, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ size_t overflow_size = is_rekey ? kAltsRecordProtocolRekeyFrameLimit
+ : kAltsRecordProtocolFrameLimit;
+ status = alts_seal_crypter_create(aead_crypter_seal, is_client, overflow_size,
+ &impl->seal_crypter, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ status =
+ alts_unseal_crypter_create(aead_crypter_unseal, is_client, overflow_size,
+ &impl->unseal_crypter, error_details);
+ return status;
+}
+
+tsi_result alts_create_frame_protector(const uint8_t* key, size_t key_size,
+ bool is_client, bool is_rekey,
+ size_t* max_protected_frame_size,
+ tsi_frame_protector** self) {
+ if (key == nullptr || self == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to alts_create_frame_protector().");
+ return TSI_INTERNAL_ERROR;
+ }
+ char* error_details = nullptr;
+ alts_frame_protector* impl =
+ static_cast<alts_frame_protector*>(gpr_zalloc(sizeof(*impl)));
+ grpc_status_code status = create_alts_crypters(
+ key, key_size, is_client, is_rekey, impl, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to create ALTS crypters, %s.", error_details);
+ gpr_free(error_details);
+ return TSI_INTERNAL_ERROR;
+ }
+ /**
+ * Set maximum frame size to be used by a frame protector. If it is nullptr, a
+ * default frame size will be used. Otherwise, the provided frame size will be
+ * adjusted (if not falling into a valid frame range) and used.
+ */
+ size_t max_protected_frame_size_to_set = kDefaultFrameLength;
+ if (max_protected_frame_size != nullptr) {
+ *max_protected_frame_size =
+ GPR_MIN(*max_protected_frame_size, kMaxFrameLength);
+ *max_protected_frame_size =
+ GPR_MAX(*max_protected_frame_size, kMinFrameLength);
+ max_protected_frame_size_to_set = *max_protected_frame_size;
+ }
+ impl->max_protected_frame_size = max_protected_frame_size_to_set;
+ impl->max_unprotected_frame_size = max_protected_frame_size_to_set;
+ impl->in_place_protect_bytes_buffered = 0;
+ impl->in_place_unprotect_bytes_processed = 0;
+ impl->in_place_protect_buffer = static_cast<unsigned char*>(
+ gpr_malloc(sizeof(unsigned char) * max_protected_frame_size_to_set));
+ impl->in_place_unprotect_buffer = static_cast<unsigned char*>(
+ gpr_malloc(sizeof(unsigned char) * max_protected_frame_size_to_set));
+ impl->overhead_length = alts_crypter_num_overhead_bytes(impl->seal_crypter);
+ impl->writer = alts_create_frame_writer();
+ impl->reader = alts_create_frame_reader();
+ impl->base.vtable = &alts_frame_protector_vtable;
+ *self = &impl->base;
+ return TSI_OK;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.h b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.h
index 321bffaed84..e128d2b2982 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_frame_protector.h
@@ -1,55 +1,55 @@
-/*
- *
- * 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_TSI_ALTS_FRAME_PROTECTOR_ALTS_FRAME_PROTECTOR_H
-#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_FRAME_PROTECTOR_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include "src/core/tsi/transport_security_interface.h"
-
-typedef struct alts_frame_protector alts_frame_protector;
-
-/**
- * TODO: Add a parameter to the interface to support the use of
- * different record protocols within a frame protector.
- *
- * This method creates a frame protector.
- *
- * - key: a symmetric key used to seal/unseal frames.
- * - key_size: the size of symmetric key.
- * - is_client: a flag indicating if the frame protector will be used at client
- * (is_client = true) or server (is_client = false) side.
- * - is_rekey: a flag indicating if the frame protector will use an AEAD with
- * rekeying.
- * - max_protected_frame_size: an in/out parameter indicating max frame size
- * to be used by the frame protector. If it is nullptr, the default frame
- * size will be used. Otherwise, the provided frame size will be adjusted (if
- * not falling into a valid frame range) and used.
- * - self: a pointer to the frame protector returned from the method.
- *
- * This method returns TSI_OK on success and TSI_INTERNAL_ERROR otherwise.
- */
-tsi_result alts_create_frame_protector(const uint8_t* key, size_t key_size,
- bool is_client, bool is_rekey,
- size_t* max_protected_frame_size,
- tsi_frame_protector** self);
-
-#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_FRAME_PROTECTOR_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_TSI_ALTS_FRAME_PROTECTOR_ALTS_FRAME_PROTECTOR_H
+#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_FRAME_PROTECTOR_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include "src/core/tsi/transport_security_interface.h"
+
+typedef struct alts_frame_protector alts_frame_protector;
+
+/**
+ * TODO: Add a parameter to the interface to support the use of
+ * different record protocols within a frame protector.
+ *
+ * This method creates a frame protector.
+ *
+ * - key: a symmetric key used to seal/unseal frames.
+ * - key_size: the size of symmetric key.
+ * - is_client: a flag indicating if the frame protector will be used at client
+ * (is_client = true) or server (is_client = false) side.
+ * - is_rekey: a flag indicating if the frame protector will use an AEAD with
+ * rekeying.
+ * - max_protected_frame_size: an in/out parameter indicating max frame size
+ * to be used by the frame protector. If it is nullptr, the default frame
+ * size will be used. Otherwise, the provided frame size will be adjusted (if
+ * not falling into a valid frame range) and used.
+ * - self: a pointer to the frame protector returned from the method.
+ *
+ * This method returns TSI_OK on success and TSI_INTERNAL_ERROR otherwise.
+ */
+tsi_result alts_create_frame_protector(const uint8_t* key, size_t key_size,
+ bool is_client, bool is_rekey,
+ size_t* max_protected_frame_size,
+ tsi_frame_protector** self);
+
+#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_FRAME_PROTECTOR_H */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc
index 0574ed5012e..ab8dd598229 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc
@@ -1,114 +1,114 @@
-/*
- *
- * 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/frame_protector/alts_record_protocol_crypter_common.h"
-
-#include <grpc/support/alloc.h>
-
-static void maybe_copy_error_msg(const char* src, char** dst) {
- if (dst != nullptr && src != nullptr) {
- *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
- memcpy(*dst, src, strlen(src) + 1);
- }
-}
-
-grpc_status_code input_sanity_check(
- const alts_record_protocol_crypter* rp_crypter, const unsigned char* data,
- size_t* output_size, char** error_details) {
- if (rp_crypter == nullptr) {
- maybe_copy_error_msg("alts_crypter instance is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- } else if (data == nullptr) {
- maybe_copy_error_msg("data is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- } else if (output_size == nullptr) {
- maybe_copy_error_msg("output_size is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- return GRPC_STATUS_OK;
-}
-
-grpc_status_code increment_counter(alts_record_protocol_crypter* rp_crypter,
- char** error_details) {
- bool is_overflow = false;
- grpc_status_code status =
- alts_counter_increment(rp_crypter->ctr, &is_overflow, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- if (is_overflow) {
- const char error_msg[] =
- "crypter counter is wrapped. The connection"
- "should be closed and the key should be deleted.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INTERNAL;
- }
- return GRPC_STATUS_OK;
-}
-
-size_t alts_record_protocol_crypter_num_overhead_bytes(const alts_crypter* c) {
- if (c != nullptr) {
- size_t num_overhead_bytes = 0;
- char* error_details = nullptr;
- const alts_record_protocol_crypter* rp_crypter =
- reinterpret_cast<const alts_record_protocol_crypter*>(c);
- grpc_status_code status = gsec_aead_crypter_tag_length(
- rp_crypter->crypter, &num_overhead_bytes, &error_details);
- if (status == GRPC_STATUS_OK) {
- return num_overhead_bytes;
- }
- }
- return 0;
-}
-
-void alts_record_protocol_crypter_destruct(alts_crypter* c) {
- if (c != nullptr) {
- alts_record_protocol_crypter* rp_crypter =
- reinterpret_cast<alts_record_protocol_crypter*>(c);
- alts_counter_destroy(rp_crypter->ctr);
- gsec_aead_crypter_destroy(rp_crypter->crypter);
- }
-}
-
-alts_record_protocol_crypter* alts_crypter_create_common(
- gsec_aead_crypter* crypter, bool is_client, size_t overflow_size,
- char** error_details) {
- if (crypter != nullptr) {
- auto* rp_crypter = static_cast<alts_record_protocol_crypter*>(
- gpr_malloc(sizeof(alts_record_protocol_crypter)));
- size_t counter_size = 0;
- grpc_status_code status =
- gsec_aead_crypter_nonce_length(crypter, &counter_size, error_details);
- if (status != GRPC_STATUS_OK) {
- return nullptr;
- }
- /* Create a counter. */
- status = alts_counter_create(is_client, counter_size, overflow_size,
- &rp_crypter->ctr, error_details);
- if (status != GRPC_STATUS_OK) {
- return nullptr;
- }
- rp_crypter->crypter = crypter;
- return rp_crypter;
- }
- const char error_msg[] = "crypter is nullptr.";
- maybe_copy_error_msg(error_msg, error_details);
- return nullptr;
-}
+/*
+ *
+ * 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/frame_protector/alts_record_protocol_crypter_common.h"
+
+#include <grpc/support/alloc.h>
+
+static void maybe_copy_error_msg(const char* src, char** dst) {
+ if (dst != nullptr && src != nullptr) {
+ *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
+ memcpy(*dst, src, strlen(src) + 1);
+ }
+}
+
+grpc_status_code input_sanity_check(
+ const alts_record_protocol_crypter* rp_crypter, const unsigned char* data,
+ size_t* output_size, char** error_details) {
+ if (rp_crypter == nullptr) {
+ maybe_copy_error_msg("alts_crypter instance is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ } else if (data == nullptr) {
+ maybe_copy_error_msg("data is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ } else if (output_size == nullptr) {
+ maybe_copy_error_msg("output_size is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ return GRPC_STATUS_OK;
+}
+
+grpc_status_code increment_counter(alts_record_protocol_crypter* rp_crypter,
+ char** error_details) {
+ bool is_overflow = false;
+ grpc_status_code status =
+ alts_counter_increment(rp_crypter->ctr, &is_overflow, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ if (is_overflow) {
+ const char error_msg[] =
+ "crypter counter is wrapped. The connection"
+ "should be closed and the key should be deleted.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ return GRPC_STATUS_OK;
+}
+
+size_t alts_record_protocol_crypter_num_overhead_bytes(const alts_crypter* c) {
+ if (c != nullptr) {
+ size_t num_overhead_bytes = 0;
+ char* error_details = nullptr;
+ const alts_record_protocol_crypter* rp_crypter =
+ reinterpret_cast<const alts_record_protocol_crypter*>(c);
+ grpc_status_code status = gsec_aead_crypter_tag_length(
+ rp_crypter->crypter, &num_overhead_bytes, &error_details);
+ if (status == GRPC_STATUS_OK) {
+ return num_overhead_bytes;
+ }
+ }
+ return 0;
+}
+
+void alts_record_protocol_crypter_destruct(alts_crypter* c) {
+ if (c != nullptr) {
+ alts_record_protocol_crypter* rp_crypter =
+ reinterpret_cast<alts_record_protocol_crypter*>(c);
+ alts_counter_destroy(rp_crypter->ctr);
+ gsec_aead_crypter_destroy(rp_crypter->crypter);
+ }
+}
+
+alts_record_protocol_crypter* alts_crypter_create_common(
+ gsec_aead_crypter* crypter, bool is_client, size_t overflow_size,
+ char** error_details) {
+ if (crypter != nullptr) {
+ auto* rp_crypter = static_cast<alts_record_protocol_crypter*>(
+ gpr_malloc(sizeof(alts_record_protocol_crypter)));
+ size_t counter_size = 0;
+ grpc_status_code status =
+ gsec_aead_crypter_nonce_length(crypter, &counter_size, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return nullptr;
+ }
+ /* Create a counter. */
+ status = alts_counter_create(is_client, counter_size, overflow_size,
+ &rp_crypter->ctr, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return nullptr;
+ }
+ rp_crypter->crypter = crypter;
+ return rp_crypter;
+ }
+ const char error_msg[] = "crypter is nullptr.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return nullptr;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h
index 682a8f7e7a9..e7b35ee2633 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h
@@ -1,114 +1,114 @@
-/*
- *
- * 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_TSI_ALTS_FRAME_PROTECTOR_ALTS_RECORD_PROTOCOL_CRYPTER_COMMON_H
-#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_RECORD_PROTOCOL_CRYPTER_COMMON_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.h>
-
-#include "src/core/tsi/alts/frame_protector/alts_counter.h"
-#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
-
-/**
- * This file contains common implementation that will be used in both seal and
- * unseal operations.
- */
-
-/**
- * Main struct for alts_record_protocol_crypter that will be used in both
- * seal and unseal operations.
- */
-typedef struct alts_record_protocol_crypter {
- alts_crypter base;
- gsec_aead_crypter* crypter;
- alts_counter* ctr;
-} alts_record_protocol_crypter;
-
-/**
- * This method performs input sanity checks on a subset of inputs to
- * alts_crypter_process_in_place() for both seal and unseal operations.
- *
- * - rp_crypter: an alts_record_protocol_crypter instance.
- * - data: it represents raw data that needs to be sealed in a seal operation or
- * protected data that needs to be unsealed in an unseal operation.
- * - output_size: size of data written to the data buffer after a seal or
- * unseal operation.
- * - error_details: a buffer containing an error message if any of checked
- * inputs is nullptr. It is legal to pass nullptr into error_details and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code input_sanity_check(
- const alts_record_protocol_crypter* rp_crypter, const unsigned char* data,
- size_t* output_size, char** error_details);
-
-/**
- * This method increments the counter within an alts_record_protocol_crypter
- * instance.
- *
- * - rp_crypter: an alts_record_protocol_crypter instance.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly or the counter is wrapped. It is legal to pass nullptr
- * into error_details and otherwise, the parameter should be freed with
- * gpr_free.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise,
- * it returns an error status code along with its details specified in
- * error_details (if error_details is not nullptr).
- */
-grpc_status_code increment_counter(alts_record_protocol_crypter* rp_crypter,
- char** error_details);
-
-/**
- * This method creates an alts_crypter instance, and populates the fields
- * that are common to both seal and unseal operations.
- *
- * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption. The
- * function does not take ownership of crypter.
- * - is_client: a flag indicating if the alts_crypter instance will be
- * used at the client (is_client = true) or server (is_client =
- * false) side.
- * - overflow_size: overflow size of counter in bytes.
- * - error_details: a buffer containing an error message if the method does
- * not function correctly. It is legal to pass nullptr into error_details, and
- * otherwise, the parameter should be freed with gpr_free.
- *
- * On success of creation, the method returns alts_record_protocol_crypter
- * instance. Otherwise, it returns nullptr with its details specified in
- * error_details (if error_details is not nullptr).
- *
- */
-alts_record_protocol_crypter* alts_crypter_create_common(
- gsec_aead_crypter* crypter, bool is_client, size_t overflow_size,
- char** error_details);
-
-/**
- * For the following two methods, please refer to the corresponding API in
- * alts_crypter.h for detailed specifications.
- */
-size_t alts_record_protocol_crypter_num_overhead_bytes(const alts_crypter* c);
-
-void alts_record_protocol_crypter_destruct(alts_crypter* c);
-
-#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_RECORD_PROTOCOL_CRYPTER_COMMON_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_TSI_ALTS_FRAME_PROTECTOR_ALTS_RECORD_PROTOCOL_CRYPTER_COMMON_H
+#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_RECORD_PROTOCOL_CRYPTER_COMMON_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+
+#include "src/core/tsi/alts/frame_protector/alts_counter.h"
+#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
+
+/**
+ * This file contains common implementation that will be used in both seal and
+ * unseal operations.
+ */
+
+/**
+ * Main struct for alts_record_protocol_crypter that will be used in both
+ * seal and unseal operations.
+ */
+typedef struct alts_record_protocol_crypter {
+ alts_crypter base;
+ gsec_aead_crypter* crypter;
+ alts_counter* ctr;
+} alts_record_protocol_crypter;
+
+/**
+ * This method performs input sanity checks on a subset of inputs to
+ * alts_crypter_process_in_place() for both seal and unseal operations.
+ *
+ * - rp_crypter: an alts_record_protocol_crypter instance.
+ * - data: it represents raw data that needs to be sealed in a seal operation or
+ * protected data that needs to be unsealed in an unseal operation.
+ * - output_size: size of data written to the data buffer after a seal or
+ * unseal operation.
+ * - error_details: a buffer containing an error message if any of checked
+ * inputs is nullptr. It is legal to pass nullptr into error_details and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code input_sanity_check(
+ const alts_record_protocol_crypter* rp_crypter, const unsigned char* data,
+ size_t* output_size, char** error_details);
+
+/**
+ * This method increments the counter within an alts_record_protocol_crypter
+ * instance.
+ *
+ * - rp_crypter: an alts_record_protocol_crypter instance.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly or the counter is wrapped. It is legal to pass nullptr
+ * into error_details and otherwise, the parameter should be freed with
+ * gpr_free.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise,
+ * it returns an error status code along with its details specified in
+ * error_details (if error_details is not nullptr).
+ */
+grpc_status_code increment_counter(alts_record_protocol_crypter* rp_crypter,
+ char** error_details);
+
+/**
+ * This method creates an alts_crypter instance, and populates the fields
+ * that are common to both seal and unseal operations.
+ *
+ * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption. The
+ * function does not take ownership of crypter.
+ * - is_client: a flag indicating if the alts_crypter instance will be
+ * used at the client (is_client = true) or server (is_client =
+ * false) side.
+ * - overflow_size: overflow size of counter in bytes.
+ * - error_details: a buffer containing an error message if the method does
+ * not function correctly. It is legal to pass nullptr into error_details, and
+ * otherwise, the parameter should be freed with gpr_free.
+ *
+ * On success of creation, the method returns alts_record_protocol_crypter
+ * instance. Otherwise, it returns nullptr with its details specified in
+ * error_details (if error_details is not nullptr).
+ *
+ */
+alts_record_protocol_crypter* alts_crypter_create_common(
+ gsec_aead_crypter* crypter, bool is_client, size_t overflow_size,
+ char** error_details);
+
+/**
+ * For the following two methods, please refer to the corresponding API in
+ * alts_crypter.h for detailed specifications.
+ */
+size_t alts_record_protocol_crypter_num_overhead_bytes(const alts_crypter* c);
+
+void alts_record_protocol_crypter_destruct(alts_crypter* c);
+
+#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_ALTS_RECORD_PROTOCOL_CRYPTER_COMMON_H \
+ */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc
index f407831613a..d1c36e5797a 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc
@@ -1,105 +1,105 @@
-/*
- *
- * 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/support/alloc.h>
-
-#include "src/core/tsi/alts/frame_protector/alts_counter.h"
-#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
-#include "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h"
-
-static void maybe_copy_error_msg(const char* src, char** dst) {
- if (dst != nullptr && src != nullptr) {
- *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
- memcpy(*dst, src, strlen(src) + 1);
- }
-}
-
-/* Perform input santity check for a seal operation. */
-static grpc_status_code seal_check(alts_crypter* c, const unsigned char* data,
- size_t data_allocated_size, size_t data_size,
- size_t* output_size, char** error_details) {
- /* Do common input sanity check. */
- grpc_status_code status = input_sanity_check(
- reinterpret_cast<const alts_record_protocol_crypter*>(c), data,
- output_size, error_details);
- if (status != GRPC_STATUS_OK) return status;
- /* Do seal-specific check. */
- size_t num_overhead_bytes =
- alts_crypter_num_overhead_bytes(reinterpret_cast<const alts_crypter*>(c));
- if (data_size == 0) {
- const char error_msg[] = "data_size is zero.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (data_size + num_overhead_bytes > data_allocated_size) {
- const char error_msg[] =
- "data_allocated_size is smaller than sum of data_size and "
- "num_overhead_bytes.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code alts_seal_crypter_process_in_place(
- alts_crypter* c, unsigned char* data, size_t data_allocated_size,
- size_t data_size, size_t* output_size, char** error_details) {
- grpc_status_code status = seal_check(c, data, data_allocated_size, data_size,
- output_size, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Do AEAD encryption. */
- alts_record_protocol_crypter* rp_crypter =
- reinterpret_cast<alts_record_protocol_crypter*>(c);
- status = gsec_aead_crypter_encrypt(
- rp_crypter->crypter, alts_counter_get_counter(rp_crypter->ctr),
- alts_counter_get_size(rp_crypter->ctr), nullptr /* aad */,
- 0 /* aad_length */, data, data_size, data, data_allocated_size,
- output_size, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Increment the crypter counter. */
- return increment_counter(rp_crypter, error_details);
-}
-
-static const alts_crypter_vtable vtable = {
- alts_record_protocol_crypter_num_overhead_bytes,
- alts_seal_crypter_process_in_place, alts_record_protocol_crypter_destruct};
-
-grpc_status_code alts_seal_crypter_create(gsec_aead_crypter* gc, bool is_client,
- size_t overflow_size,
- alts_crypter** crypter,
- char** error_details) {
- if (crypter == nullptr) {
- const char error_msg[] = "crypter is nullptr.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- alts_record_protocol_crypter* rp_crypter =
- alts_crypter_create_common(gc, !is_client, overflow_size, error_details);
- if (rp_crypter == nullptr) {
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- rp_crypter->base.vtable = &vtable;
- *crypter = &rp_crypter->base;
- return GRPC_STATUS_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 <grpc/support/alloc.h>
+
+#include "src/core/tsi/alts/frame_protector/alts_counter.h"
+#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
+#include "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h"
+
+static void maybe_copy_error_msg(const char* src, char** dst) {
+ if (dst != nullptr && src != nullptr) {
+ *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
+ memcpy(*dst, src, strlen(src) + 1);
+ }
+}
+
+/* Perform input santity check for a seal operation. */
+static grpc_status_code seal_check(alts_crypter* c, const unsigned char* data,
+ size_t data_allocated_size, size_t data_size,
+ size_t* output_size, char** error_details) {
+ /* Do common input sanity check. */
+ grpc_status_code status = input_sanity_check(
+ reinterpret_cast<const alts_record_protocol_crypter*>(c), data,
+ output_size, error_details);
+ if (status != GRPC_STATUS_OK) return status;
+ /* Do seal-specific check. */
+ size_t num_overhead_bytes =
+ alts_crypter_num_overhead_bytes(reinterpret_cast<const alts_crypter*>(c));
+ if (data_size == 0) {
+ const char error_msg[] = "data_size is zero.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (data_size + num_overhead_bytes > data_allocated_size) {
+ const char error_msg[] =
+ "data_allocated_size is smaller than sum of data_size and "
+ "num_overhead_bytes.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code alts_seal_crypter_process_in_place(
+ alts_crypter* c, unsigned char* data, size_t data_allocated_size,
+ size_t data_size, size_t* output_size, char** error_details) {
+ grpc_status_code status = seal_check(c, data, data_allocated_size, data_size,
+ output_size, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Do AEAD encryption. */
+ alts_record_protocol_crypter* rp_crypter =
+ reinterpret_cast<alts_record_protocol_crypter*>(c);
+ status = gsec_aead_crypter_encrypt(
+ rp_crypter->crypter, alts_counter_get_counter(rp_crypter->ctr),
+ alts_counter_get_size(rp_crypter->ctr), nullptr /* aad */,
+ 0 /* aad_length */, data, data_size, data, data_allocated_size,
+ output_size, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Increment the crypter counter. */
+ return increment_counter(rp_crypter, error_details);
+}
+
+static const alts_crypter_vtable vtable = {
+ alts_record_protocol_crypter_num_overhead_bytes,
+ alts_seal_crypter_process_in_place, alts_record_protocol_crypter_destruct};
+
+grpc_status_code alts_seal_crypter_create(gsec_aead_crypter* gc, bool is_client,
+ size_t overflow_size,
+ alts_crypter** crypter,
+ char** error_details) {
+ if (crypter == nullptr) {
+ const char error_msg[] = "crypter is nullptr.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ alts_record_protocol_crypter* rp_crypter =
+ alts_crypter_create_common(gc, !is_client, overflow_size, error_details);
+ if (rp_crypter == nullptr) {
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ rp_crypter->base.vtable = &vtable;
+ *crypter = &rp_crypter->base;
+ return GRPC_STATUS_OK;
+}
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 a5b70032313..cd2ecc1ddc2 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/support/alloc.h>
-
-#include "src/core/tsi/alts/frame_protector/alts_counter.h"
-#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
-#include "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h"
-
-static void maybe_copy_error_msg(const char* src, char** dst) {
- if (dst != nullptr && src != nullptr) {
- *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
- memcpy(*dst, src, strlen(src) + 1);
- }
-}
-
-/* Perform input santity check. */
-static grpc_status_code unseal_check(alts_crypter* c, const unsigned char* data,
+/*
+ *
+ * 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/support/alloc.h>
+
+#include "src/core/tsi/alts/frame_protector/alts_counter.h"
+#include "src/core/tsi/alts/frame_protector/alts_crypter.h"
+#include "src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.h"
+
+static void maybe_copy_error_msg(const char* src, char** dst) {
+ if (dst != nullptr && src != nullptr) {
+ *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
+ memcpy(*dst, src, strlen(src) + 1);
+ }
+}
+
+/* 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_size, size_t* output_size,
- char** error_details) {
- /* Do common input sanity check. */
- grpc_status_code status = input_sanity_check(
- reinterpret_cast<const alts_record_protocol_crypter*>(c), data,
- output_size, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Do unseal-specific input check. */
- size_t num_overhead_bytes =
- alts_crypter_num_overhead_bytes(reinterpret_cast<const alts_crypter*>(c));
- if (num_overhead_bytes > data_size) {
- const char error_msg[] = "data_size is smaller than num_overhead_bytes.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- return GRPC_STATUS_OK;
-}
-
-static grpc_status_code alts_unseal_crypter_process_in_place(
- alts_crypter* c, unsigned char* data, size_t data_allocated_size,
- size_t data_size, size_t* output_size, char** error_details) {
- grpc_status_code status = unseal_check(c, data, data_allocated_size,
- data_size, output_size, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Do AEAD decryption. */
- alts_record_protocol_crypter* rp_crypter =
- reinterpret_cast<alts_record_protocol_crypter*>(c);
- status = gsec_aead_crypter_decrypt(
- rp_crypter->crypter, alts_counter_get_counter(rp_crypter->ctr),
- alts_counter_get_size(rp_crypter->ctr), nullptr /* aad */,
- 0 /* aad_length */, data, data_size, data, data_allocated_size,
- output_size, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Increment the crypter counter. */
- return increment_counter(rp_crypter, error_details);
-}
-
-static const alts_crypter_vtable vtable = {
- alts_record_protocol_crypter_num_overhead_bytes,
- alts_unseal_crypter_process_in_place,
- alts_record_protocol_crypter_destruct};
-
-grpc_status_code alts_unseal_crypter_create(gsec_aead_crypter* gc,
- bool is_client,
- size_t overflow_size,
- alts_crypter** crypter,
- char** error_details) {
- if (crypter == nullptr) {
- const char error_msg[] = "crypter is nullptr.";
- maybe_copy_error_msg(error_msg, error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- alts_record_protocol_crypter* rp_crypter =
- alts_crypter_create_common(gc, is_client, overflow_size, error_details);
- if (rp_crypter == nullptr) {
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- rp_crypter->base.vtable = &vtable;
- *crypter = &rp_crypter->base;
- return GRPC_STATUS_OK;
-}
+ size_t data_size, size_t* output_size,
+ char** error_details) {
+ /* Do common input sanity check. */
+ grpc_status_code status = input_sanity_check(
+ reinterpret_cast<const alts_record_protocol_crypter*>(c), data,
+ output_size, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Do unseal-specific input check. */
+ size_t num_overhead_bytes =
+ alts_crypter_num_overhead_bytes(reinterpret_cast<const alts_crypter*>(c));
+ if (num_overhead_bytes > data_size) {
+ const char error_msg[] = "data_size is smaller than num_overhead_bytes.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ return GRPC_STATUS_OK;
+}
+
+static grpc_status_code alts_unseal_crypter_process_in_place(
+ alts_crypter* c, unsigned char* data, size_t data_allocated_size,
+ size_t data_size, size_t* output_size, char** error_details) {
+ grpc_status_code status = unseal_check(c, data, data_allocated_size,
+ data_size, output_size, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Do AEAD decryption. */
+ alts_record_protocol_crypter* rp_crypter =
+ reinterpret_cast<alts_record_protocol_crypter*>(c);
+ status = gsec_aead_crypter_decrypt(
+ rp_crypter->crypter, alts_counter_get_counter(rp_crypter->ctr),
+ alts_counter_get_size(rp_crypter->ctr), nullptr /* aad */,
+ 0 /* aad_length */, data, data_size, data, data_allocated_size,
+ output_size, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Increment the crypter counter. */
+ return increment_counter(rp_crypter, error_details);
+}
+
+static const alts_crypter_vtable vtable = {
+ alts_record_protocol_crypter_num_overhead_bytes,
+ alts_unseal_crypter_process_in_place,
+ alts_record_protocol_crypter_destruct};
+
+grpc_status_code alts_unseal_crypter_create(gsec_aead_crypter* gc,
+ bool is_client,
+ size_t overflow_size,
+ alts_crypter** crypter,
+ char** error_details) {
+ if (crypter == nullptr) {
+ const char error_msg[] = "crypter is nullptr.";
+ maybe_copy_error_msg(error_msg, error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ alts_record_protocol_crypter* rp_crypter =
+ alts_crypter_create_common(gc, is_client, overflow_size, error_details);
+ if (rp_crypter == nullptr) {
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ rp_crypter->base.vtable = &vtable;
+ *crypter = &rp_crypter->base;
+ return GRPC_STATUS_OK;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.cc b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.cc
index d3fda63b3dd..5efba25a295 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.cc
@@ -1,218 +1,218 @@
-/*
- *
- * 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/frame_protector/frame_handler.h"
-
-#include <limits.h>
-#include <stdint.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-
-/* Use little endian to interpret a string of bytes as uint32_t. */
-static uint32_t load_32_le(const unsigned char* buffer) {
- return (((uint32_t)buffer[3]) << 24) | (((uint32_t)buffer[2]) << 16) |
- (((uint32_t)buffer[1]) << 8) | ((uint32_t)buffer[0]);
-}
-
-/* Store uint32_t as a string of little endian bytes. */
-static void store_32_le(uint32_t value, unsigned char* buffer) {
- buffer[3] = (unsigned char)(value >> 24) & 0xFF;
- buffer[2] = (unsigned char)(value >> 16) & 0xFF;
- buffer[1] = (unsigned char)(value >> 8) & 0xFF;
- buffer[0] = (unsigned char)(value)&0xFF;
-}
-
-/* Frame writer implementation. */
-alts_frame_writer* alts_create_frame_writer() {
- alts_frame_writer* writer =
- static_cast<alts_frame_writer*>(gpr_zalloc(sizeof(*writer)));
- return writer;
-}
-
-bool alts_reset_frame_writer(alts_frame_writer* writer,
- const unsigned char* buffer, size_t length) {
- if (buffer == nullptr) return false;
- size_t max_input_size = SIZE_MAX - kFrameLengthFieldSize;
- if (length > max_input_size) {
- gpr_log(GPR_ERROR, "length must be at most %zu", max_input_size);
- return false;
- }
- writer->input_buffer = buffer;
- writer->input_size = length;
- writer->input_bytes_written = 0;
- writer->header_bytes_written = 0;
- store_32_le(
- static_cast<uint32_t>(writer->input_size + kFrameMessageTypeFieldSize),
- writer->header_buffer);
- store_32_le(kFrameMessageType, writer->header_buffer + kFrameLengthFieldSize);
- return true;
-}
-
-bool alts_write_frame_bytes(alts_frame_writer* writer, unsigned char* output,
- size_t* bytes_size) {
- if (bytes_size == nullptr || output == nullptr) return false;
- if (alts_is_frame_writer_done(writer)) {
- *bytes_size = 0;
- return true;
- }
- size_t bytes_written = 0;
- /* Write some header bytes, if needed. */
- if (writer->header_bytes_written != sizeof(writer->header_buffer)) {
- size_t bytes_to_write =
- GPR_MIN(*bytes_size,
- sizeof(writer->header_buffer) - writer->header_bytes_written);
- memcpy(output, writer->header_buffer + writer->header_bytes_written,
- bytes_to_write);
- bytes_written += bytes_to_write;
- *bytes_size -= bytes_to_write;
- writer->header_bytes_written += bytes_to_write;
- output += bytes_to_write;
- if (writer->header_bytes_written != sizeof(writer->header_buffer)) {
- *bytes_size = bytes_written;
- return true;
- }
- }
- /* Write some non-header bytes. */
- size_t bytes_to_write =
- GPR_MIN(writer->input_size - writer->input_bytes_written, *bytes_size);
- memcpy(output, writer->input_buffer, bytes_to_write);
- writer->input_buffer += bytes_to_write;
- bytes_written += bytes_to_write;
- writer->input_bytes_written += bytes_to_write;
- *bytes_size = bytes_written;
- return true;
-}
-
-bool alts_is_frame_writer_done(alts_frame_writer* writer) {
- return writer->input_buffer == nullptr ||
- writer->input_size == writer->input_bytes_written;
-}
-
-size_t alts_get_num_writer_bytes_remaining(alts_frame_writer* writer) {
- return (sizeof(writer->header_buffer) - writer->header_bytes_written) +
- (writer->input_size - writer->input_bytes_written);
-}
-
-void alts_destroy_frame_writer(alts_frame_writer* writer) { gpr_free(writer); }
-
-/* Frame reader implementation. */
-alts_frame_reader* alts_create_frame_reader() {
- alts_frame_reader* reader =
- static_cast<alts_frame_reader*>(gpr_zalloc(sizeof(*reader)));
- return reader;
-}
-
-bool alts_is_frame_reader_done(alts_frame_reader* reader) {
- return reader->output_buffer == nullptr ||
- (reader->header_bytes_read == sizeof(reader->header_buffer) &&
- reader->bytes_remaining == 0);
-}
-
-bool alts_has_read_frame_length(alts_frame_reader* reader) {
- return sizeof(reader->header_buffer) == reader->header_bytes_read;
-}
-
-size_t alts_get_reader_bytes_remaining(alts_frame_reader* reader) {
- return alts_has_read_frame_length(reader) ? reader->bytes_remaining : 0;
-}
-
-void alts_reset_reader_output_buffer(alts_frame_reader* reader,
- unsigned char* buffer) {
- reader->output_buffer = buffer;
-}
-
-bool alts_reset_frame_reader(alts_frame_reader* reader, unsigned char* buffer) {
- if (buffer == nullptr) return false;
- reader->output_buffer = buffer;
- reader->bytes_remaining = 0;
- reader->header_bytes_read = 0;
- reader->output_bytes_read = 0;
- return true;
-}
-
-bool alts_read_frame_bytes(alts_frame_reader* reader,
- const unsigned char* bytes, size_t* bytes_size) {
- if (bytes_size == nullptr) return false;
- if (bytes == nullptr) {
- *bytes_size = 0;
- return false;
- }
- if (alts_is_frame_reader_done(reader)) {
- *bytes_size = 0;
- return true;
- }
- size_t bytes_processed = 0;
- /* Process the header, if needed. */
- if (reader->header_bytes_read != sizeof(reader->header_buffer)) {
- size_t bytes_to_write = GPR_MIN(
- *bytes_size, sizeof(reader->header_buffer) - reader->header_bytes_read);
- memcpy(reader->header_buffer + reader->header_bytes_read, bytes,
- bytes_to_write);
- reader->header_bytes_read += bytes_to_write;
- bytes_processed += bytes_to_write;
- bytes += bytes_to_write;
- *bytes_size -= bytes_to_write;
- if (reader->header_bytes_read != sizeof(reader->header_buffer)) {
- *bytes_size = bytes_processed;
- return true;
- }
- size_t frame_length = load_32_le(reader->header_buffer);
- if (frame_length < kFrameMessageTypeFieldSize ||
- frame_length > kFrameMaxSize) {
- gpr_log(GPR_ERROR,
- "Bad frame length (should be at least %zu, and at most %zu)",
- kFrameMessageTypeFieldSize, kFrameMaxSize);
- *bytes_size = 0;
- return false;
- }
- size_t message_type =
- load_32_le(reader->header_buffer + kFrameLengthFieldSize);
- if (message_type != kFrameMessageType) {
- gpr_log(GPR_ERROR, "Unsupported message type %zu (should be %zu)",
- message_type, kFrameMessageType);
- *bytes_size = 0;
- return false;
- }
- reader->bytes_remaining = frame_length - kFrameMessageTypeFieldSize;
- }
- /* Process the non-header bytes. */
- size_t bytes_to_write = GPR_MIN(*bytes_size, reader->bytes_remaining);
- memcpy(reader->output_buffer, bytes, bytes_to_write);
- reader->output_buffer += bytes_to_write;
- bytes_processed += bytes_to_write;
- reader->bytes_remaining -= bytes_to_write;
- reader->output_bytes_read += bytes_to_write;
- *bytes_size = bytes_processed;
- return true;
-}
-
-size_t alts_get_output_bytes_read(alts_frame_reader* reader) {
- return reader->output_bytes_read;
-}
-
-unsigned char* alts_get_output_buffer(alts_frame_reader* reader) {
- return reader->output_buffer;
-}
-
-void alts_destroy_frame_reader(alts_frame_reader* reader) { gpr_free(reader); }
+/*
+ *
+ * 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/frame_protector/frame_handler.h"
+
+#include <limits.h>
+#include <stdint.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+
+/* Use little endian to interpret a string of bytes as uint32_t. */
+static uint32_t load_32_le(const unsigned char* buffer) {
+ return (((uint32_t)buffer[3]) << 24) | (((uint32_t)buffer[2]) << 16) |
+ (((uint32_t)buffer[1]) << 8) | ((uint32_t)buffer[0]);
+}
+
+/* Store uint32_t as a string of little endian bytes. */
+static void store_32_le(uint32_t value, unsigned char* buffer) {
+ buffer[3] = (unsigned char)(value >> 24) & 0xFF;
+ buffer[2] = (unsigned char)(value >> 16) & 0xFF;
+ buffer[1] = (unsigned char)(value >> 8) & 0xFF;
+ buffer[0] = (unsigned char)(value)&0xFF;
+}
+
+/* Frame writer implementation. */
+alts_frame_writer* alts_create_frame_writer() {
+ alts_frame_writer* writer =
+ static_cast<alts_frame_writer*>(gpr_zalloc(sizeof(*writer)));
+ return writer;
+}
+
+bool alts_reset_frame_writer(alts_frame_writer* writer,
+ const unsigned char* buffer, size_t length) {
+ if (buffer == nullptr) return false;
+ size_t max_input_size = SIZE_MAX - kFrameLengthFieldSize;
+ if (length > max_input_size) {
+ gpr_log(GPR_ERROR, "length must be at most %zu", max_input_size);
+ return false;
+ }
+ writer->input_buffer = buffer;
+ writer->input_size = length;
+ writer->input_bytes_written = 0;
+ writer->header_bytes_written = 0;
+ store_32_le(
+ static_cast<uint32_t>(writer->input_size + kFrameMessageTypeFieldSize),
+ writer->header_buffer);
+ store_32_le(kFrameMessageType, writer->header_buffer + kFrameLengthFieldSize);
+ return true;
+}
+
+bool alts_write_frame_bytes(alts_frame_writer* writer, unsigned char* output,
+ size_t* bytes_size) {
+ if (bytes_size == nullptr || output == nullptr) return false;
+ if (alts_is_frame_writer_done(writer)) {
+ *bytes_size = 0;
+ return true;
+ }
+ size_t bytes_written = 0;
+ /* Write some header bytes, if needed. */
+ if (writer->header_bytes_written != sizeof(writer->header_buffer)) {
+ size_t bytes_to_write =
+ GPR_MIN(*bytes_size,
+ sizeof(writer->header_buffer) - writer->header_bytes_written);
+ memcpy(output, writer->header_buffer + writer->header_bytes_written,
+ bytes_to_write);
+ bytes_written += bytes_to_write;
+ *bytes_size -= bytes_to_write;
+ writer->header_bytes_written += bytes_to_write;
+ output += bytes_to_write;
+ if (writer->header_bytes_written != sizeof(writer->header_buffer)) {
+ *bytes_size = bytes_written;
+ return true;
+ }
+ }
+ /* Write some non-header bytes. */
+ size_t bytes_to_write =
+ GPR_MIN(writer->input_size - writer->input_bytes_written, *bytes_size);
+ memcpy(output, writer->input_buffer, bytes_to_write);
+ writer->input_buffer += bytes_to_write;
+ bytes_written += bytes_to_write;
+ writer->input_bytes_written += bytes_to_write;
+ *bytes_size = bytes_written;
+ return true;
+}
+
+bool alts_is_frame_writer_done(alts_frame_writer* writer) {
+ return writer->input_buffer == nullptr ||
+ writer->input_size == writer->input_bytes_written;
+}
+
+size_t alts_get_num_writer_bytes_remaining(alts_frame_writer* writer) {
+ return (sizeof(writer->header_buffer) - writer->header_bytes_written) +
+ (writer->input_size - writer->input_bytes_written);
+}
+
+void alts_destroy_frame_writer(alts_frame_writer* writer) { gpr_free(writer); }
+
+/* Frame reader implementation. */
+alts_frame_reader* alts_create_frame_reader() {
+ alts_frame_reader* reader =
+ static_cast<alts_frame_reader*>(gpr_zalloc(sizeof(*reader)));
+ return reader;
+}
+
+bool alts_is_frame_reader_done(alts_frame_reader* reader) {
+ return reader->output_buffer == nullptr ||
+ (reader->header_bytes_read == sizeof(reader->header_buffer) &&
+ reader->bytes_remaining == 0);
+}
+
+bool alts_has_read_frame_length(alts_frame_reader* reader) {
+ return sizeof(reader->header_buffer) == reader->header_bytes_read;
+}
+
+size_t alts_get_reader_bytes_remaining(alts_frame_reader* reader) {
+ return alts_has_read_frame_length(reader) ? reader->bytes_remaining : 0;
+}
+
+void alts_reset_reader_output_buffer(alts_frame_reader* reader,
+ unsigned char* buffer) {
+ reader->output_buffer = buffer;
+}
+
+bool alts_reset_frame_reader(alts_frame_reader* reader, unsigned char* buffer) {
+ if (buffer == nullptr) return false;
+ reader->output_buffer = buffer;
+ reader->bytes_remaining = 0;
+ reader->header_bytes_read = 0;
+ reader->output_bytes_read = 0;
+ return true;
+}
+
+bool alts_read_frame_bytes(alts_frame_reader* reader,
+ const unsigned char* bytes, size_t* bytes_size) {
+ if (bytes_size == nullptr) return false;
+ if (bytes == nullptr) {
+ *bytes_size = 0;
+ return false;
+ }
+ if (alts_is_frame_reader_done(reader)) {
+ *bytes_size = 0;
+ return true;
+ }
+ size_t bytes_processed = 0;
+ /* Process the header, if needed. */
+ if (reader->header_bytes_read != sizeof(reader->header_buffer)) {
+ size_t bytes_to_write = GPR_MIN(
+ *bytes_size, sizeof(reader->header_buffer) - reader->header_bytes_read);
+ memcpy(reader->header_buffer + reader->header_bytes_read, bytes,
+ bytes_to_write);
+ reader->header_bytes_read += bytes_to_write;
+ bytes_processed += bytes_to_write;
+ bytes += bytes_to_write;
+ *bytes_size -= bytes_to_write;
+ if (reader->header_bytes_read != sizeof(reader->header_buffer)) {
+ *bytes_size = bytes_processed;
+ return true;
+ }
+ size_t frame_length = load_32_le(reader->header_buffer);
+ if (frame_length < kFrameMessageTypeFieldSize ||
+ frame_length > kFrameMaxSize) {
+ gpr_log(GPR_ERROR,
+ "Bad frame length (should be at least %zu, and at most %zu)",
+ kFrameMessageTypeFieldSize, kFrameMaxSize);
+ *bytes_size = 0;
+ return false;
+ }
+ size_t message_type =
+ load_32_le(reader->header_buffer + kFrameLengthFieldSize);
+ if (message_type != kFrameMessageType) {
+ gpr_log(GPR_ERROR, "Unsupported message type %zu (should be %zu)",
+ message_type, kFrameMessageType);
+ *bytes_size = 0;
+ return false;
+ }
+ reader->bytes_remaining = frame_length - kFrameMessageTypeFieldSize;
+ }
+ /* Process the non-header bytes. */
+ size_t bytes_to_write = GPR_MIN(*bytes_size, reader->bytes_remaining);
+ memcpy(reader->output_buffer, bytes, bytes_to_write);
+ reader->output_buffer += bytes_to_write;
+ bytes_processed += bytes_to_write;
+ reader->bytes_remaining -= bytes_to_write;
+ reader->output_bytes_read += bytes_to_write;
+ *bytes_size = bytes_processed;
+ return true;
+}
+
+size_t alts_get_output_bytes_read(alts_frame_reader* reader) {
+ return reader->output_bytes_read;
+}
+
+unsigned char* alts_get_output_buffer(alts_frame_reader* reader) {
+ return reader->output_buffer;
+}
+
+void alts_destroy_frame_reader(alts_frame_reader* reader) { gpr_free(reader); }
diff --git a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.h b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.h
index a703ff40d30..729174322a7 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/frame_protector/frame_handler.h
@@ -1,236 +1,236 @@
-/*
- *
- * 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_TSI_ALTS_FRAME_PROTECTOR_FRAME_HANDLER_H
-#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_FRAME_HANDLER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-#include <stdlib.h>
-
-const size_t kFrameMessageType = 0x06;
-const size_t kFrameLengthFieldSize = 4;
-const size_t kFrameMessageTypeFieldSize = 4;
-const size_t kFrameMaxSize = 1024 * 1024;
-const size_t kFrameHeaderSize =
- kFrameLengthFieldSize + kFrameMessageTypeFieldSize;
-
-/**
- * Implementation of frame reader and frame writer. All APIs in the
- * header are thread-compatible.
- */
-
-/**
- * Main struct for a frame writer. It reads frames from an input buffer, and
- * writes the contents as raw bytes. It does not own the input buffer.
- */
-typedef struct alts_frame_writer {
- const unsigned char* input_buffer;
- unsigned char header_buffer[kFrameHeaderSize];
- size_t input_bytes_written;
- size_t header_bytes_written;
- size_t input_size;
-} alts_frame_writer;
-
-/**
- * Main struct for a frame reader. It reads raw bytes and puts the framed
- * result into an output buffer. It does not own the output buffer.
- */
-typedef struct alts_frame_reader {
- unsigned char* output_buffer;
- unsigned char header_buffer[kFrameHeaderSize];
- size_t header_bytes_read;
- size_t output_bytes_read;
- size_t bytes_remaining;
-} alts_frame_reader;
-
-/**
- * This method creates a frame writer instance and initializes its internal
- * states.
- */
-alts_frame_writer* alts_create_frame_writer();
-
-/**
- * This method resets internal states of a frame writer and prepares to write
- * a single frame. It does not take ownership of payload_buffer.
- * The payload_buffer must outlive the writer.
- *
- * - writer: a frame writer instance.
- * - buffer: a buffer storing full payload data to be framed.
- * - length: size of payload data.
- *
- * The method returns true on success and false otherwise.
- */
-bool alts_reset_frame_writer(alts_frame_writer* writer,
- const unsigned char* buffer, size_t length);
-
-/**
- * This method writes up to bytes_size bytes of a frame to output.
- *
- * - writer: a frame writer instance.
- * - output: an output buffer used to store the frame.
- * - bytes_size: an in/out parameter that stores the size of output buffer
- * before the call, and gets written the number of frame bytes written to the
- * buffer.
- *
- * The method returns true on success and false otherwise.
- */
-bool alts_write_frame_bytes(alts_frame_writer* writer, unsigned char* output,
- size_t* bytes_size);
-
-/**
- * This method checks if a reset can be called to write a new frame. It returns
- * true if it's the first time to frame a payload, or the current frame has
- * been finished processing. It returns false if it's not ready yet to start a
- * new frame (e.g., more payload data needs to be accumulated to process the
- * current frame).
- *
- * if (alts_is_frame_writer_done(writer)) {
- * // a new frame can be written, call reset.
- * alts_reset_frame_writer(writer, payload_buffer, payload_size);
- * } else {
- * // accumulate more payload data until a full frame can be written.
- * }
- *
- * - writer: a frame writer instance.
- */
-bool alts_is_frame_writer_done(alts_frame_writer* writer);
-
-/**
- * This method returns the number of bytes left to write before a complete frame
- * is formed.
- *
- * - writer: a frame writer instance.
- */
-size_t alts_get_num_writer_bytes_remaining(alts_frame_writer* writer);
-
-/**
- * This method destroys a frame writer instance.
- *
- * - writer: a frame writer instance.
- */
-void alts_destroy_frame_writer(alts_frame_writer* writer);
-
-/**
- * This method creates a frame reader instance and initializes its internal
- * states.
- */
-alts_frame_reader* alts_create_frame_reader();
-
-/**
- * This method resets internal states of a frame reader (including setting its
- * output_buffer with buffer), and prepares to write processed bytes to
- * an output_buffer. It does not take ownership of buffer. The buffer must
- * outlive reader.
- *
- * - reader: a frame reader instance.
- * - buffer: an output buffer used to store deframed results.
- *
- * The method returns true on success and false otherwise.
- */
-bool alts_reset_frame_reader(alts_frame_reader* reader, unsigned char* buffer);
-
-/**
- * This method processes up to the number of bytes given in bytes_size. It may
- * choose not to process all the bytes, if, for instance, more bytes are
- * given to the method than required to complete the current frame.
- *
- * - reader: a frame reader instance.
- * - bytes: a buffer that stores data to be processed.
- * - bytes_size: an in/out parameter that stores the size of bytes before the
- * call and gets written the number of bytes processed.
- *
- * The method returns true on success and false otherwise.
- */
-bool alts_read_frame_bytes(alts_frame_reader* reader,
- const unsigned char* bytes, size_t* bytes_size);
-
-/**
- * This method checks if a frame length has been read.
- *
- * - reader: a frame reader instance.
- *
- * The method returns true if a frame length has been read and false otherwise.
- */
-bool alts_has_read_frame_length(alts_frame_reader* reader);
-
-/**
- * This method returns the number of bytes the frame reader intends to write.
- * It may only be called if alts_has_read_frame_length() returns true.
- *
- * - reader: a frame reader instance.
- */
-size_t alts_get_reader_bytes_remaining(alts_frame_reader* reader);
-
-/**
- * This method resets output_buffer but does not otherwise modify other internal
- * states of a frame reader instance. After being set, the new output_buffer
- * will hold the deframed payload held by the original output_buffer. It does
- * not take ownership of buffer. The buffer must outlive the reader.
- * To distinguish between two reset methods on a frame reader,
- *
- * if (alts_fh_is_frame_reader_done(reader)) {
- * // if buffer contains a full payload to be deframed, call reset.
- * alts_reset_frame_reader(reader, buffer);
- * }
- *
- * // if remaining buffer space is not enough to hold a full payload
- * if (buffer_space_remaining < alts_get_reader_bytes_remaining(reader)) {
- * // allocate enough space for a new buffer, copy back data processed so far,
- * // and call reset.
- * alts_reset_reader_output_buffer(reader, new_buffer).
- * }
- *
- * - reader: a frame reader instance.
- * - buffer: a buffer used to set reader's output_buffer.
- */
-void alts_reset_reader_output_buffer(alts_frame_reader* reader,
- unsigned char* buffer);
-
-/**
- * This method checks if reset can be called to start processing a new frame.
- * If true and reset was previously called, a full frame has been processed and
- * the content of the frame is available in output_buffer.
-
- * - reader: a frame reader instance.
- */
-bool alts_is_frame_reader_done(alts_frame_reader* reader);
-
-/**
- * This method returns output_bytes_read of a frame reader instance.
- *
- * - reader: a frame reader instance.
- */
-size_t alts_get_output_bytes_read(alts_frame_reader* reader);
-
-/**
- * This method returns output_buffer of a frame reader instance.
- *
- * - reader: a frame reader instance.
- */
-unsigned char* alts_get_output_buffer(alts_frame_reader* reader);
-
-/**
- * This method destroys a frame reader instance.
- *
- * - reader: a frame reader instance.
- */
-void alts_destroy_frame_reader(alts_frame_reader* reader);
-
-#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_FRAME_HANDLER_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_TSI_ALTS_FRAME_PROTECTOR_FRAME_HANDLER_H
+#define GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_FRAME_HANDLER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+#include <stdlib.h>
+
+const size_t kFrameMessageType = 0x06;
+const size_t kFrameLengthFieldSize = 4;
+const size_t kFrameMessageTypeFieldSize = 4;
+const size_t kFrameMaxSize = 1024 * 1024;
+const size_t kFrameHeaderSize =
+ kFrameLengthFieldSize + kFrameMessageTypeFieldSize;
+
+/**
+ * Implementation of frame reader and frame writer. All APIs in the
+ * header are thread-compatible.
+ */
+
+/**
+ * Main struct for a frame writer. It reads frames from an input buffer, and
+ * writes the contents as raw bytes. It does not own the input buffer.
+ */
+typedef struct alts_frame_writer {
+ const unsigned char* input_buffer;
+ unsigned char header_buffer[kFrameHeaderSize];
+ size_t input_bytes_written;
+ size_t header_bytes_written;
+ size_t input_size;
+} alts_frame_writer;
+
+/**
+ * Main struct for a frame reader. It reads raw bytes and puts the framed
+ * result into an output buffer. It does not own the output buffer.
+ */
+typedef struct alts_frame_reader {
+ unsigned char* output_buffer;
+ unsigned char header_buffer[kFrameHeaderSize];
+ size_t header_bytes_read;
+ size_t output_bytes_read;
+ size_t bytes_remaining;
+} alts_frame_reader;
+
+/**
+ * This method creates a frame writer instance and initializes its internal
+ * states.
+ */
+alts_frame_writer* alts_create_frame_writer();
+
+/**
+ * This method resets internal states of a frame writer and prepares to write
+ * a single frame. It does not take ownership of payload_buffer.
+ * The payload_buffer must outlive the writer.
+ *
+ * - writer: a frame writer instance.
+ * - buffer: a buffer storing full payload data to be framed.
+ * - length: size of payload data.
+ *
+ * The method returns true on success and false otherwise.
+ */
+bool alts_reset_frame_writer(alts_frame_writer* writer,
+ const unsigned char* buffer, size_t length);
+
+/**
+ * This method writes up to bytes_size bytes of a frame to output.
+ *
+ * - writer: a frame writer instance.
+ * - output: an output buffer used to store the frame.
+ * - bytes_size: an in/out parameter that stores the size of output buffer
+ * before the call, and gets written the number of frame bytes written to the
+ * buffer.
+ *
+ * The method returns true on success and false otherwise.
+ */
+bool alts_write_frame_bytes(alts_frame_writer* writer, unsigned char* output,
+ size_t* bytes_size);
+
+/**
+ * This method checks if a reset can be called to write a new frame. It returns
+ * true if it's the first time to frame a payload, or the current frame has
+ * been finished processing. It returns false if it's not ready yet to start a
+ * new frame (e.g., more payload data needs to be accumulated to process the
+ * current frame).
+ *
+ * if (alts_is_frame_writer_done(writer)) {
+ * // a new frame can be written, call reset.
+ * alts_reset_frame_writer(writer, payload_buffer, payload_size);
+ * } else {
+ * // accumulate more payload data until a full frame can be written.
+ * }
+ *
+ * - writer: a frame writer instance.
+ */
+bool alts_is_frame_writer_done(alts_frame_writer* writer);
+
+/**
+ * This method returns the number of bytes left to write before a complete frame
+ * is formed.
+ *
+ * - writer: a frame writer instance.
+ */
+size_t alts_get_num_writer_bytes_remaining(alts_frame_writer* writer);
+
+/**
+ * This method destroys a frame writer instance.
+ *
+ * - writer: a frame writer instance.
+ */
+void alts_destroy_frame_writer(alts_frame_writer* writer);
+
+/**
+ * This method creates a frame reader instance and initializes its internal
+ * states.
+ */
+alts_frame_reader* alts_create_frame_reader();
+
+/**
+ * This method resets internal states of a frame reader (including setting its
+ * output_buffer with buffer), and prepares to write processed bytes to
+ * an output_buffer. It does not take ownership of buffer. The buffer must
+ * outlive reader.
+ *
+ * - reader: a frame reader instance.
+ * - buffer: an output buffer used to store deframed results.
+ *
+ * The method returns true on success and false otherwise.
+ */
+bool alts_reset_frame_reader(alts_frame_reader* reader, unsigned char* buffer);
+
+/**
+ * This method processes up to the number of bytes given in bytes_size. It may
+ * choose not to process all the bytes, if, for instance, more bytes are
+ * given to the method than required to complete the current frame.
+ *
+ * - reader: a frame reader instance.
+ * - bytes: a buffer that stores data to be processed.
+ * - bytes_size: an in/out parameter that stores the size of bytes before the
+ * call and gets written the number of bytes processed.
+ *
+ * The method returns true on success and false otherwise.
+ */
+bool alts_read_frame_bytes(alts_frame_reader* reader,
+ const unsigned char* bytes, size_t* bytes_size);
+
+/**
+ * This method checks if a frame length has been read.
+ *
+ * - reader: a frame reader instance.
+ *
+ * The method returns true if a frame length has been read and false otherwise.
+ */
+bool alts_has_read_frame_length(alts_frame_reader* reader);
+
+/**
+ * This method returns the number of bytes the frame reader intends to write.
+ * It may only be called if alts_has_read_frame_length() returns true.
+ *
+ * - reader: a frame reader instance.
+ */
+size_t alts_get_reader_bytes_remaining(alts_frame_reader* reader);
+
+/**
+ * This method resets output_buffer but does not otherwise modify other internal
+ * states of a frame reader instance. After being set, the new output_buffer
+ * will hold the deframed payload held by the original output_buffer. It does
+ * not take ownership of buffer. The buffer must outlive the reader.
+ * To distinguish between two reset methods on a frame reader,
+ *
+ * if (alts_fh_is_frame_reader_done(reader)) {
+ * // if buffer contains a full payload to be deframed, call reset.
+ * alts_reset_frame_reader(reader, buffer);
+ * }
+ *
+ * // if remaining buffer space is not enough to hold a full payload
+ * if (buffer_space_remaining < alts_get_reader_bytes_remaining(reader)) {
+ * // allocate enough space for a new buffer, copy back data processed so far,
+ * // and call reset.
+ * alts_reset_reader_output_buffer(reader, new_buffer).
+ * }
+ *
+ * - reader: a frame reader instance.
+ * - buffer: a buffer used to set reader's output_buffer.
+ */
+void alts_reset_reader_output_buffer(alts_frame_reader* reader,
+ unsigned char* buffer);
+
+/**
+ * This method checks if reset can be called to start processing a new frame.
+ * If true and reset was previously called, a full frame has been processed and
+ * the content of the frame is available in output_buffer.
+
+ * - reader: a frame reader instance.
+ */
+bool alts_is_frame_reader_done(alts_frame_reader* reader);
+
+/**
+ * This method returns output_bytes_read of a frame reader instance.
+ *
+ * - reader: a frame reader instance.
+ */
+size_t alts_get_output_bytes_read(alts_frame_reader* reader);
+
+/**
+ * This method returns output_buffer of a frame reader instance.
+ *
+ * - reader: a frame reader instance.
+ */
+unsigned char* alts_get_output_buffer(alts_frame_reader* reader);
+
+/**
+ * This method destroys a frame reader instance.
+ *
+ * - reader: a frame reader instance.
+ */
+void alts_destroy_frame_reader(alts_frame_reader* reader);
+
+#endif /* GRPC_CORE_TSI_ALTS_FRAME_PROTECTOR_FRAME_HANDLER_H */
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 e2f04f7310d..320bdee221f 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
@@ -1,33 +1,33 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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 <list>
-#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
-
+#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
+
#include "upb/upb.hpp"
-#include <grpc/byte_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
+#include <grpc/byte_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/call.h"
@@ -35,11 +35,11 @@
#include "src/core/tsi/alts/handshaker/alts_shared_resource.h"
#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h"
#include "src/core/tsi/alts/handshaker/alts_tsi_utils.h"
-
+
#define TSI_ALTS_INITIAL_BUFFER_SIZE 256
-const int kHandshakerClientOpNum = 4;
-
+const int kHandshakerClientOpNum = 4;
+
struct alts_handshaker_client {
const alts_handshaker_client_vtable* vtable;
};
@@ -51,19 +51,19 @@ struct recv_message_result {
tsi_handshaker_result* result;
};
-typedef struct alts_grpc_handshaker_client {
- alts_handshaker_client base;
+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;
alts_tsi_handshaker* handshaker;
- grpc_call* call;
+ grpc_call* call;
/* A pointer to a function handling the interaction with handshaker service.
* That is, it points to grpc_call_start_batch_and_execute when the handshaker
* client is used in a non-testing use case and points to a custom function
* that validates the data to be sent to handshaker service in a testing use
* case. */
- alts_grpc_caller grpc_caller;
+ 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. */
grpc_closure on_handshaker_service_resp_recv;
@@ -106,15 +106,15 @@ typedef struct alts_grpc_handshaker_client {
recv_message_result* pending_recv_message_result;
/* Maximum frame size used by frame protector. */
size_t max_frame_size;
-} alts_grpc_handshaker_client;
-
+} alts_grpc_handshaker_client;
+
static void handshaker_client_send_buffer_destroy(
alts_grpc_handshaker_client* client) {
GPR_ASSERT(client != nullptr);
grpc_byte_buffer_destroy(client->send_buffer);
client->send_buffer = nullptr;
-}
-
+}
+
static bool is_handshake_finished_properly(grpc_gcp_HandshakerResp* resp) {
GPR_ASSERT(resp != nullptr);
if (grpc_gcp_HandshakerResp_result(resp)) {
@@ -296,10 +296,10 @@ void alts_handshaker_client_handle_response(alts_handshaker_client* c,
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) {
+ 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;
@@ -317,34 +317,34 @@ static tsi_result continue_make_grpc_call(alts_grpc_handshaker_client* client,
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++;
- GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
- op->op = GRPC_OP_RECV_INITIAL_METADATA;
- op->data.recv_initial_metadata.recv_initial_metadata =
+ op->op = GRPC_OP_SEND_INITIAL_METADATA;
+ op->data.send_initial_metadata.count = 0;
+ op++;
+ GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
+ op->op = GRPC_OP_RECV_INITIAL_METADATA;
+ op->data.recv_initial_metadata.recv_initial_metadata =
&client->recv_initial_metadata;
- op++;
- GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
- }
- op->op = GRPC_OP_SEND_MESSAGE;
+ op++;
+ GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
+ }
+ op->op = GRPC_OP_SEND_MESSAGE;
op->data.send_message.send_message = client->send_buffer;
- op++;
- GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
- op->op = GRPC_OP_RECV_MESSAGE;
+ op++;
+ GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
+ op->op = GRPC_OP_RECV_MESSAGE;
op->data.recv_message.recv_message = &client->recv_buffer;
- op++;
- GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
+ op++;
+ GPR_ASSERT(op - ops <= kHandshakerClientOpNum);
GPR_ASSERT(client->grpc_caller != nullptr);
if (client->grpc_caller(client->call, ops, static_cast<size_t>(op - ops),
&client->on_handshaker_service_resp_recv) !=
GRPC_CALL_OK) {
- gpr_log(GPR_ERROR, "Start batch operation failed");
- return TSI_INTERNAL_ERROR;
- }
- return TSI_OK;
-}
-
+ gpr_log(GPR_ERROR, "Start batch operation failed");
+ return TSI_INTERNAL_ERROR;
+ }
+ 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.
@@ -479,7 +479,7 @@ static grpc_byte_buffer* get_serialized_handshaker_req(
return byte_buffer;
}
-/* Create and populate a client_start handshaker request, then serialize it. */
+/* 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);
@@ -505,48 +505,48 @@ static grpc_byte_buffer* get_serialized_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 =
+ target_service_account* ptr =
(reinterpret_cast<grpc_alts_credentials_client_options*>(client->options))
- ->target_account_list_head;
- while (ptr != nullptr) {
+ ->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));
- ptr = ptr->next;
- }
+ 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());
-}
-
+}
+
static tsi_result handshaker_client_start_client(alts_handshaker_client* c) {
if (c == nullptr) {
gpr_log(GPR_ERROR, "client is nullptr in handshaker_client_start_client()");
- return TSI_INVALID_ARGUMENT;
- }
+ return TSI_INVALID_ARGUMENT;
+ }
grpc_byte_buffer* buffer = get_serialized_start_client(c);
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
- if (buffer == nullptr) {
- gpr_log(GPR_ERROR, "get_serialized_start_client() failed");
- return TSI_INTERNAL_ERROR;
- }
+ if (buffer == nullptr) {
+ gpr_log(GPR_ERROR, "get_serialized_start_client() failed");
+ return TSI_INTERNAL_ERROR;
+ }
handshaker_client_send_buffer_destroy(client);
client->send_buffer = buffer;
tsi_result result = make_grpc_call(&client->base, true /* is_start */);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "make_grpc_call() failed");
- }
- return result;
-}
-
-/* Create and populate a start_server handshaker request, then serialize it. */
-static grpc_byte_buffer* get_serialized_start_server(
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "make_grpc_call() failed");
+ }
+ return result;
+}
+
+/* Create and populate a start_server handshaker request, then serialize it. */
+static grpc_byte_buffer* get_serialized_start_server(
alts_handshaker_client* c, grpc_slice* bytes_received) {
GPR_ASSERT(c != nullptr);
- GPR_ASSERT(bytes_received != nullptr);
+ GPR_ASSERT(bytes_received != nullptr);
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
@@ -575,33 +575,33 @@ static grpc_byte_buffer* get_serialized_start_server(
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());
-}
-
+}
+
static tsi_result handshaker_client_start_server(alts_handshaker_client* c,
- grpc_slice* bytes_received) {
+ grpc_slice* bytes_received) {
if (c == nullptr || bytes_received == nullptr) {
gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_start_server()");
- return TSI_INVALID_ARGUMENT;
- }
+ return TSI_INVALID_ARGUMENT;
+ }
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
grpc_byte_buffer* buffer = get_serialized_start_server(c, bytes_received);
- if (buffer == nullptr) {
- gpr_log(GPR_ERROR, "get_serialized_start_server() failed");
- return TSI_INTERNAL_ERROR;
- }
+ if (buffer == nullptr) {
+ gpr_log(GPR_ERROR, "get_serialized_start_server() failed");
+ return TSI_INTERNAL_ERROR;
+ }
handshaker_client_send_buffer_destroy(client);
client->send_buffer = buffer;
tsi_result result = make_grpc_call(&client->base, true /* is_start */);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "make_grpc_call() failed");
- }
- return result;
-}
-
-/* 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);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "make_grpc_call() failed");
+ }
+ return result;
+}
+
+/* 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 =
@@ -611,32 +611,32 @@ static grpc_byte_buffer* get_serialized_next(grpc_slice* bytes_received) {
*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,
- grpc_slice* bytes_received) {
+ grpc_slice* bytes_received) {
if (c == nullptr || bytes_received == nullptr) {
gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_next()");
- return TSI_INVALID_ARGUMENT;
- }
+ return TSI_INVALID_ARGUMENT;
+ }
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);
- grpc_byte_buffer* buffer = get_serialized_next(bytes_received);
- if (buffer == nullptr) {
- gpr_log(GPR_ERROR, "get_serialized_next() failed");
- return TSI_INTERNAL_ERROR;
- }
+ grpc_byte_buffer* buffer = get_serialized_next(bytes_received);
+ if (buffer == nullptr) {
+ gpr_log(GPR_ERROR, "get_serialized_next() failed");
+ return TSI_INTERNAL_ERROR;
+ }
handshaker_client_send_buffer_destroy(client);
client->send_buffer = buffer;
tsi_result result = make_grpc_call(&client->base, false /* is_start */);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "make_grpc_call() failed");
- }
- return result;
-}
-
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "make_grpc_call() failed");
+ }
+ return result;
+}
+
static void handshaker_client_shutdown(alts_handshaker_client* c) {
GPR_ASSERT(c != nullptr);
alts_grpc_handshaker_client* client =
@@ -653,8 +653,8 @@ static void handshaker_call_unref(void* arg, grpc_error* /* error */) {
static void handshaker_client_destruct(alts_handshaker_client* c) {
if (c == nullptr) {
- return;
- }
+ return;
+ }
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
if (client->call != nullptr) {
@@ -677,14 +677,14 @@ static void handshaker_client_destruct(alts_handshaker_client* c) {
GRPC_ERROR_NONE);
}
}
-}
-
-static const alts_handshaker_client_vtable vtable = {
- handshaker_client_start_client, handshaker_client_start_server,
+}
+
+static const alts_handshaker_client_vtable vtable = {
+ handshaker_client_start_client, handshaker_client_start_server,
handshaker_client_next, handshaker_client_shutdown,
handshaker_client_destruct};
-
-alts_handshaker_client* alts_grpc_handshaker_client_create(
+
+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,
@@ -692,11 +692,11 @@ alts_handshaker_client* alts_grpc_handshaker_client_create(
void* user_data, alts_handshaker_client_vtable* vtable_for_testing,
bool is_client, size_t max_frame_size) {
if (channel == nullptr || handshaker_service_url == nullptr) {
- gpr_log(GPR_ERROR, "Invalid arguments to alts_handshaker_client_create()");
- return nullptr;
- }
- alts_grpc_handshaker_client* client =
- static_cast<alts_grpc_handshaker_client*>(gpr_zalloc(sizeof(*client)));
+ gpr_log(GPR_ERROR, "Invalid arguments to alts_handshaker_client_create()");
+ return nullptr;
+ }
+ 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);
client->grpc_caller = grpc_call_start_batch_and_execute;
@@ -713,7 +713,7 @@ alts_handshaker_client* alts_grpc_handshaker_client_create(
client->max_frame_size = max_frame_size;
client->buffer_size = TSI_ALTS_INITIAL_BUFFER_SIZE;
client->buffer = static_cast<unsigned char*>(gpr_zalloc(client->buffer_size));
- grpc_slice slice = grpc_slice_from_copied_string(handshaker_service_url);
+ grpc_slice slice = grpc_slice_from_copied_string(handshaker_service_url);
client->call =
strcmp(handshaker_service_url, ALTS_HANDSHAKER_SERVICE_URL_FOR_TESTING) ==
0
@@ -729,20 +729,20 @@ alts_handshaker_client* alts_grpc_handshaker_client_create(
GRPC_CLOSURE_INIT(&client->on_status_received, on_status_received, client,
grpc_schedule_on_exec_ctx);
grpc_slice_unref_internal(slice);
- return &client->base;
-}
-
-namespace grpc_core {
-namespace internal {
-
-void alts_handshaker_client_set_grpc_caller_for_testing(
+ return &client->base;
+}
+
+namespace grpc_core {
+namespace internal {
+
+void alts_handshaker_client_set_grpc_caller_for_testing(
alts_handshaker_client* c, alts_grpc_caller caller) {
GPR_ASSERT(c != nullptr && caller != nullptr);
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
client->grpc_caller = caller;
-}
-
+}
+
grpc_byte_buffer* alts_handshaker_client_get_send_buffer_for_testing(
alts_handshaker_client* c) {
GPR_ASSERT(c != nullptr);
@@ -858,41 +858,41 @@ void alts_handshaker_client_on_status_received_for_testing(
grpc_core::Closure::Run(DEBUG_LOCATION, &client->on_status_received, error);
}
-} // namespace internal
-} // namespace grpc_core
-
+} // namespace internal
+} // namespace grpc_core
+
tsi_result alts_handshaker_client_start_client(alts_handshaker_client* client) {
- if (client != nullptr && client->vtable != nullptr &&
- client->vtable->client_start != nullptr) {
+ if (client != nullptr && client->vtable != nullptr &&
+ client->vtable->client_start != nullptr) {
return client->vtable->client_start(client);
- }
- gpr_log(GPR_ERROR,
- "client or client->vtable has not been initialized properly");
- return TSI_INVALID_ARGUMENT;
-}
-
-tsi_result alts_handshaker_client_start_server(alts_handshaker_client* client,
- grpc_slice* bytes_received) {
- if (client != nullptr && client->vtable != nullptr &&
- client->vtable->server_start != nullptr) {
+ }
+ gpr_log(GPR_ERROR,
+ "client or client->vtable has not been initialized properly");
+ return TSI_INVALID_ARGUMENT;
+}
+
+tsi_result alts_handshaker_client_start_server(alts_handshaker_client* client,
+ grpc_slice* bytes_received) {
+ if (client != nullptr && client->vtable != nullptr &&
+ client->vtable->server_start != nullptr) {
return client->vtable->server_start(client, bytes_received);
- }
- gpr_log(GPR_ERROR,
- "client or client->vtable has not been initialized properly");
- return TSI_INVALID_ARGUMENT;
-}
-
-tsi_result alts_handshaker_client_next(alts_handshaker_client* client,
- grpc_slice* bytes_received) {
- if (client != nullptr && client->vtable != nullptr &&
- client->vtable->next != nullptr) {
+ }
+ gpr_log(GPR_ERROR,
+ "client or client->vtable has not been initialized properly");
+ return TSI_INVALID_ARGUMENT;
+}
+
+tsi_result alts_handshaker_client_next(alts_handshaker_client* client,
+ grpc_slice* bytes_received) {
+ if (client != nullptr && client->vtable != nullptr &&
+ client->vtable->next != nullptr) {
return client->vtable->next(client, bytes_received);
- }
- gpr_log(GPR_ERROR,
- "client or client->vtable has not been initialized properly");
- return TSI_INVALID_ARGUMENT;
-}
-
+ }
+ gpr_log(GPR_ERROR,
+ "client or client->vtable has not been initialized properly");
+ return TSI_INVALID_ARGUMENT;
+}
+
void alts_handshaker_client_shutdown(alts_handshaker_client* client) {
if (client != nullptr && client->vtable != nullptr &&
client->vtable->shutdown != nullptr) {
@@ -905,5 +905,5 @@ void alts_handshaker_client_destroy(alts_handshaker_client* c) {
alts_grpc_handshaker_client* client =
reinterpret_cast<alts_grpc_handshaker_client*>(c);
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 d8669da01cb..b125111e245 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
@@ -1,109 +1,109 @@
-/*
- *
- * 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_TSI_ALTS_HANDSHAKER_ALTS_HANDSHAKER_CLIENT_H
-#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_HANDSHAKER_CLIENT_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_TSI_ALTS_HANDSHAKER_ALTS_HANDSHAKER_CLIENT_H
+#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_HANDSHAKER_CLIENT_H
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/byte_buffer.h>
#include <grpc/byte_buffer_reader.h>
-#include <grpc/grpc.h>
-
+#include <grpc/grpc.h>
+
#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h"
#include "src/core/tsi/transport_security_interface.h"
-
+
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/pollset_set.h"
-#define ALTS_SERVICE_METHOD "/grpc.gcp.HandshakerService/DoHandshake"
-#define ALTS_APPLICATION_PROTOCOL "grpc"
-#define ALTS_RECORD_PROTOCOL "ALTSRP_GCM_AES128_REKEY"
+#define ALTS_SERVICE_METHOD "/grpc.gcp.HandshakerService/DoHandshake"
+#define ALTS_APPLICATION_PROTOCOL "grpc"
+#define ALTS_RECORD_PROTOCOL "ALTSRP_GCM_AES128_REKEY"
#define ALTS_HANDSHAKER_SERVICE_URL_FOR_TESTING "lame"
-
-const size_t kAltsAes128GcmRekeyKeyLength = 44;
-
+
+const size_t kAltsAes128GcmRekeyKeyLength = 44;
+
typedef struct alts_tsi_handshaker alts_tsi_handshaker;
-/**
- * A ALTS handshaker client interface. It is used to communicate with
- * ALTS handshaker service by scheduling a handshaker request that could be one
- * of client_start, server_start, and next handshaker requests. All APIs in the
- * header are thread-compatible.
- */
-typedef struct alts_handshaker_client alts_handshaker_client;
-
-/* A function that makes the grpc call to the handshaker service. */
-typedef grpc_call_error (*alts_grpc_caller)(grpc_call* call, const grpc_op* ops,
+/**
+ * A ALTS handshaker client interface. It is used to communicate with
+ * ALTS handshaker service by scheduling a handshaker request that could be one
+ * of client_start, server_start, and next handshaker requests. All APIs in the
+ * header are thread-compatible.
+ */
+typedef struct alts_handshaker_client alts_handshaker_client;
+
+/* A function that makes the grpc call to the handshaker service. */
+typedef grpc_call_error (*alts_grpc_caller)(grpc_call* call, const grpc_op* ops,
size_t nops, grpc_closure* tag);
-
-/* V-table for ALTS handshaker client operations. */
-typedef struct alts_handshaker_client_vtable {
+
+/* V-table for ALTS handshaker client operations. */
+typedef struct alts_handshaker_client_vtable {
tsi_result (*client_start)(alts_handshaker_client* client);
- tsi_result (*server_start)(alts_handshaker_client* client,
+ tsi_result (*server_start)(alts_handshaker_client* client,
grpc_slice* bytes_received);
tsi_result (*next)(alts_handshaker_client* client,
- grpc_slice* bytes_received);
+ grpc_slice* bytes_received);
void (*shutdown)(alts_handshaker_client* client);
- void (*destruct)(alts_handshaker_client* client);
-} alts_handshaker_client_vtable;
-
-/**
- * This method schedules a client_start handshaker request to ALTS handshaker
- * service.
- *
- * - client: ALTS handshaker client instance.
- *
- * It returns TSI_OK on success and an error status code on failure.
- */
+ void (*destruct)(alts_handshaker_client* client);
+} alts_handshaker_client_vtable;
+
+/**
+ * This method schedules a client_start handshaker request to ALTS handshaker
+ * service.
+ *
+ * - client: ALTS handshaker client instance.
+ *
+ * It returns TSI_OK on success and an error status code on failure.
+ */
tsi_result alts_handshaker_client_start_client(alts_handshaker_client* client);
-
-/**
- * This method schedules a server_start handshaker request to ALTS handshaker
- * service.
- *
- * - client: ALTS handshaker client instance.
- * - bytes_received: bytes in out_frames returned from the peer's handshaker
- * response.
- *
- * It returns TSI_OK on success and an error status code on failure.
- */
-tsi_result alts_handshaker_client_start_server(alts_handshaker_client* client,
- grpc_slice* bytes_received);
-
-/**
- * This method schedules a next handshaker request to ALTS handshaker service.
- *
- * - client: ALTS handshaker client instance.
- * - bytes_received: bytes in out_frames returned from the peer's handshaker
- * response.
- *
- * It returns TSI_OK on success and an error status code on failure.
- */
-tsi_result alts_handshaker_client_next(alts_handshaker_client* client,
- grpc_slice* bytes_received);
-
-/**
+
+/**
+ * This method schedules a server_start handshaker request to ALTS handshaker
+ * service.
+ *
+ * - client: ALTS handshaker client instance.
+ * - bytes_received: bytes in out_frames returned from the peer's handshaker
+ * response.
+ *
+ * It returns TSI_OK on success and an error status code on failure.
+ */
+tsi_result alts_handshaker_client_start_server(alts_handshaker_client* client,
+ grpc_slice* bytes_received);
+
+/**
+ * This method schedules a next handshaker request to ALTS handshaker service.
+ *
+ * - client: ALTS handshaker client instance.
+ * - bytes_received: bytes in out_frames returned from the peer's handshaker
+ * response.
+ *
+ * It returns TSI_OK on success and an error status code on failure.
+ */
+tsi_result alts_handshaker_client_next(alts_handshaker_client* client,
+ grpc_slice* bytes_received);
+
+/**
* This method cancels previously scheduled, but yet executed handshaker
* requests to ALTS handshaker service. After this operation, the handshake
* will be shutdown, and no more handshaker requests will get scheduled.
- *
+ *
* - client: ALTS handshaker client instance.
- */
+ */
void alts_handshaker_client_shutdown(alts_handshaker_client* client);
/**
@@ -111,16 +111,16 @@ void alts_handshaker_client_shutdown(alts_handshaker_client* client);
*
* - client: an ALTS handshaker client instance.
*/
-void alts_handshaker_client_destroy(alts_handshaker_client* client);
-
-/**
+void alts_handshaker_client_destroy(alts_handshaker_client* client);
+
+/**
* This method creates an ALTS handshaker client.
- *
+ *
* - handshaker: ALTS TSI handshaker to which the created handshaker client
* belongs to.
- * - channel: grpc channel to ALTS handshaker service.
- * - handshaker_service_url: address of ALTS handshaker service in the format of
- * "host:port".
+ * - channel: grpc channel to ALTS handshaker service.
+ * - handshaker_service_url: address of ALTS handshaker service in the format of
+ * "host:port".
* - interested_parties: set of pollsets interested in this connection.
* - options: ALTS credentials options containing information passed from TSI
* caller (e.g., rpc protocol versions)
@@ -138,24 +138,24 @@ void alts_handshaker_client_destroy(alts_handshaker_client* client);
*
* It returns the created ALTS handshaker client on success, and NULL
* on failure.
- */
-alts_handshaker_client* alts_grpc_handshaker_client_create(
+ */
+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_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);
-
-/**
+
+/**
* This method handles handshaker response returned from ALTS handshaker
* service. Note that the only reason the API is exposed is that it is used in
* alts_shared_resources.cc.
*
* - client: an ALTS handshaker client instance.
* - is_ok: a boolean value indicating if the handshaker response is ok to read.
- */
+ */
void alts_handshaker_client_handle_response(alts_handshaker_client* client,
bool is_ok);
-
-#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_HANDSHAKER_CLIENT_H */
+
+#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_HANDSHAKER_CLIENT_H */
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 01ef56157a5..97f2e3c5333 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
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.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 "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
#include "upb/upb.hpp"
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.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/thd_id.h>
-
+#include <grpc/support/sync.h>
+#include <grpc/support/thd_id.h>
+
#include "src/core/lib/gprpp/sync.h"
-#include "src/core/lib/gprpp/thd.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/tsi/alts/frame_protector/alts_frame_protector.h"
-#include "src/core/tsi/alts/handshaker/alts_handshaker_client.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"
-#include "src/core/tsi/alts/handshaker/alts_tsi_utils.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h"
-
-/* Main struct for ALTS TSI handshaker. */
+#include "src/core/tsi/alts/handshaker/alts_tsi_utils.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h"
+
+/* Main struct for ALTS TSI handshaker. */
struct alts_tsi_handshaker {
- tsi_handshaker base;
- grpc_slice target_name;
- bool is_client;
- bool has_sent_start_message;
+ tsi_handshaker base;
+ grpc_slice target_name;
+ bool is_client;
+ bool has_sent_start_message;
bool has_created_handshaker_client;
char* handshaker_service_url;
grpc_pollset_set* interested_parties;
- grpc_alts_credentials_options* options;
+ grpc_alts_credentials_options* options;
alts_handshaker_client_vtable* client_vtable_for_testing;
grpc_channel* channel;
bool use_dedicated_cq;
@@ -68,65 +68,65 @@ struct alts_tsi_handshaker {
// Maximum frame size used by frame protector.
size_t max_frame_size;
};
-
-/* Main struct for ALTS TSI handshaker result. */
-typedef struct alts_tsi_handshaker_result {
- tsi_handshaker_result base;
- char* peer_identity;
- char* key_data;
- unsigned char* unused_bytes;
- size_t unused_bytes_size;
- grpc_slice rpc_versions;
- bool is_client;
+
+/* Main struct for ALTS TSI handshaker result. */
+typedef struct alts_tsi_handshaker_result {
+ tsi_handshaker_result base;
+ char* peer_identity;
+ char* key_data;
+ unsigned char* unused_bytes;
+ size_t unused_bytes_size;
+ grpc_slice rpc_versions;
+ bool is_client;
grpc_slice serialized_context;
// Peer's maximum frame size.
size_t max_frame_size;
-} alts_tsi_handshaker_result;
-
-static tsi_result handshaker_result_extract_peer(
- const tsi_handshaker_result* self, tsi_peer* peer) {
- if (self == nullptr || peer == nullptr) {
- gpr_log(GPR_ERROR, "Invalid argument to handshaker_result_extract_peer()");
- return TSI_INVALID_ARGUMENT;
- }
- alts_tsi_handshaker_result* result =
- reinterpret_cast<alts_tsi_handshaker_result*>(
- const_cast<tsi_handshaker_result*>(self));
+} alts_tsi_handshaker_result;
+
+static tsi_result handshaker_result_extract_peer(
+ const tsi_handshaker_result* self, tsi_peer* peer) {
+ if (self == nullptr || peer == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid argument to handshaker_result_extract_peer()");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_tsi_handshaker_result* result =
+ reinterpret_cast<alts_tsi_handshaker_result*>(
+ const_cast<tsi_handshaker_result*>(self));
GPR_ASSERT(kTsiAltsNumOfPeerProperties == 5);
- tsi_result ok = tsi_construct_peer(kTsiAltsNumOfPeerProperties, peer);
- int index = 0;
- if (ok != TSI_OK) {
- gpr_log(GPR_ERROR, "Failed to construct tsi peer");
- return ok;
- }
- GPR_ASSERT(&peer->properties[index] != nullptr);
- ok = tsi_construct_string_peer_property_from_cstring(
- TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_ALTS_CERTIFICATE_TYPE,
- &peer->properties[index]);
- if (ok != TSI_OK) {
- tsi_peer_destruct(peer);
- gpr_log(GPR_ERROR, "Failed to set tsi peer property");
- return ok;
- }
- index++;
- GPR_ASSERT(&peer->properties[index] != nullptr);
- ok = tsi_construct_string_peer_property_from_cstring(
- TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY, result->peer_identity,
- &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_RPC_VERSIONS,
- reinterpret_cast<char*>(GRPC_SLICE_START_PTR(result->rpc_versions)),
+ tsi_result ok = tsi_construct_peer(kTsiAltsNumOfPeerProperties, peer);
+ int index = 0;
+ if (ok != TSI_OK) {
+ gpr_log(GPR_ERROR, "Failed to construct tsi peer");
+ return ok;
+ }
+ GPR_ASSERT(&peer->properties[index] != nullptr);
+ ok = tsi_construct_string_peer_property_from_cstring(
+ TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_ALTS_CERTIFICATE_TYPE,
+ &peer->properties[index]);
+ if (ok != TSI_OK) {
+ tsi_peer_destruct(peer);
+ gpr_log(GPR_ERROR, "Failed to set tsi peer property");
+ return ok;
+ }
+ index++;
+ GPR_ASSERT(&peer->properties[index] != nullptr);
+ ok = tsi_construct_string_peer_property_from_cstring(
+ TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY, result->peer_identity,
+ &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_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");
- }
+ 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(
@@ -147,21 +147,21 @@ static tsi_result handshaker_result_extract_peer(
tsi_peer_destruct(peer);
gpr_log(GPR_ERROR, "Failed to set tsi peer property");
}
- GPR_ASSERT(++index == kTsiAltsNumOfPeerProperties);
- return ok;
-}
-
-static tsi_result handshaker_result_create_zero_copy_grpc_protector(
- 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,
- "Invalid arguments to create_zero_copy_grpc_protector()");
- return TSI_INVALID_ARGUMENT;
- }
- alts_tsi_handshaker_result* result =
- reinterpret_cast<alts_tsi_handshaker_result*>(
- const_cast<tsi_handshaker_result*>(self));
+ GPR_ASSERT(++index == kTsiAltsNumOfPeerProperties);
+ return ok;
+}
+
+static tsi_result handshaker_result_create_zero_copy_grpc_protector(
+ 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,
+ "Invalid arguments to create_zero_copy_grpc_protector()");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_tsi_handshaker_result* result =
+ reinterpret_cast<alts_tsi_handshaker_result*>(
+ const_cast<tsi_handshaker_result*>(self));
// In case the peer does not send max frame size (e.g. peer is gRPC Go or
// peer uses an old binary), the negotiated frame size is set to
@@ -182,90 +182,90 @@ static tsi_result handshaker_result_create_zero_copy_grpc_protector(
"After Frame Size Negotiation, maximum frame size used by frame "
"protector equals %zu",
*max_output_protected_frame_size);
- tsi_result ok = alts_zero_copy_grpc_protector_create(
- reinterpret_cast<const uint8_t*>(result->key_data),
- kAltsAes128GcmRekeyKeyLength, /*is_rekey=*/true, result->is_client,
+ tsi_result ok = alts_zero_copy_grpc_protector_create(
+ reinterpret_cast<const uint8_t*>(result->key_data),
+ kAltsAes128GcmRekeyKeyLength, /*is_rekey=*/true, result->is_client,
/*is_integrity_only=*/false, /*enable_extra_copy=*/false,
max_output_protected_frame_size, protector);
- if (ok != TSI_OK) {
- gpr_log(GPR_ERROR, "Failed to create zero-copy grpc protector");
- }
- return ok;
-}
-
-static tsi_result handshaker_result_create_frame_protector(
- const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
- tsi_frame_protector** protector) {
- if (self == nullptr || protector == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid arguments to handshaker_result_create_frame_protector()");
- return TSI_INVALID_ARGUMENT;
- }
- alts_tsi_handshaker_result* result =
- reinterpret_cast<alts_tsi_handshaker_result*>(
- const_cast<tsi_handshaker_result*>(self));
- tsi_result ok = alts_create_frame_protector(
- reinterpret_cast<const uint8_t*>(result->key_data),
- kAltsAes128GcmRekeyKeyLength, result->is_client, /*is_rekey=*/true,
- max_output_protected_frame_size, protector);
- if (ok != TSI_OK) {
- gpr_log(GPR_ERROR, "Failed to create frame protector");
- }
- return ok;
-}
-
-static tsi_result handshaker_result_get_unused_bytes(
- const tsi_handshaker_result* self, const unsigned char** bytes,
- size_t* bytes_size) {
- if (self == nullptr || bytes == nullptr || bytes_size == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid arguments to handshaker_result_get_unused_bytes()");
- return TSI_INVALID_ARGUMENT;
- }
- alts_tsi_handshaker_result* result =
- reinterpret_cast<alts_tsi_handshaker_result*>(
- const_cast<tsi_handshaker_result*>(self));
- *bytes = result->unused_bytes;
- *bytes_size = result->unused_bytes_size;
- return TSI_OK;
-}
-
-static void handshaker_result_destroy(tsi_handshaker_result* self) {
- if (self == nullptr) {
- return;
- }
- alts_tsi_handshaker_result* result =
- reinterpret_cast<alts_tsi_handshaker_result*>(
- const_cast<tsi_handshaker_result*>(self));
- gpr_free(result->peer_identity);
- gpr_free(result->key_data);
- gpr_free(result->unused_bytes);
+ if (ok != TSI_OK) {
+ gpr_log(GPR_ERROR, "Failed to create zero-copy grpc protector");
+ }
+ return ok;
+}
+
+static tsi_result handshaker_result_create_frame_protector(
+ const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
+ tsi_frame_protector** protector) {
+ if (self == nullptr || protector == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid arguments to handshaker_result_create_frame_protector()");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_tsi_handshaker_result* result =
+ reinterpret_cast<alts_tsi_handshaker_result*>(
+ const_cast<tsi_handshaker_result*>(self));
+ tsi_result ok = alts_create_frame_protector(
+ reinterpret_cast<const uint8_t*>(result->key_data),
+ kAltsAes128GcmRekeyKeyLength, result->is_client, /*is_rekey=*/true,
+ max_output_protected_frame_size, protector);
+ if (ok != TSI_OK) {
+ gpr_log(GPR_ERROR, "Failed to create frame protector");
+ }
+ return ok;
+}
+
+static tsi_result handshaker_result_get_unused_bytes(
+ const tsi_handshaker_result* self, const unsigned char** bytes,
+ size_t* bytes_size) {
+ if (self == nullptr || bytes == nullptr || bytes_size == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid arguments to handshaker_result_get_unused_bytes()");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_tsi_handshaker_result* result =
+ reinterpret_cast<alts_tsi_handshaker_result*>(
+ const_cast<tsi_handshaker_result*>(self));
+ *bytes = result->unused_bytes;
+ *bytes_size = result->unused_bytes_size;
+ return TSI_OK;
+}
+
+static void handshaker_result_destroy(tsi_handshaker_result* self) {
+ if (self == nullptr) {
+ return;
+ }
+ alts_tsi_handshaker_result* result =
+ reinterpret_cast<alts_tsi_handshaker_result*>(
+ const_cast<tsi_handshaker_result*>(self));
+ gpr_free(result->peer_identity);
+ gpr_free(result->key_data);
+ gpr_free(result->unused_bytes);
grpc_slice_unref_internal(result->rpc_versions);
grpc_slice_unref_internal(result->serialized_context);
- gpr_free(result);
-}
-
-static const tsi_handshaker_result_vtable result_vtable = {
- handshaker_result_extract_peer,
- handshaker_result_create_zero_copy_grpc_protector,
- handshaker_result_create_frame_protector,
- handshaker_result_get_unused_bytes, handshaker_result_destroy};
-
+ gpr_free(result);
+}
+
+static const tsi_handshaker_result_vtable result_vtable = {
+ handshaker_result_extract_peer,
+ handshaker_result_create_zero_copy_grpc_protector,
+ handshaker_result_create_frame_protector,
+ handshaker_result_get_unused_bytes, handshaker_result_destroy};
+
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;
- }
+ 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);
- if (identity == nullptr) {
+ if (identity == nullptr) {
gpr_log(GPR_ERROR, "Invalid identity");
- return TSI_FAILED_PRECONDITION;
- }
+ return TSI_FAILED_PRECONDITION;
+ }
upb_strview peer_service_account =
grpc_gcp_Identity_service_account(identity);
if (peer_service_account.size == 0) {
@@ -274,9 +274,9 @@ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
}
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;
- }
+ 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) {
@@ -305,10 +305,10 @@ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
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));
+ 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));
@@ -320,8 +320,8 @@ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
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;
- }
+ 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);
@@ -361,16 +361,16 @@ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
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;
- }
+ return TSI_FAILED_PRECONDITION;
+ }
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;
- return TSI_OK;
-}
-
+ result->is_client = is_client;
+ result->base.vtable = &result_vtable;
+ *self = &result->base;
+ return TSI_OK;
+}
+
/* gRPC provided callback used when gRPC thread model is applied. */
static void on_handshaker_service_resp_recv(void* arg, grpc_error* error) {
alts_handshaker_client* client = static_cast<alts_handshaker_client*>(arg);
@@ -439,21 +439,21 @@ static tsi_result alts_tsi_handshaker_continue_handshaker_next(
}
}
handshaker->has_created_handshaker_client = true;
- }
+ }
if (handshaker->channel == nullptr &&
handshaker->client_vtable_for_testing == nullptr) {
GPR_ASSERT(grpc_cq_begin_op(grpc_alts_get_shared_resource_dedicated()->cq,
handshaker->client));
}
- grpc_slice slice = (received_bytes == nullptr || received_bytes_size == 0)
- ? grpc_empty_slice()
- : grpc_slice_from_copied_buffer(
- reinterpret_cast<const char*>(received_bytes),
- received_bytes_size);
+ grpc_slice slice = (received_bytes == nullptr || received_bytes_size == 0)
+ ? grpc_empty_slice()
+ : grpc_slice_from_copied_buffer(
+ reinterpret_cast<const char*>(received_bytes),
+ received_bytes_size);
tsi_result ok = TSI_OK;
- if (!handshaker->has_sent_start_message) {
+ if (!handshaker->has_sent_start_message) {
handshaker->has_sent_start_message = true;
- ok = handshaker->is_client
+ 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
@@ -463,9 +463,9 @@ static tsi_result alts_tsi_handshaker_continue_handshaker_next(
// 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 {
+ } else {
ok = alts_handshaker_client_next(handshaker->client, &slice);
- }
+ }
grpc_slice_unref_internal(slice);
return ok;
}
@@ -494,7 +494,7 @@ static void alts_tsi_handshaker_create_channel(void* arg,
if (continue_next_result != TSI_OK) {
next_args->cb(continue_next_result, next_args->user_data, nullptr, 0,
nullptr);
- }
+ }
delete next_args;
}
@@ -545,9 +545,9 @@ static tsi_result handshaker_next(
return ok;
}
}
- return TSI_ASYNC;
-}
-
+ return TSI_ASYNC;
+}
+
/*
* This API will be invoked by a non-gRPC application, and an ExecCtx needs
* to be explicitly created in order to invoke ALTS handshaker client API's
@@ -578,29 +578,29 @@ static void handshaker_shutdown(tsi_handshaker* self) {
handshaker->shutdown = true;
}
-static void handshaker_destroy(tsi_handshaker* self) {
- if (self == nullptr) {
- return;
- }
- alts_tsi_handshaker* handshaker =
- reinterpret_cast<alts_tsi_handshaker*>(self);
- alts_handshaker_client_destroy(handshaker->client);
+static void handshaker_destroy(tsi_handshaker* self) {
+ if (self == nullptr) {
+ return;
+ }
+ alts_tsi_handshaker* handshaker =
+ reinterpret_cast<alts_tsi_handshaker*>(self);
+ alts_handshaker_client_destroy(handshaker->client);
grpc_slice_unref_internal(handshaker->target_name);
- grpc_alts_credentials_options_destroy(handshaker->options);
+ grpc_alts_credentials_options_destroy(handshaker->options);
if (handshaker->channel != nullptr) {
grpc_channel_destroy_internal(handshaker->channel);
}
gpr_free(handshaker->handshaker_service_url);
gpr_mu_destroy(&handshaker->mu);
- gpr_free(handshaker);
-}
-
-static const tsi_handshaker_vtable handshaker_vtable = {
+ gpr_free(handshaker);
+}
+
+static const tsi_handshaker_vtable handshaker_vtable = {
nullptr, nullptr,
nullptr, nullptr,
nullptr, handshaker_destroy,
handshaker_next, handshaker_shutdown};
-
+
static const tsi_handshaker_vtable handshaker_vtable_dedicated = {
nullptr,
nullptr,
@@ -610,89 +610,89 @@ static const tsi_handshaker_vtable handshaker_vtable_dedicated = {
handshaker_destroy,
handshaker_next_dedicated,
handshaker_shutdown};
-
+
bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker) {
GPR_ASSERT(handshaker != nullptr);
grpc_core::MutexLock lock(&handshaker->mu);
return handshaker->shutdown;
-}
-
-tsi_result alts_tsi_handshaker_create(
- const grpc_alts_credentials_options* options, const char* target_name,
+}
+
+tsi_result alts_tsi_handshaker_create(
+ const grpc_alts_credentials_options* options, const char* target_name,
const char* handshaker_service_url, bool is_client,
grpc_pollset_set* interested_parties, tsi_handshaker** self,
size_t user_specified_max_frame_size) {
- if (handshaker_service_url == nullptr || self == nullptr ||
- options == nullptr || (is_client && target_name == nullptr)) {
- gpr_log(GPR_ERROR, "Invalid arguments to alts_tsi_handshaker_create()");
- return TSI_INVALID_ARGUMENT;
- }
- alts_tsi_handshaker* handshaker =
- static_cast<alts_tsi_handshaker*>(gpr_zalloc(sizeof(*handshaker)));
+ if (handshaker_service_url == nullptr || self == nullptr ||
+ options == nullptr || (is_client && target_name == nullptr)) {
+ gpr_log(GPR_ERROR, "Invalid arguments to alts_tsi_handshaker_create()");
+ return TSI_INVALID_ARGUMENT;
+ }
+ 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;
handshaker->client = nullptr;
- handshaker->is_client = is_client;
- handshaker->has_sent_start_message = false;
- handshaker->target_name = target_name == nullptr
- ? grpc_empty_slice()
- : grpc_slice_from_static_string(target_name);
+ handshaker->is_client = is_client;
+ handshaker->has_sent_start_message = false;
+ handshaker->target_name = target_name == nullptr
+ ? grpc_empty_slice()
+ : grpc_slice_from_static_string(target_name);
handshaker->interested_parties = interested_parties;
handshaker->has_created_handshaker_client = false;
handshaker->handshaker_service_url = gpr_strdup(handshaker_service_url);
- handshaker->options = grpc_alts_credentials_options_copy(options);
+ handshaker->options = grpc_alts_credentials_options_copy(options);
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;
- *self = &handshaker->base;
- return TSI_OK;
-}
-
+ *self = &handshaker->base;
+ return TSI_OK;
+}
+
void alts_tsi_handshaker_result_set_unused_bytes(tsi_handshaker_result* self,
grpc_slice* recv_bytes,
size_t bytes_consumed) {
- GPR_ASSERT(recv_bytes != nullptr && self != nullptr);
- if (GRPC_SLICE_LENGTH(*recv_bytes) == bytes_consumed) {
- return;
- }
- alts_tsi_handshaker_result* result =
- reinterpret_cast<alts_tsi_handshaker_result*>(self);
- result->unused_bytes_size = GRPC_SLICE_LENGTH(*recv_bytes) - bytes_consumed;
- result->unused_bytes =
- static_cast<unsigned char*>(gpr_zalloc(result->unused_bytes_size));
- memcpy(result->unused_bytes,
- GRPC_SLICE_START_PTR(*recv_bytes) + bytes_consumed,
- result->unused_bytes_size);
-}
-
-namespace grpc_core {
-namespace internal {
-
-bool alts_tsi_handshaker_get_has_sent_start_message_for_testing(
- alts_tsi_handshaker* handshaker) {
- GPR_ASSERT(handshaker != nullptr);
- return handshaker->has_sent_start_message;
-}
-
+ GPR_ASSERT(recv_bytes != nullptr && self != nullptr);
+ if (GRPC_SLICE_LENGTH(*recv_bytes) == bytes_consumed) {
+ return;
+ }
+ alts_tsi_handshaker_result* result =
+ reinterpret_cast<alts_tsi_handshaker_result*>(self);
+ result->unused_bytes_size = GRPC_SLICE_LENGTH(*recv_bytes) - bytes_consumed;
+ result->unused_bytes =
+ static_cast<unsigned char*>(gpr_zalloc(result->unused_bytes_size));
+ memcpy(result->unused_bytes,
+ GRPC_SLICE_START_PTR(*recv_bytes) + bytes_consumed,
+ result->unused_bytes_size);
+}
+
+namespace grpc_core {
+namespace internal {
+
+bool alts_tsi_handshaker_get_has_sent_start_message_for_testing(
+ alts_tsi_handshaker* handshaker) {
+ GPR_ASSERT(handshaker != nullptr);
+ return handshaker->has_sent_start_message;
+}
+
void alts_tsi_handshaker_set_client_vtable_for_testing(
alts_tsi_handshaker* handshaker, alts_handshaker_client_vtable* vtable) {
GPR_ASSERT(handshaker != nullptr);
handshaker->client_vtable_for_testing = vtable;
}
-bool alts_tsi_handshaker_get_is_client_for_testing(
- alts_tsi_handshaker* handshaker) {
- GPR_ASSERT(handshaker != nullptr);
- return handshaker->is_client;
-}
-
+bool alts_tsi_handshaker_get_is_client_for_testing(
+ alts_tsi_handshaker* handshaker) {
+ GPR_ASSERT(handshaker != nullptr);
+ return handshaker->is_client;
+}
+
alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing(
- alts_tsi_handshaker* handshaker) {
+ alts_tsi_handshaker* handshaker) {
return handshaker->client;
-}
-
-} // namespace internal
-} // namespace grpc_core
+}
+
+} // namespace internal
+} // namespace grpc_core
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 e1ae985a84d..c2d2068fd7b 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
@@ -1,80 +1,80 @@
-/*
- *
- * 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_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_H
-#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/grpc.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_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_H
+#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/grpc.h>
+
#include "src/core/lib/iomgr/pollset_set.h"
-#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
+#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h"
#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/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"
-
+
#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_CERTIFICATE_TYPE "ALTS"
+#define TSI_ALTS_RPC_VERSIONS "rpc_versions"
#define TSI_ALTS_CONTEXT "alts_context"
-
+
const size_t kTsiAltsNumOfPeerProperties = 5;
-
+
// Frame size negotiation extends send frame size range to
// [kTsiAltsMinFrameSize, kTsiAltsMaxFrameSize].
const size_t kTsiAltsMinFrameSize = 16 * 1024;
const size_t kTsiAltsMaxFrameSize = 128 * 1024;
-typedef struct alts_tsi_handshaker alts_tsi_handshaker;
-
-/**
- * This method creates a ALTS TSI handshaker instance.
- *
- * - options: ALTS credentials options containing information passed from TSI
- * caller (e.g., rpc protocol versions).
- * - target_name: the name of the endpoint that the channel is connecting to,
- * and will be used for secure naming check.
- * - handshaker_service_url: address of ALTS handshaker service in the format of
- * "host:port".
- * - is_client: boolean value indicating if the handshaker is used at the client
- * (is_client = true) or server (is_client = false) side.
+typedef struct alts_tsi_handshaker alts_tsi_handshaker;
+
+/**
+ * This method creates a ALTS TSI handshaker instance.
+ *
+ * - options: ALTS credentials options containing information passed from TSI
+ * caller (e.g., rpc protocol versions).
+ * - target_name: the name of the endpoint that the channel is connecting to,
+ * and will be used for secure naming check.
+ * - handshaker_service_url: address of ALTS handshaker service in the format of
+ * "host:port".
+ * - is_client: boolean value indicating if the handshaker is used at the client
+ * (is_client = true) or server (is_client = false) side.
* - interested_parties: set of pollsets interested in this connection.
- * - self: address of ALTS TSI handshaker instance to be returned from the
- * method.
+ * - self: address of ALTS TSI handshaker instance to be returned from the
+ * method.
* - user_specified_max_frame_size: Determines the maximum frame size used by
* frame protector that is specified via user. If unspecified, the value is 0.
- *
+ *
* It returns TSI_OK on success and an error status code on failure. Note that
* if interested_parties is nullptr, a dedicated TSI thread will be created and
* used.
- */
-tsi_result alts_tsi_handshaker_create(
- const grpc_alts_credentials_options* options, const char* target_name,
+ */
+tsi_result alts_tsi_handshaker_create(
+ const grpc_alts_credentials_options* options, const char* target_name,
const char* handshaker_service_url, bool is_client,
grpc_pollset_set* interested_parties, tsi_handshaker** self,
size_t user_specified_max_frame_size);
-
-/**
+
+/**
* This method creates an ALTS TSI handshaker result instance.
- *
+ *
* - resp: data received from the handshaker service.
* - is_client: a boolean value indicating if the result belongs to a
* client or not.
@@ -86,19 +86,19 @@ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp,
/**
* This method sets unused bytes of ALTS TSI handshaker result instance.
- *
+ *
* - result: an ALTS TSI handshaker result instance.
* - recv_bytes: data received from the handshaker service.
* - bytes_consumed: size of data consumed by the handshaker service.
- */
+ */
void alts_tsi_handshaker_result_set_unused_bytes(tsi_handshaker_result* result,
grpc_slice* recv_bytes,
size_t bytes_consumed);
-
+
/**
* This method returns a boolean value indicating if an ALTS TSI handshaker
* has been shutdown or not.
*/
bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker);
-#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_H */
+#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_H */
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 cb99fdcce0d..bab2ddb349f 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
@@ -1,52 +1,52 @@
-/*
- *
- * 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_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_PRIVATE_H
-#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_PRIVATE_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
-
-namespace grpc_core {
-namespace internal {
-
-/**
+/*
+ *
+ * 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_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_PRIVATE_H
+#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_PRIVATE_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
+
+namespace grpc_core {
+namespace internal {
+
+/**
* Unsafe, use for testing only. */
-
+
alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing(
alts_tsi_handshaker* handshaker);
-bool alts_tsi_handshaker_get_has_sent_start_message_for_testing(
- alts_tsi_handshaker* handshaker);
-
+bool alts_tsi_handshaker_get_has_sent_start_message_for_testing(
+ alts_tsi_handshaker* handshaker);
+
void alts_tsi_handshaker_set_client_vtable_for_testing(
alts_tsi_handshaker* handshaker, alts_handshaker_client_vtable* vtable);
-bool alts_tsi_handshaker_get_is_client_for_testing(
- alts_tsi_handshaker* handshaker);
-
+bool alts_tsi_handshaker_get_is_client_for_testing(
+ alts_tsi_handshaker* handshaker);
+
void alts_handshaker_client_set_grpc_caller_for_testing(
alts_handshaker_client* client, alts_grpc_caller caller);
-
+
grpc_byte_buffer* alts_handshaker_client_get_send_buffer_for_testing(
alts_handshaker_client* client);
-
+
grpc_byte_buffer** alts_handshaker_client_get_recv_buffer_addr_for_testing(
alts_handshaker_client* client);
@@ -82,7 +82,7 @@ void alts_handshaker_client_on_status_received_for_testing(
void alts_handshaker_client_ref_for_testing(alts_handshaker_client* c);
-} // namespace internal
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_PRIVATE_H */
+} // namespace internal
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_PRIVATE_H */
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 f80498db990..3decab7c7e6 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
@@ -1,53 +1,53 @@
-/*
- *
- * 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/handshaker/alts_tsi_utils.h"
-
-#include <grpc/byte_buffer_reader.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 "src/core/tsi/alts/handshaker/alts_tsi_utils.h"
+
+#include <grpc/byte_buffer_reader.h>
+
#include "src/core/lib/slice/slice_internal.h"
-tsi_result alts_tsi_utils_convert_to_tsi_result(grpc_status_code code) {
- switch (code) {
- case GRPC_STATUS_OK:
- return TSI_OK;
- case GRPC_STATUS_UNKNOWN:
- return TSI_UNKNOWN_ERROR;
- case GRPC_STATUS_INVALID_ARGUMENT:
- return TSI_INVALID_ARGUMENT;
- case GRPC_STATUS_NOT_FOUND:
- return TSI_NOT_FOUND;
- case GRPC_STATUS_INTERNAL:
- return TSI_INTERNAL_ERROR;
- default:
- return TSI_UNKNOWN_ERROR;
- }
-}
-
+tsi_result alts_tsi_utils_convert_to_tsi_result(grpc_status_code code) {
+ switch (code) {
+ case GRPC_STATUS_OK:
+ return TSI_OK;
+ case GRPC_STATUS_UNKNOWN:
+ return TSI_UNKNOWN_ERROR;
+ case GRPC_STATUS_INVALID_ARGUMENT:
+ return TSI_INVALID_ARGUMENT;
+ case GRPC_STATUS_NOT_FOUND:
+ return TSI_NOT_FOUND;
+ case GRPC_STATUS_INTERNAL:
+ return TSI_INTERNAL_ERROR;
+ default:
+ return TSI_UNKNOWN_ERROR;
+ }
+}
+
grpc_gcp_HandshakerResp* alts_tsi_utils_deserialize_response(
grpc_byte_buffer* resp_buffer, upb_arena* arena) {
- GPR_ASSERT(resp_buffer != nullptr);
+ GPR_ASSERT(resp_buffer != 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);
+ 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)),
@@ -55,10 +55,10 @@ grpc_gcp_HandshakerResp* alts_tsi_utils_deserialize_response(
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);
+ grpc_byte_buffer_reader_destroy(&bbr);
if (resp == nullptr) {
- gpr_log(GPR_ERROR, "grpc_gcp_handshaker_resp_decode() failed");
- return nullptr;
- }
- return resp;
-}
+ gpr_log(GPR_ERROR, "grpc_gcp_handshaker_resp_decode() failed");
+ return nullptr;
+ }
+ return resp;
+}
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 a20e5e9cd99..79357c11fce 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
@@ -1,53 +1,53 @@
-/*
- *
- * 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_TSI_ALTS_HANDSHAKER_ALTS_TSI_UTILS_H
-#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_UTILS_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/byte_buffer.h>
-#include <grpc/grpc.h>
-
-#include "src/core/tsi/transport_security_interface.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_TSI_ALTS_HANDSHAKER_ALTS_TSI_UTILS_H
+#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_UTILS_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/byte_buffer.h>
+#include <grpc/grpc.h>
+
+#include "src/core/tsi/transport_security_interface.h"
#include "src/proto/grpc/gcp/handshaker.upb.h"
-
-/**
- * This method converts grpc_status_code code to the corresponding tsi_result
- * code.
- *
- * - code: grpc_status_code code.
- *
- * It returns the converted tsi_result code.
- */
-tsi_result alts_tsi_utils_convert_to_tsi_result(grpc_status_code code);
-
-/**
- * This method deserializes a handshaker response returned from ALTS handshaker
- * service.
- *
- * - bytes_received: data returned from ALTS handshaker service.
+
+/**
+ * This method converts grpc_status_code code to the corresponding tsi_result
+ * code.
+ *
+ * - code: grpc_status_code code.
+ *
+ * It returns the converted tsi_result code.
+ */
+tsi_result alts_tsi_utils_convert_to_tsi_result(grpc_status_code code);
+
+/**
+ * This method deserializes a handshaker response returned from ALTS handshaker
+ * service.
+ *
+ * - bytes_received: data returned from ALTS handshaker service.
* - arena: upb arena.
- *
- * It returns a deserialized handshaker response on success and nullptr on
- * failure.
- */
+ *
+ * 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);
-
-#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_UTILS_H */
+
+#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_UTILS_H */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/altscontext.proto b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/altscontext.proto
index 9a1dad5f56a..ec2f0946911 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/altscontext.proto
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/altscontext.proto
@@ -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.
-
-syntax = "proto3";
-
-import "transport_security_common.proto";
-
-package grpc.gcp;
-
-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;
-}
+// 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.
+
+syntax = "proto3";
+
+import "transport_security_common.proto";
+
+package grpc.gcp;
+
+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;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.options b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.options
index 702ba3802af..912c24783cb 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.options
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.options
@@ -1,2 +1,2 @@
-handshaker.proto no_unions:true
-grpc.gcp.StartServerHandshakeReq.handshake_parameters max_count:3
+handshaker.proto no_unions:true
+grpc.gcp.StartServerHandshakeReq.handshake_parameters max_count:3
diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.proto b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.proto
index 84a4153b703..cc74749c781 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.proto
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/handshaker.proto
@@ -1,224 +1,224 @@
-// 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.
-
-syntax = "proto3";
-
-import "transport_security_common.proto";
-
-package grpc.gcp;
-
-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;
- }
-}
-
-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;
-}
-
-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 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 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) {
- }
-}
+// 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.
+
+syntax = "proto3";
+
+import "transport_security_common.proto";
+
+package grpc.gcp;
+
+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;
+ }
+}
+
+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;
+}
+
+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 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 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/core/tsi/alts/handshaker/proto/transport_security_common.proto b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/transport_security_common.proto
index d0f861e6446..876c48c8238 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/transport_security_common.proto
+++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/proto/transport_security_common.proto
@@ -1,40 +1,40 @@
-// 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.
-
-syntax = "proto3";
-
-package grpc.gcp;
-
-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 gRPC authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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.gcp;
+
+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/core/tsi/alts/handshaker/transport_security_common_api.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/transport_security_common_api.cc
index a0462b2d76c..59c6860e1f2 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
@@ -1,63 +1,63 @@
-/*
- *
- * 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/handshaker/transport_security_common_api.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 "src/core/tsi/alts/handshaker/transport_security_common_api.h"
+
#include "upb/upb.hpp"
-bool grpc_gcp_rpc_protocol_versions_set_max(
- grpc_gcp_rpc_protocol_versions* versions, uint32_t max_major,
- uint32_t max_minor) {
- if (versions == nullptr) {
- gpr_log(GPR_ERROR,
- "versions is nullptr in "
- "grpc_gcp_rpc_protocol_versions_set_max().");
- return false;
- }
- versions->max_rpc_version.major = max_major;
- versions->max_rpc_version.minor = max_minor;
- return true;
-}
-
-bool grpc_gcp_rpc_protocol_versions_set_min(
- grpc_gcp_rpc_protocol_versions* versions, uint32_t min_major,
- uint32_t min_minor) {
- if (versions == nullptr) {
- gpr_log(GPR_ERROR,
- "versions is nullptr in "
- "grpc_gcp_rpc_protocol_versions_set_min().");
- return false;
- }
- versions->min_rpc_version.major = min_major;
- versions->min_rpc_version.minor = min_minor;
- return true;
-}
-
+bool grpc_gcp_rpc_protocol_versions_set_max(
+ grpc_gcp_rpc_protocol_versions* versions, uint32_t max_major,
+ uint32_t max_minor) {
+ if (versions == nullptr) {
+ gpr_log(GPR_ERROR,
+ "versions is nullptr in "
+ "grpc_gcp_rpc_protocol_versions_set_max().");
+ return false;
+ }
+ versions->max_rpc_version.major = max_major;
+ versions->max_rpc_version.minor = max_minor;
+ return true;
+}
+
+bool grpc_gcp_rpc_protocol_versions_set_min(
+ grpc_gcp_rpc_protocol_versions* versions, uint32_t min_major,
+ uint32_t min_minor) {
+ if (versions == nullptr) {
+ gpr_log(GPR_ERROR,
+ "versions is nullptr in "
+ "grpc_gcp_rpc_protocol_versions_set_min().");
+ return false;
+ }
+ versions->min_rpc_version.major = min_major;
+ versions->min_rpc_version.minor = min_minor;
+ return true;
+}
+
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 "
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to "
"grpc_gcp_rpc_protocol_versions_encode().");
return false;
- }
+ }
upb::Arena arena;
grpc_gcp_RpcProtocolVersions* versions_msg =
grpc_gcp_RpcProtocolVersions_new(arena.ptr());
@@ -65,35 +65,35 @@ bool grpc_gcp_rpc_protocol_versions_encode(
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) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to "
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to "
"grpc_gcp_rpc_protocol_versions_encode().");
- return false;
- }
+ return false;
+ }
size_t buf_length;
char* buf =
grpc_gcp_RpcProtocolVersions_serialize(versions, arena, &buf_length);
if (buf == nullptr) {
- return false;
- }
+ return false;
+ }
*slice = grpc_slice_from_copied_buffer(buf, buf_length);
- return true;
-}
-
-bool grpc_gcp_rpc_protocol_versions_decode(
+ return true;
+}
+
+bool grpc_gcp_rpc_protocol_versions_decode(
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;
- }
+ 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(
@@ -101,12 +101,12 @@ bool grpc_gcp_rpc_protocol_versions_decode(
GRPC_SLICE_LENGTH(slice), arena.ptr());
if (versions_msg == nullptr) {
gpr_log(GPR_ERROR, "cannot deserialize RpcProtocolVersions message");
- return false;
- }
+ return false;
+ }
grpc_gcp_rpc_protocol_versions_assign_from_upb(versions, versions_msg);
- return true;
-}
-
+ return true;
+}
+
void grpc_gcp_rpc_protocol_versions_assign_from_upb(
grpc_gcp_rpc_protocol_versions* versions,
const grpc_gcp_RpcProtocolVersions* value) {
@@ -151,75 +151,75 @@ void grpc_gcp_RpcProtocolVersions_assign_from_struct(
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) {
- if ((src == nullptr && dst != nullptr) ||
- (src != nullptr && dst == nullptr)) {
- gpr_log(GPR_ERROR,
- "Invalid arguments to "
- "grpc_gcp_rpc_protocol_versions_copy().");
- return false;
- }
- if (src == nullptr) {
- return true;
- }
- grpc_gcp_rpc_protocol_versions_set_max(dst, src->max_rpc_version.major,
- src->max_rpc_version.minor);
- grpc_gcp_rpc_protocol_versions_set_min(dst, src->min_rpc_version.major,
- src->min_rpc_version.minor);
- return true;
-}
-
-namespace grpc_core {
-namespace internal {
-
-int grpc_gcp_rpc_protocol_version_compare(
- const grpc_gcp_rpc_protocol_versions_version* v1,
- const grpc_gcp_rpc_protocol_versions_version* v2) {
- if ((v1->major > v2->major) ||
- (v1->major == v2->major && v1->minor > v2->minor)) {
- return 1;
- }
- if ((v1->major < v2->major) ||
- (v1->major == v2->major && v1->minor < v2->minor)) {
- return -1;
- }
- return 0;
-}
-
-} // namespace internal
-} // namespace grpc_core
-
-bool grpc_gcp_rpc_protocol_versions_check(
- const grpc_gcp_rpc_protocol_versions* local_versions,
- const grpc_gcp_rpc_protocol_versions* peer_versions,
- grpc_gcp_rpc_protocol_versions_version* highest_common_version) {
- if (local_versions == nullptr || peer_versions == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid arguments to "
- "grpc_gcp_rpc_protocol_versions_check().");
- return false;
- }
- /* max_common_version is MIN(local.max, peer.max) */
- const grpc_gcp_rpc_protocol_versions_version* max_common_version =
- grpc_core::internal::grpc_gcp_rpc_protocol_version_compare(
- &local_versions->max_rpc_version, &peer_versions->max_rpc_version) > 0
- ? &peer_versions->max_rpc_version
- : &local_versions->max_rpc_version;
- /* min_common_version is MAX(local.min, peer.min) */
- const grpc_gcp_rpc_protocol_versions_version* min_common_version =
- grpc_core::internal::grpc_gcp_rpc_protocol_version_compare(
- &local_versions->min_rpc_version, &peer_versions->min_rpc_version) > 0
- ? &local_versions->min_rpc_version
- : &peer_versions->min_rpc_version;
- bool result = grpc_core::internal::grpc_gcp_rpc_protocol_version_compare(
- max_common_version, min_common_version) >= 0
- ? true
- : false;
- if (result && highest_common_version != nullptr) {
- memcpy(highest_common_version, max_common_version,
- sizeof(grpc_gcp_rpc_protocol_versions_version));
- }
- return result;
-}
+bool grpc_gcp_rpc_protocol_versions_copy(
+ const grpc_gcp_rpc_protocol_versions* src,
+ grpc_gcp_rpc_protocol_versions* dst) {
+ if ((src == nullptr && dst != nullptr) ||
+ (src != nullptr && dst == nullptr)) {
+ gpr_log(GPR_ERROR,
+ "Invalid arguments to "
+ "grpc_gcp_rpc_protocol_versions_copy().");
+ return false;
+ }
+ if (src == nullptr) {
+ return true;
+ }
+ grpc_gcp_rpc_protocol_versions_set_max(dst, src->max_rpc_version.major,
+ src->max_rpc_version.minor);
+ grpc_gcp_rpc_protocol_versions_set_min(dst, src->min_rpc_version.major,
+ src->min_rpc_version.minor);
+ return true;
+}
+
+namespace grpc_core {
+namespace internal {
+
+int grpc_gcp_rpc_protocol_version_compare(
+ const grpc_gcp_rpc_protocol_versions_version* v1,
+ const grpc_gcp_rpc_protocol_versions_version* v2) {
+ if ((v1->major > v2->major) ||
+ (v1->major == v2->major && v1->minor > v2->minor)) {
+ return 1;
+ }
+ if ((v1->major < v2->major) ||
+ (v1->major == v2->major && v1->minor < v2->minor)) {
+ return -1;
+ }
+ return 0;
+}
+
+} // namespace internal
+} // namespace grpc_core
+
+bool grpc_gcp_rpc_protocol_versions_check(
+ const grpc_gcp_rpc_protocol_versions* local_versions,
+ const grpc_gcp_rpc_protocol_versions* peer_versions,
+ grpc_gcp_rpc_protocol_versions_version* highest_common_version) {
+ if (local_versions == nullptr || peer_versions == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid arguments to "
+ "grpc_gcp_rpc_protocol_versions_check().");
+ return false;
+ }
+ /* max_common_version is MIN(local.max, peer.max) */
+ const grpc_gcp_rpc_protocol_versions_version* max_common_version =
+ grpc_core::internal::grpc_gcp_rpc_protocol_version_compare(
+ &local_versions->max_rpc_version, &peer_versions->max_rpc_version) > 0
+ ? &peer_versions->max_rpc_version
+ : &local_versions->max_rpc_version;
+ /* min_common_version is MAX(local.min, peer.min) */
+ const grpc_gcp_rpc_protocol_versions_version* min_common_version =
+ grpc_core::internal::grpc_gcp_rpc_protocol_version_compare(
+ &local_versions->min_rpc_version, &peer_versions->min_rpc_version) > 0
+ ? &local_versions->min_rpc_version
+ : &peer_versions->min_rpc_version;
+ bool result = grpc_core::internal::grpc_gcp_rpc_protocol_version_compare(
+ max_common_version, min_common_version) >= 0
+ ? true
+ : false;
+ if (result && highest_common_version != nullptr) {
+ memcpy(highest_common_version, max_common_version,
+ sizeof(grpc_gcp_rpc_protocol_versions_version));
+ }
+ return result;
+}
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 75739e4fe76..01872735d4f 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
@@ -1,113 +1,113 @@
-/*
- *
- * 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_TSI_ALTS_HANDSHAKER_TRANSPORT_SECURITY_COMMON_API_H
-#define GRPC_CORE_TSI_ALTS_HANDSHAKER_TRANSPORT_SECURITY_COMMON_API_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.h>
-#include <grpc/slice_buffer.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.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_TSI_ALTS_HANDSHAKER_TRANSPORT_SECURITY_COMMON_API_H
+#define GRPC_CORE_TSI_ALTS_HANDSHAKER_TRANSPORT_SECURITY_COMMON_API_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice.h>
+#include <grpc/slice_buffer.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.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
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
- * versions.
- *
- * - versions: an rpc protocol version instance.
- * - max_major: a major version of maximum supported RPC version.
- * - max_minor: a minor version of maximum supported RPC version.
- *
- * The method returns true on success and false otherwise.
- */
-bool grpc_gcp_rpc_protocol_versions_set_max(
- grpc_gcp_rpc_protocol_versions* versions, uint32_t max_major,
- uint32_t max_minor);
-
-/**
- * This method sets the value for min_rpc_versions field of rpc protocol
- * versions.
- *
- * - versions: an rpc protocol version instance.
- * - min_major: a major version of minimum supported RPC version.
- * - min_minor: a minor version of minimum supported RPC version.
- *
- * The method returns true on success and false otherwise.
- */
-bool grpc_gcp_rpc_protocol_versions_set_min(
- grpc_gcp_rpc_protocol_versions* versions, uint32_t min_major,
- uint32_t min_minor);
-
-/**
+
+/**
+ * This method sets the value for max_rpc_versions field of rpc protocol
+ * versions.
+ *
+ * - versions: an rpc protocol version instance.
+ * - max_major: a major version of maximum supported RPC version.
+ * - max_minor: a minor version of maximum supported RPC version.
+ *
+ * The method returns true on success and false otherwise.
+ */
+bool grpc_gcp_rpc_protocol_versions_set_max(
+ grpc_gcp_rpc_protocol_versions* versions, uint32_t max_major,
+ uint32_t max_minor);
+
+/**
+ * This method sets the value for min_rpc_versions field of rpc protocol
+ * versions.
+ *
+ * - versions: an rpc protocol version instance.
+ * - min_major: a major version of minimum supported RPC version.
+ * - min_minor: a minor version of minimum supported RPC version.
+ *
+ * The method returns true on success and false otherwise.
+ */
+bool grpc_gcp_rpc_protocol_versions_set_min(
+ grpc_gcp_rpc_protocol_versions* versions, uint32_t min_major,
+ uint32_t min_minor);
+
+/**
* This method serializes an rpc protocol version and returns serialized rpc
* versions in grpc slice.
- *
- * - versions: an rpc protocol versions instance.
+ *
+ * - versions: an rpc protocol versions instance.
* - slice: grpc slice where the serialized result will be written.
- *
- * The method returns true on success and false otherwise.
- */
+ *
+ * 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);
-
-/**
- * This method serializes an rpc protocol version and returns serialized rpc
- * versions in grpc slice.
- *
- * - versions: an rpc protocol versions instance.
+
+/**
+ * This method serializes an rpc protocol version and returns serialized rpc
+ * versions in grpc slice.
+ *
+ * - versions: an rpc protocol versions instance.
* - 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(
+ * - 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);
-
-/**
- * This method de-serializes input in grpc slice form and stores the result
- * in rpc protocol versions.
- *
- * - slice: a data stream containing a serialized rpc protocol version.
- * - versions: an rpc protocol version instance used to hold de-serialized
- * result.
- *
- * The method returns true on success and false otherwise.
- */
-bool grpc_gcp_rpc_protocol_versions_decode(
+
+/**
+ * This method de-serializes input in grpc slice form and stores the result
+ * in rpc protocol versions.
+ *
+ * - slice: a data stream containing a serialized rpc protocol version.
+ * - versions: an rpc protocol version instance used to hold de-serialized
+ * result.
+ *
+ * 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(
@@ -123,49 +123,49 @@ void grpc_gcp_RpcProtocolVersions_assign_from_struct(
const grpc_gcp_rpc_protocol_versions* value);
/**
- * This method performs a deep copy operation on rpc protocol versions
- * instance.
- *
- * - src: rpc protocol versions instance that needs to be copied.
- * - dst: rpc protocol versions instance that stores the copied result.
- *
- * The method returns true on success and false otherwise.
- */
-bool grpc_gcp_rpc_protocol_versions_copy(
- const grpc_gcp_rpc_protocol_versions* src,
- grpc_gcp_rpc_protocol_versions* dst);
-
-/**
- * This method performs a version check between local and peer rpc protocol
- * versions.
- *
- * - local_versions: local rpc protocol versions instance.
- * - peer_versions: peer rpc protocol versions instance.
- * - highest_common_version: an output parameter that will store the highest
- * common rpc protocol version both parties agreed on.
- *
- * The method returns true if the check passes which means both parties agreed
- * on a common rpc protocol to use, and false otherwise.
- */
-bool grpc_gcp_rpc_protocol_versions_check(
- const grpc_gcp_rpc_protocol_versions* local_versions,
- const grpc_gcp_rpc_protocol_versions* peer_versions,
- grpc_gcp_rpc_protocol_versions_version* highest_common_version);
-
-namespace grpc_core {
-namespace internal {
-
-/**
- * Exposed for testing only.
- * The method returns 0 if v1 = v2,
- * returns 1 if v1 > v2,
- * returns -1 if v1 < v2.
- */
-int grpc_gcp_rpc_protocol_version_compare(
- const grpc_gcp_rpc_protocol_versions_version* v1,
- const grpc_gcp_rpc_protocol_versions_version* v2);
-
-} // namespace internal
-} // namespace grpc_core
-
-#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_TRANSPORT_SECURITY_COMMON_API_H */
+ * This method performs a deep copy operation on rpc protocol versions
+ * instance.
+ *
+ * - src: rpc protocol versions instance that needs to be copied.
+ * - dst: rpc protocol versions instance that stores the copied result.
+ *
+ * The method returns true on success and false otherwise.
+ */
+bool grpc_gcp_rpc_protocol_versions_copy(
+ const grpc_gcp_rpc_protocol_versions* src,
+ grpc_gcp_rpc_protocol_versions* dst);
+
+/**
+ * This method performs a version check between local and peer rpc protocol
+ * versions.
+ *
+ * - local_versions: local rpc protocol versions instance.
+ * - peer_versions: peer rpc protocol versions instance.
+ * - highest_common_version: an output parameter that will store the highest
+ * common rpc protocol version both parties agreed on.
+ *
+ * The method returns true if the check passes which means both parties agreed
+ * on a common rpc protocol to use, and false otherwise.
+ */
+bool grpc_gcp_rpc_protocol_versions_check(
+ const grpc_gcp_rpc_protocol_versions* local_versions,
+ const grpc_gcp_rpc_protocol_versions* peer_versions,
+ grpc_gcp_rpc_protocol_versions_version* highest_common_version);
+
+namespace grpc_core {
+namespace internal {
+
+/**
+ * Exposed for testing only.
+ * The method returns 0 if v1 = v2,
+ * returns 1 if v1 > v2,
+ * returns -1 if v1 < v2.
+ */
+int grpc_gcp_rpc_protocol_version_compare(
+ const grpc_gcp_rpc_protocol_versions_version* v1,
+ const grpc_gcp_rpc_protocol_versions_version* v2);
+
+} // namespace internal
+} // namespace grpc_core
+
+#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_TRANSPORT_SECURITY_COMMON_API_H */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h
index 5456d34fad5..cdf4d33890a 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h
@@ -1,54 +1,54 @@
-/*
- *
- * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_INTEGRITY_ONLY_RECORD_PROTOCOL_H
-#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_INTEGRITY_ONLY_RECORD_PROTOCOL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include "src/core/tsi/alts/crypt/gsec.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
-
-/**
- * This method creates an integrity-only alts_grpc_record_protocol instance,
- * given a gsec_aead_crypter instance and a flag indicating if the created
- * instance will be used at the client or server side. The ownership of
- * gsec_aead_crypter instance is transferred to this new object.
- *
- * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption.
- * - overflow_size: overflow size of counter in bytes.
- * - is_client: a flag indicating if the alts_grpc_record_protocol instance will
- * be used at the client or server side.
- * - is_protect: a flag indicating if the alts_grpc_record_protocol instance
- * will be used for protect or unprotect.
+/*
+ *
+ * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_INTEGRITY_ONLY_RECORD_PROTOCOL_H
+#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_INTEGRITY_ONLY_RECORD_PROTOCOL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include "src/core/tsi/alts/crypt/gsec.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
+
+/**
+ * This method creates an integrity-only alts_grpc_record_protocol instance,
+ * given a gsec_aead_crypter instance and a flag indicating if the created
+ * instance will be used at the client or server side. The ownership of
+ * gsec_aead_crypter instance is transferred to this new object.
+ *
+ * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption.
+ * - overflow_size: overflow size of counter in bytes.
+ * - is_client: a flag indicating if the alts_grpc_record_protocol instance will
+ * be used at the client or server side.
+ * - is_protect: a flag indicating if the alts_grpc_record_protocol instance
+ * will be used for protect or unprotect.
*- enable_extra_copy: a flag indicating if the instance uses one-copy instead
* of zero-copy in the protect operation.
- * - rp: an alts_grpc_record_protocol instance to be returned from
- * the method.
- *
- * This method returns TSI_OK in case of success or a specific error code in
- * case of failure.
- */
-tsi_result alts_grpc_integrity_only_record_protocol_create(
- gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
+ * - rp: an alts_grpc_record_protocol instance to be returned from
+ * the method.
+ *
+ * This method returns TSI_OK in case of success or a specific error code in
+ * case of failure.
+ */
+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);
-
-#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_INTEGRITY_ONLY_RECORD_PROTOCOL_H \
- */
+
+#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_INTEGRITY_ONLY_RECORD_PROTOCOL_H \
+ */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h
index 1e34aef2d87..c9fdb320ed2 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.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_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_PRIVACY_INTEGRITY_RECORD_PROTOCOL_H
-#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_PRIVACY_INTEGRITY_RECORD_PROTOCOL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include "src/core/tsi/alts/crypt/gsec.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
-
-/**
- * This method creates a privacy-integrity alts_grpc_record_protocol instance,
- * given a gsec_aead_crypter instance and a flag indicating if the created
- * instance will be used at the client or server side. The ownership of
- * gsec_aead_crypter instance is transferred to this new object.
- *
- * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption.
- * - is_client: a flag indicating if the alts_grpc_record_protocol instance will
- * be used at the client or server side.
- * - rp: an alts_grpc_record_protocol instance to be returned from
- * the method.
- *
- * This method returns TSI_OK in case of success or a specific error code in
- * case of failure.
- */
-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);
-
-#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_PRIVACY_INTEGRITY_RECORD_PROTOCOL_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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_PRIVACY_INTEGRITY_RECORD_PROTOCOL_H
+#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_PRIVACY_INTEGRITY_RECORD_PROTOCOL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include "src/core/tsi/alts/crypt/gsec.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
+
+/**
+ * This method creates a privacy-integrity alts_grpc_record_protocol instance,
+ * given a gsec_aead_crypter instance and a flag indicating if the created
+ * instance will be used at the client or server side. The ownership of
+ * gsec_aead_crypter instance is transferred to this new object.
+ *
+ * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption.
+ * - is_client: a flag indicating if the alts_grpc_record_protocol instance will
+ * be used at the client or server side.
+ * - rp: an alts_grpc_record_protocol instance to be returned from
+ * the method.
+ *
+ * This method returns TSI_OK in case of success or a specific error code in
+ * case of failure.
+ */
+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);
+
+#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_PRIVACY_INTEGRITY_RECORD_PROTOCOL_H \
+ */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h
index d1e433dac47..67eff0e3c3e 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h
@@ -1,91 +1,91 @@
-/*
- *
- * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_H
-#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice_buffer.h>
-
-#include "src/core/tsi/transport_security_interface.h"
-
-/**
- * This alts_grpc_record_protocol object protects and unprotects a single frame
- * stored in grpc slice buffer with zero or minimized memory copy.
- * Implementations of this object must be thread compatible.
- */
-typedef struct alts_grpc_record_protocol alts_grpc_record_protocol;
-
-/**
- * This methods performs protect operation on unprotected data and appends the
- * protected frame to protected_slices. The caller needs to ensure the length
- * of unprotected data plus the frame overhead is less than or equal to the
- * maximum frame length. The input unprotected data slice buffer will be
- * cleared, although the actual unprotected data bytes are not modified.
- *
- * - self: an alts_grpc_record_protocol instance.
- * - unprotected_slices: the unprotected data to be protected.
- * - protected_slices: slice buffer where the protected frame is appended.
- *
- * This method returns TSI_OK in case of success or a specific error code in
- * case of failure.
- */
-tsi_result alts_grpc_record_protocol_protect(
- alts_grpc_record_protocol* self, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices);
-
-/**
- * This methods performs unprotect operation on a full frame of protected data
- * and appends unprotected data to unprotected_slices. It is the caller's
- * responsibility to prepare a full frame of data before calling this method.
- * The input protected frame slice buffer will be cleared, although the actual
- * protected data bytes are not modified.
- *
- * - self: an alts_grpc_record_protocol instance.
- * - protected_slices: a full frame of protected data in grpc slices.
- * - unprotected_slices: slice buffer where unprotected data is appended.
- *
- * This method returns TSI_OK in case of success or a specific error code in
- * case of failure.
- */
-tsi_result alts_grpc_record_protocol_unprotect(
- alts_grpc_record_protocol* self, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices);
-
-/**
- * This method returns maximum allowed unprotected data size, given maximum
- * protected frame size.
- *
- * - self: an alts_grpc_record_protocol instance.
- * - max_protected_frame_size: maximum protected frame size.
- *
- * On success, the method returns the maximum allowed unprotected data size.
- * Otherwise, it returns zero.
- */
-size_t alts_grpc_record_protocol_max_unprotected_data_size(
- const alts_grpc_record_protocol* self, size_t max_protected_frame_size);
-
-/**
- * This method destroys an alts_grpc_record_protocol instance by de-allocating
- * all of its occupied memory.
- */
-void alts_grpc_record_protocol_destroy(alts_grpc_record_protocol* self);
-
-#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_H
+#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice_buffer.h>
+
+#include "src/core/tsi/transport_security_interface.h"
+
+/**
+ * This alts_grpc_record_protocol object protects and unprotects a single frame
+ * stored in grpc slice buffer with zero or minimized memory copy.
+ * Implementations of this object must be thread compatible.
+ */
+typedef struct alts_grpc_record_protocol alts_grpc_record_protocol;
+
+/**
+ * This methods performs protect operation on unprotected data and appends the
+ * protected frame to protected_slices. The caller needs to ensure the length
+ * of unprotected data plus the frame overhead is less than or equal to the
+ * maximum frame length. The input unprotected data slice buffer will be
+ * cleared, although the actual unprotected data bytes are not modified.
+ *
+ * - self: an alts_grpc_record_protocol instance.
+ * - unprotected_slices: the unprotected data to be protected.
+ * - protected_slices: slice buffer where the protected frame is appended.
+ *
+ * This method returns TSI_OK in case of success or a specific error code in
+ * case of failure.
+ */
+tsi_result alts_grpc_record_protocol_protect(
+ alts_grpc_record_protocol* self, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices);
+
+/**
+ * This methods performs unprotect operation on a full frame of protected data
+ * and appends unprotected data to unprotected_slices. It is the caller's
+ * responsibility to prepare a full frame of data before calling this method.
+ * The input protected frame slice buffer will be cleared, although the actual
+ * protected data bytes are not modified.
+ *
+ * - self: an alts_grpc_record_protocol instance.
+ * - protected_slices: a full frame of protected data in grpc slices.
+ * - unprotected_slices: slice buffer where unprotected data is appended.
+ *
+ * This method returns TSI_OK in case of success or a specific error code in
+ * case of failure.
+ */
+tsi_result alts_grpc_record_protocol_unprotect(
+ alts_grpc_record_protocol* self, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices);
+
+/**
+ * This method returns maximum allowed unprotected data size, given maximum
+ * protected frame size.
+ *
+ * - self: an alts_grpc_record_protocol instance.
+ * - max_protected_frame_size: maximum protected frame size.
+ *
+ * On success, the method returns the maximum allowed unprotected data size.
+ * Otherwise, it returns zero.
+ */
+size_t alts_grpc_record_protocol_max_unprotected_data_size(
+ const alts_grpc_record_protocol* self, size_t max_protected_frame_size);
+
+/**
+ * This method destroys an alts_grpc_record_protocol instance by de-allocating
+ * all of its occupied memory.
+ */
+void alts_grpc_record_protocol_destroy(alts_grpc_record_protocol* self);
+
+#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_H \
+ */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc
index 1048b600f0b..4b72305c2d4 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc
@@ -1,174 +1,174 @@
-/*
- *
- * 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_record_protocol_common.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/slice/slice_internal.h"
-
-const size_t kInitialIovecBufferSize = 8;
-
-/* Makes sure iovec_buf in alts_grpc_record_protocol is large enough. */
-static void ensure_iovec_buf_size(alts_grpc_record_protocol* rp,
- const grpc_slice_buffer* sb) {
- GPR_ASSERT(rp != nullptr && sb != nullptr);
- if (sb->count <= rp->iovec_buf_length) {
- return;
- }
- /* At least double the iovec buffer size. */
- rp->iovec_buf_length = GPR_MAX(sb->count, 2 * rp->iovec_buf_length);
- rp->iovec_buf = static_cast<iovec_t*>(
- gpr_realloc(rp->iovec_buf, rp->iovec_buf_length * sizeof(iovec_t)));
-}
-
-/* --- Implementation of methods defined in tsi_grpc_record_protocol_common.h.
- * --- */
-
-void alts_grpc_record_protocol_convert_slice_buffer_to_iovec(
- alts_grpc_record_protocol* rp, const grpc_slice_buffer* sb) {
- GPR_ASSERT(rp != nullptr && sb != nullptr);
- ensure_iovec_buf_size(rp, sb);
- for (size_t i = 0; i < sb->count; i++) {
- rp->iovec_buf[i].iov_base = GRPC_SLICE_START_PTR(sb->slices[i]);
- rp->iovec_buf[i].iov_len = GRPC_SLICE_LENGTH(sb->slices[i]);
- }
-}
-
-void alts_grpc_record_protocol_copy_slice_buffer(const grpc_slice_buffer* src,
- unsigned char* dst) {
- GPR_ASSERT(src != nullptr && dst != nullptr);
- for (size_t i = 0; i < src->count; i++) {
- size_t slice_length = GRPC_SLICE_LENGTH(src->slices[i]);
- memcpy(dst, GRPC_SLICE_START_PTR(src->slices[i]), slice_length);
- dst += slice_length;
- }
-}
-
-iovec_t alts_grpc_record_protocol_get_header_iovec(
- alts_grpc_record_protocol* rp) {
- iovec_t header_iovec = {nullptr, 0};
- if (rp == nullptr) {
- return header_iovec;
- }
- header_iovec.iov_len = rp->header_length;
- if (rp->header_sb.count == 1) {
- header_iovec.iov_base = GRPC_SLICE_START_PTR(rp->header_sb.slices[0]);
- } else {
- /* Frame header is in multiple slices, copies the header bytes from slice
- * buffer to a single flat buffer. */
- alts_grpc_record_protocol_copy_slice_buffer(&rp->header_sb, rp->header_buf);
- header_iovec.iov_base = rp->header_buf;
- }
- return header_iovec;
-}
-
-tsi_result alts_grpc_record_protocol_init(alts_grpc_record_protocol* rp,
- gsec_aead_crypter* crypter,
- size_t overflow_size, bool is_client,
- bool is_integrity_only,
- bool is_protect) {
- if (rp == nullptr || crypter == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to alts_grpc_record_protocol init.");
- return TSI_INVALID_ARGUMENT;
- }
- /* Creates alts_iovec_record_protocol. */
- char* error_details = nullptr;
- grpc_status_code status = alts_iovec_record_protocol_create(
- crypter, overflow_size, is_client, is_integrity_only, is_protect,
- &rp->iovec_rp, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to create alts_iovec_record_protocol, %s.",
- error_details);
- gpr_free(error_details);
- return TSI_INTERNAL_ERROR;
- }
- /* Allocates header slice buffer. */
- grpc_slice_buffer_init(&rp->header_sb);
- /* Allocates header buffer. */
- rp->header_length = alts_iovec_record_protocol_get_header_length();
- rp->header_buf = static_cast<unsigned char*>(gpr_malloc(rp->header_length));
- rp->tag_length = alts_iovec_record_protocol_get_tag_length(rp->iovec_rp);
- /* Allocates iovec buffer. */
- rp->iovec_buf_length = kInitialIovecBufferSize;
- rp->iovec_buf =
- static_cast<iovec_t*>(gpr_malloc(rp->iovec_buf_length * sizeof(iovec_t)));
- return TSI_OK;
-}
-
-/* --- Implementation of methods defined in tsi_grpc_record_protocol.h. --- */
-tsi_result alts_grpc_record_protocol_protect(
- alts_grpc_record_protocol* self, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices) {
- if (grpc_core::ExecCtx::Get() == nullptr || self == nullptr ||
- self->vtable == nullptr || unprotected_slices == nullptr ||
- protected_slices == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->protect == nullptr) {
- return TSI_UNIMPLEMENTED;
- }
- return self->vtable->protect(self, unprotected_slices, protected_slices);
-}
-
-tsi_result alts_grpc_record_protocol_unprotect(
- alts_grpc_record_protocol* self, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices) {
- if (grpc_core::ExecCtx::Get() == nullptr || self == nullptr ||
- self->vtable == nullptr || protected_slices == nullptr ||
- unprotected_slices == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->unprotect == nullptr) {
- return TSI_UNIMPLEMENTED;
- }
- return self->vtable->unprotect(self, protected_slices, unprotected_slices);
-}
-
-void alts_grpc_record_protocol_destroy(alts_grpc_record_protocol* self) {
- if (self == nullptr) {
- return;
- }
- if (self->vtable->destruct != nullptr) {
- self->vtable->destruct(self);
- }
- alts_iovec_record_protocol_destroy(self->iovec_rp);
- grpc_slice_buffer_destroy_internal(&self->header_sb);
- gpr_free(self->header_buf);
- gpr_free(self->iovec_buf);
- gpr_free(self);
-}
-
-/* Integrity-only and privacy-integrity share the same implementation. No need
- * to call vtable. */
-size_t alts_grpc_record_protocol_max_unprotected_data_size(
- const alts_grpc_record_protocol* self, size_t max_protected_frame_size) {
- if (self == nullptr) {
- return 0;
- }
- return alts_iovec_record_protocol_max_unprotected_data_size(
- self->iovec_rp, max_protected_frame_size);
-}
+/*
+ *
+ * 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_record_protocol_common.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/slice/slice_internal.h"
+
+const size_t kInitialIovecBufferSize = 8;
+
+/* Makes sure iovec_buf in alts_grpc_record_protocol is large enough. */
+static void ensure_iovec_buf_size(alts_grpc_record_protocol* rp,
+ const grpc_slice_buffer* sb) {
+ GPR_ASSERT(rp != nullptr && sb != nullptr);
+ if (sb->count <= rp->iovec_buf_length) {
+ return;
+ }
+ /* At least double the iovec buffer size. */
+ rp->iovec_buf_length = GPR_MAX(sb->count, 2 * rp->iovec_buf_length);
+ rp->iovec_buf = static_cast<iovec_t*>(
+ gpr_realloc(rp->iovec_buf, rp->iovec_buf_length * sizeof(iovec_t)));
+}
+
+/* --- Implementation of methods defined in tsi_grpc_record_protocol_common.h.
+ * --- */
+
+void alts_grpc_record_protocol_convert_slice_buffer_to_iovec(
+ alts_grpc_record_protocol* rp, const grpc_slice_buffer* sb) {
+ GPR_ASSERT(rp != nullptr && sb != nullptr);
+ ensure_iovec_buf_size(rp, sb);
+ for (size_t i = 0; i < sb->count; i++) {
+ rp->iovec_buf[i].iov_base = GRPC_SLICE_START_PTR(sb->slices[i]);
+ rp->iovec_buf[i].iov_len = GRPC_SLICE_LENGTH(sb->slices[i]);
+ }
+}
+
+void alts_grpc_record_protocol_copy_slice_buffer(const grpc_slice_buffer* src,
+ unsigned char* dst) {
+ GPR_ASSERT(src != nullptr && dst != nullptr);
+ for (size_t i = 0; i < src->count; i++) {
+ size_t slice_length = GRPC_SLICE_LENGTH(src->slices[i]);
+ memcpy(dst, GRPC_SLICE_START_PTR(src->slices[i]), slice_length);
+ dst += slice_length;
+ }
+}
+
+iovec_t alts_grpc_record_protocol_get_header_iovec(
+ alts_grpc_record_protocol* rp) {
+ iovec_t header_iovec = {nullptr, 0};
+ if (rp == nullptr) {
+ return header_iovec;
+ }
+ header_iovec.iov_len = rp->header_length;
+ if (rp->header_sb.count == 1) {
+ header_iovec.iov_base = GRPC_SLICE_START_PTR(rp->header_sb.slices[0]);
+ } else {
+ /* Frame header is in multiple slices, copies the header bytes from slice
+ * buffer to a single flat buffer. */
+ alts_grpc_record_protocol_copy_slice_buffer(&rp->header_sb, rp->header_buf);
+ header_iovec.iov_base = rp->header_buf;
+ }
+ return header_iovec;
+}
+
+tsi_result alts_grpc_record_protocol_init(alts_grpc_record_protocol* rp,
+ gsec_aead_crypter* crypter,
+ size_t overflow_size, bool is_client,
+ bool is_integrity_only,
+ bool is_protect) {
+ if (rp == nullptr || crypter == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to alts_grpc_record_protocol init.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ /* Creates alts_iovec_record_protocol. */
+ char* error_details = nullptr;
+ grpc_status_code status = alts_iovec_record_protocol_create(
+ crypter, overflow_size, is_client, is_integrity_only, is_protect,
+ &rp->iovec_rp, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to create alts_iovec_record_protocol, %s.",
+ error_details);
+ gpr_free(error_details);
+ return TSI_INTERNAL_ERROR;
+ }
+ /* Allocates header slice buffer. */
+ grpc_slice_buffer_init(&rp->header_sb);
+ /* Allocates header buffer. */
+ rp->header_length = alts_iovec_record_protocol_get_header_length();
+ rp->header_buf = static_cast<unsigned char*>(gpr_malloc(rp->header_length));
+ rp->tag_length = alts_iovec_record_protocol_get_tag_length(rp->iovec_rp);
+ /* Allocates iovec buffer. */
+ rp->iovec_buf_length = kInitialIovecBufferSize;
+ rp->iovec_buf =
+ static_cast<iovec_t*>(gpr_malloc(rp->iovec_buf_length * sizeof(iovec_t)));
+ return TSI_OK;
+}
+
+/* --- Implementation of methods defined in tsi_grpc_record_protocol.h. --- */
+tsi_result alts_grpc_record_protocol_protect(
+ alts_grpc_record_protocol* self, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices) {
+ if (grpc_core::ExecCtx::Get() == nullptr || self == nullptr ||
+ self->vtable == nullptr || unprotected_slices == nullptr ||
+ protected_slices == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->protect == nullptr) {
+ return TSI_UNIMPLEMENTED;
+ }
+ return self->vtable->protect(self, unprotected_slices, protected_slices);
+}
+
+tsi_result alts_grpc_record_protocol_unprotect(
+ alts_grpc_record_protocol* self, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices) {
+ if (grpc_core::ExecCtx::Get() == nullptr || self == nullptr ||
+ self->vtable == nullptr || protected_slices == nullptr ||
+ unprotected_slices == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->unprotect == nullptr) {
+ return TSI_UNIMPLEMENTED;
+ }
+ return self->vtable->unprotect(self, protected_slices, unprotected_slices);
+}
+
+void alts_grpc_record_protocol_destroy(alts_grpc_record_protocol* self) {
+ if (self == nullptr) {
+ return;
+ }
+ if (self->vtable->destruct != nullptr) {
+ self->vtable->destruct(self);
+ }
+ alts_iovec_record_protocol_destroy(self->iovec_rp);
+ grpc_slice_buffer_destroy_internal(&self->header_sb);
+ gpr_free(self->header_buf);
+ gpr_free(self->iovec_buf);
+ gpr_free(self);
+}
+
+/* Integrity-only and privacy-integrity share the same implementation. No need
+ * to call vtable. */
+size_t alts_grpc_record_protocol_max_unprotected_data_size(
+ const alts_grpc_record_protocol* self, size_t max_protected_frame_size) {
+ if (self == nullptr) {
+ return 0;
+ }
+ return alts_iovec_record_protocol_max_unprotected_data_size(
+ self->iovec_rp, max_protected_frame_size);
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h
index 571a915768f..2b9e5886851 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.h
@@ -1,99 +1,99 @@
-/*
- *
- * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_COMMON_H
-#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_COMMON_H
-
-/**
- * this file contains alts_grpc_record_protocol internals and internal-only
- * helper functions. The public functions of alts_grpc_record_protocol are
- * defined in the alts_grpc_record_protocol.h.
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
-
-/* V-table for alts_grpc_record_protocol implementations. */
+/*
+ *
+ * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_COMMON_H
+#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_COMMON_H
+
+/**
+ * this file contains alts_grpc_record_protocol internals and internal-only
+ * helper functions. The public functions of alts_grpc_record_protocol are
+ * defined in the alts_grpc_record_protocol.h.
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
+
+/* V-table for alts_grpc_record_protocol implementations. */
struct alts_grpc_record_protocol_vtable {
- tsi_result (*protect)(alts_grpc_record_protocol* self,
- grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices);
- tsi_result (*unprotect)(alts_grpc_record_protocol* self,
- grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices);
- void (*destruct)(alts_grpc_record_protocol* self);
+ tsi_result (*protect)(alts_grpc_record_protocol* self,
+ grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices);
+ tsi_result (*unprotect)(alts_grpc_record_protocol* self,
+ grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices);
+ void (*destruct)(alts_grpc_record_protocol* self);
};
-/* Main struct for alts_grpc_record_protocol implementation, shared by both
- * integrity-only record protocol and privacy-integrity record protocol.
- * Integrity-only record protocol has additional data elements.
- * Privacy-integrity record protocol uses this struct directly. */
-struct alts_grpc_record_protocol {
- const alts_grpc_record_protocol_vtable* vtable;
- alts_iovec_record_protocol* iovec_rp;
- grpc_slice_buffer header_sb;
- unsigned char* header_buf;
- size_t header_length;
- size_t tag_length;
- iovec_t* iovec_buf;
- size_t iovec_buf_length;
-};
-
-/**
- * Converts the slices of input sb into iovec_t's and puts the result into
- * rp->iovec_buf. Note that the actual data are not copied, only
- * pointers and lengths are copied.
- */
-void alts_grpc_record_protocol_convert_slice_buffer_to_iovec(
- alts_grpc_record_protocol* rp, const grpc_slice_buffer* sb);
-
-/**
- * Copies bytes from slice buffer to destination buffer. Caller is responsible
- * for allocating enough memory of destination buffer. This method is used for
- * copying frame header and tag in case they are stored in multiple slices.
- */
-void alts_grpc_record_protocol_copy_slice_buffer(const grpc_slice_buffer* src,
- unsigned char* dst);
-
-/**
- * This method returns an iovec object pointing to the frame header stored in
- * rp->header_sb. If the frame header is stored in multiple slices,
- * this method will copy the bytes in rp->header_sb to
- * rp->header_buf, and return an iovec object pointing to
- * rp->header_buf.
- */
-iovec_t alts_grpc_record_protocol_get_header_iovec(
- alts_grpc_record_protocol* rp);
-
-/**
- * Initializes an alts_grpc_record_protocol object, given a gsec_aead_crypter
- * instance, the overflow size of the counter in bytes, a flag indicating if the
- * object is used for client or server side, a flag indicating if it is used for
- * integrity-only or privacy-integrity mode, and a flag indicating if it is for
- * protect or unprotect. The ownership of gsec_aead_crypter object is
- * transferred to the alts_grpc_record_protocol object.
- */
-tsi_result alts_grpc_record_protocol_init(alts_grpc_record_protocol* rp,
- gsec_aead_crypter* crypter,
- size_t overflow_size, bool is_client,
- bool is_integrity_only,
- bool is_protect);
-
-#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_COMMON_H \
- */
+/* Main struct for alts_grpc_record_protocol implementation, shared by both
+ * integrity-only record protocol and privacy-integrity record protocol.
+ * Integrity-only record protocol has additional data elements.
+ * Privacy-integrity record protocol uses this struct directly. */
+struct alts_grpc_record_protocol {
+ const alts_grpc_record_protocol_vtable* vtable;
+ alts_iovec_record_protocol* iovec_rp;
+ grpc_slice_buffer header_sb;
+ unsigned char* header_buf;
+ size_t header_length;
+ size_t tag_length;
+ iovec_t* iovec_buf;
+ size_t iovec_buf_length;
+};
+
+/**
+ * Converts the slices of input sb into iovec_t's and puts the result into
+ * rp->iovec_buf. Note that the actual data are not copied, only
+ * pointers and lengths are copied.
+ */
+void alts_grpc_record_protocol_convert_slice_buffer_to_iovec(
+ alts_grpc_record_protocol* rp, const grpc_slice_buffer* sb);
+
+/**
+ * Copies bytes from slice buffer to destination buffer. Caller is responsible
+ * for allocating enough memory of destination buffer. This method is used for
+ * copying frame header and tag in case they are stored in multiple slices.
+ */
+void alts_grpc_record_protocol_copy_slice_buffer(const grpc_slice_buffer* src,
+ unsigned char* dst);
+
+/**
+ * This method returns an iovec object pointing to the frame header stored in
+ * rp->header_sb. If the frame header is stored in multiple slices,
+ * this method will copy the bytes in rp->header_sb to
+ * rp->header_buf, and return an iovec object pointing to
+ * rp->header_buf.
+ */
+iovec_t alts_grpc_record_protocol_get_header_iovec(
+ alts_grpc_record_protocol* rp);
+
+/**
+ * Initializes an alts_grpc_record_protocol object, given a gsec_aead_crypter
+ * instance, the overflow size of the counter in bytes, a flag indicating if the
+ * object is used for client or server side, a flag indicating if it is used for
+ * integrity-only or privacy-integrity mode, and a flag indicating if it is for
+ * protect or unprotect. The ownership of gsec_aead_crypter object is
+ * transferred to the alts_grpc_record_protocol object.
+ */
+tsi_result alts_grpc_record_protocol_init(alts_grpc_record_protocol* rp,
+ gsec_aead_crypter* crypter,
+ size_t overflow_size, bool is_client,
+ bool is_integrity_only,
+ bool is_protect);
+
+#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_RECORD_PROTOCOL_COMMON_H \
+ */
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc
index 6a548e50dd4..f6795abb573 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc
@@ -1,476 +1,476 @@
-/*
- *
- * 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_iovec_record_protocol.h"
-
-#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/tsi/alts/frame_protector/alts_counter.h"
-
-struct alts_iovec_record_protocol {
- alts_counter* ctr;
- gsec_aead_crypter* crypter;
- size_t tag_length;
- bool is_integrity_only;
- bool is_protect;
-};
-
-/* Copies error message to destination. */
-static void maybe_copy_error_msg(const char* src, char** dst) {
- if (dst != nullptr && src != nullptr) {
- *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
- memcpy(*dst, src, strlen(src) + 1);
- }
-}
-
-/* Appends error message to destination. */
-static void maybe_append_error_msg(const char* appendix, char** dst) {
- if (dst != nullptr && appendix != nullptr) {
- int dst_len = static_cast<int>(strlen(*dst));
- *dst = static_cast<char*>(realloc(*dst, dst_len + strlen(appendix) + 1));
- assert(*dst != nullptr);
- memcpy(*dst + dst_len, appendix, strlen(appendix) + 1);
- }
-}
-
-/* Use little endian to interpret a string of bytes as uint32_t. */
-static uint32_t load_32_le(const unsigned char* buffer) {
- return (((uint32_t)buffer[3]) << 24) | (((uint32_t)buffer[2]) << 16) |
- (((uint32_t)buffer[1]) << 8) | ((uint32_t)buffer[0]);
-}
-
-/* Store uint32_t as a string of little endian bytes. */
-static void store_32_le(uint32_t value, unsigned char* buffer) {
- buffer[3] = (unsigned char)(value >> 24) & 0xFF;
- buffer[2] = (unsigned char)(value >> 16) & 0xFF;
- buffer[1] = (unsigned char)(value >> 8) & 0xFF;
- buffer[0] = (unsigned char)(value)&0xFF;
-}
-
-/* Ensures header and tag iovec have sufficient length. */
-static grpc_status_code ensure_header_and_tag_length(
- const alts_iovec_record_protocol* rp, iovec_t header, iovec_t tag,
- char** error_details) {
- if (rp == nullptr) {
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- if (header.iov_base == nullptr) {
- maybe_copy_error_msg("Header is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (header.iov_len != alts_iovec_record_protocol_get_header_length()) {
- maybe_copy_error_msg("Header length is incorrect.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (tag.iov_base == nullptr) {
- maybe_copy_error_msg("Tag is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (tag.iov_len != rp->tag_length) {
- maybe_copy_error_msg("Tag length is incorrect.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- return GRPC_STATUS_OK;
-}
-
-/* Increments crypter counter and checks overflow. */
-static grpc_status_code increment_counter(alts_counter* counter,
- char** error_details) {
- if (counter == nullptr) {
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- bool is_overflow = false;
- grpc_status_code status =
- alts_counter_increment(counter, &is_overflow, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- if (is_overflow) {
- maybe_copy_error_msg("Crypter counter is overflowed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- return GRPC_STATUS_OK;
-}
-
-/* Given an array of iovec, computes the total length of buffer. */
-static size_t get_total_length(const iovec_t* vec, size_t vec_length) {
- size_t total_length = 0;
- for (size_t i = 0; i < vec_length; ++i) {
- total_length += vec[i].iov_len;
- }
- return total_length;
-}
-
-/* Writes frame header given data and tag length. */
-static grpc_status_code write_frame_header(size_t data_length,
- unsigned char* header,
- char** error_details) {
- if (header == nullptr) {
- maybe_copy_error_msg("Header is nullptr.", error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- size_t frame_length = kZeroCopyFrameMessageTypeFieldSize + data_length;
- store_32_le(static_cast<uint32_t>(frame_length), header);
- store_32_le(kZeroCopyFrameMessageType,
- header + kZeroCopyFrameLengthFieldSize);
- return GRPC_STATUS_OK;
-}
-
-/* Verifies frame header given protected data length. */
-static grpc_status_code verify_frame_header(size_t data_length,
- unsigned char* header,
- char** error_details) {
- if (header == nullptr) {
- maybe_copy_error_msg("Header is nullptr.", error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- size_t frame_length = load_32_le(header);
- if (frame_length != kZeroCopyFrameMessageTypeFieldSize + data_length) {
- maybe_copy_error_msg("Bad frame length.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- size_t message_type = load_32_le(header + kZeroCopyFrameLengthFieldSize);
- if (message_type != kZeroCopyFrameMessageType) {
- maybe_copy_error_msg("Unsupported message type.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- return GRPC_STATUS_OK;
-}
-
-/* --- alts_iovec_record_protocol methods implementation. --- */
-
-size_t alts_iovec_record_protocol_get_header_length() {
- return kZeroCopyFrameHeaderSize;
-}
-
-size_t alts_iovec_record_protocol_get_tag_length(
- const alts_iovec_record_protocol* rp) {
- if (rp != nullptr) {
- return rp->tag_length;
- }
- return 0;
-}
-
-size_t alts_iovec_record_protocol_max_unprotected_data_size(
- const alts_iovec_record_protocol* rp, size_t max_protected_frame_size) {
- if (rp == nullptr) {
- return 0;
- }
- size_t overhead_bytes_size =
- kZeroCopyFrameMessageTypeFieldSize + rp->tag_length;
- if (max_protected_frame_size <= overhead_bytes_size) return 0;
- return max_protected_frame_size - overhead_bytes_size;
-}
-
-grpc_status_code alts_iovec_record_protocol_integrity_only_protect(
- alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
- size_t unprotected_vec_length, iovec_t header, iovec_t tag,
- char** error_details) {
- /* Input sanity checks. */
- if (rp == nullptr) {
- maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (!rp->is_integrity_only) {
- maybe_copy_error_msg(
- "Integrity-only operations are not allowed for this object.",
- error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- if (!rp->is_protect) {
- maybe_copy_error_msg("Protect operations are not allowed for this object.",
- error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- grpc_status_code status =
- ensure_header_and_tag_length(rp, header, tag, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Unprotected data should not be zero length. */
- size_t data_length =
- get_total_length(unprotected_vec, unprotected_vec_length);
- /* Sets frame header. */
- status = write_frame_header(data_length + rp->tag_length,
- static_cast<unsigned char*>(header.iov_base),
- error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Computes frame tag by calling AEAD crypter. */
- size_t bytes_written = 0;
- status = gsec_aead_crypter_encrypt_iovec(
- rp->crypter, alts_counter_get_counter(rp->ctr),
- alts_counter_get_size(rp->ctr), unprotected_vec, unprotected_vec_length,
- /* plaintext_vec = */ nullptr, /* plaintext_vec_length = */ 0, tag,
- &bytes_written, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- if (bytes_written != rp->tag_length) {
- maybe_copy_error_msg("Bytes written expects to be the same as tag length.",
- error_details);
- return GRPC_STATUS_INTERNAL;
- }
- /* Increments the crypter counter. */
- return increment_counter(rp->ctr, error_details);
-}
-
-grpc_status_code alts_iovec_record_protocol_integrity_only_unprotect(
- alts_iovec_record_protocol* rp, const iovec_t* protected_vec,
- size_t protected_vec_length, iovec_t header, iovec_t tag,
- char** error_details) {
- /* Input sanity checks. */
- if (rp == nullptr) {
- maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (!rp->is_integrity_only) {
- maybe_copy_error_msg(
- "Integrity-only operations are not allowed for this object.",
- error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- if (rp->is_protect) {
- maybe_copy_error_msg(
- "Unprotect operations are not allowed for this object.", error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- grpc_status_code status =
- ensure_header_and_tag_length(rp, header, tag, error_details);
- if (status != GRPC_STATUS_OK) return status;
- /* Protected data should not be zero length. */
- size_t data_length = get_total_length(protected_vec, protected_vec_length);
- /* Verifies frame header. */
- status = verify_frame_header(data_length + rp->tag_length,
- static_cast<unsigned char*>(header.iov_base),
- error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Verifies frame tag by calling AEAD crypter. */
- iovec_t plaintext = {nullptr, 0};
- size_t bytes_written = 0;
- status = gsec_aead_crypter_decrypt_iovec(
- rp->crypter, alts_counter_get_counter(rp->ctr),
- alts_counter_get_size(rp->ctr), protected_vec, protected_vec_length, &tag,
- 1, plaintext, &bytes_written, error_details);
- if (status != GRPC_STATUS_OK || bytes_written != 0) {
- maybe_append_error_msg(" Frame tag verification failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- /* Increments the crypter counter. */
- return increment_counter(rp->ctr, error_details);
-}
-
-grpc_status_code alts_iovec_record_protocol_privacy_integrity_protect(
- alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
- size_t unprotected_vec_length, iovec_t protected_frame,
- char** error_details) {
- /* Input sanity checks. */
- if (rp == nullptr) {
- maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (rp->is_integrity_only) {
- maybe_copy_error_msg(
- "Privacy-integrity operations are not allowed for this object.",
- error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- if (!rp->is_protect) {
- maybe_copy_error_msg("Protect operations are not allowed for this object.",
- error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- /* Unprotected data should not be zero length. */
- size_t data_length =
- get_total_length(unprotected_vec, unprotected_vec_length);
- /* Ensures protected frame iovec has sufficient size. */
- if (protected_frame.iov_base == nullptr) {
- maybe_copy_error_msg("Protected frame is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (protected_frame.iov_len !=
- alts_iovec_record_protocol_get_header_length() + data_length +
- rp->tag_length) {
- maybe_copy_error_msg("Protected frame size is incorrect.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- /* Writer frame header. */
- grpc_status_code status = write_frame_header(
- data_length + rp->tag_length,
- static_cast<unsigned char*>(protected_frame.iov_base), error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Encrypt unprotected data by calling AEAD crypter. */
- unsigned char* ciphertext_buffer =
- static_cast<unsigned char*>(protected_frame.iov_base) +
- alts_iovec_record_protocol_get_header_length();
- iovec_t ciphertext = {ciphertext_buffer, data_length + rp->tag_length};
- size_t bytes_written = 0;
- status = gsec_aead_crypter_encrypt_iovec(
- rp->crypter, alts_counter_get_counter(rp->ctr),
- alts_counter_get_size(rp->ctr), /* aad_vec = */ nullptr,
- /* aad_vec_length = */ 0, unprotected_vec, unprotected_vec_length,
- ciphertext, &bytes_written, error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- if (bytes_written != data_length + rp->tag_length) {
- maybe_copy_error_msg(
- "Bytes written expects to be data length plus tag length.",
- error_details);
- return GRPC_STATUS_INTERNAL;
- }
- /* Increments the crypter counter. */
- return increment_counter(rp->ctr, error_details);
-}
-
-grpc_status_code alts_iovec_record_protocol_privacy_integrity_unprotect(
- alts_iovec_record_protocol* rp, iovec_t header,
- const iovec_t* protected_vec, size_t protected_vec_length,
- iovec_t unprotected_data, char** error_details) {
- /* Input sanity checks. */
- if (rp == nullptr) {
- maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (rp->is_integrity_only) {
- maybe_copy_error_msg(
- "Privacy-integrity operations are not allowed for this object.",
- error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- if (rp->is_protect) {
- maybe_copy_error_msg(
- "Unprotect operations are not allowed for this object.", error_details);
- return GRPC_STATUS_FAILED_PRECONDITION;
- }
- /* Protected data size should be no less than tag size. */
- size_t protected_data_length =
- get_total_length(protected_vec, protected_vec_length);
- if (protected_data_length < rp->tag_length) {
- maybe_copy_error_msg(
- "Protected data length should be more than the tag length.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- /* Ensures header has sufficient size. */
- if (header.iov_base == nullptr) {
- maybe_copy_error_msg("Header is nullptr.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- if (header.iov_len != alts_iovec_record_protocol_get_header_length()) {
- maybe_copy_error_msg("Header length is incorrect.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- /* Ensures unprotected data iovec has sufficient size. */
- if (unprotected_data.iov_len != protected_data_length - rp->tag_length) {
- maybe_copy_error_msg("Unprotected data size is incorrect.", error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- /* Verify frame header. */
- grpc_status_code status = verify_frame_header(
- protected_data_length, static_cast<unsigned char*>(header.iov_base),
- error_details);
- if (status != GRPC_STATUS_OK) {
- return status;
- }
- /* Decrypt protected data by calling AEAD crypter. */
- size_t bytes_written = 0;
- status = gsec_aead_crypter_decrypt_iovec(
- rp->crypter, alts_counter_get_counter(rp->ctr),
- alts_counter_get_size(rp->ctr), /* aad_vec = */ nullptr,
- /* aad_vec_length = */ 0, protected_vec, protected_vec_length,
- unprotected_data, &bytes_written, error_details);
- if (status != GRPC_STATUS_OK) {
- maybe_append_error_msg(" Frame decryption failed.", error_details);
- return GRPC_STATUS_INTERNAL;
- }
- if (bytes_written != protected_data_length - rp->tag_length) {
- maybe_copy_error_msg(
- "Bytes written expects to be protected data length minus tag length.",
- error_details);
- return GRPC_STATUS_INTERNAL;
- }
- /* Increments the crypter counter. */
- return increment_counter(rp->ctr, error_details);
-}
-
-grpc_status_code alts_iovec_record_protocol_create(
- gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
- bool is_integrity_only, bool is_protect, alts_iovec_record_protocol** rp,
- char** error_details) {
- if (crypter == nullptr || rp == nullptr) {
- maybe_copy_error_msg(
- "Invalid nullptr arguments to alts_iovec_record_protocol create.",
- error_details);
- return GRPC_STATUS_INVALID_ARGUMENT;
- }
- alts_iovec_record_protocol* impl = static_cast<alts_iovec_record_protocol*>(
- gpr_zalloc(sizeof(alts_iovec_record_protocol)));
- /* Gets counter length. */
- size_t counter_length = 0;
- grpc_status_code status =
- gsec_aead_crypter_nonce_length(crypter, &counter_length, error_details);
- if (status != GRPC_STATUS_OK) {
- goto cleanup;
- }
- /* Creates counters. */
- status =
- alts_counter_create(is_protect ? !is_client : is_client, counter_length,
- overflow_size, &impl->ctr, error_details);
- if (status != GRPC_STATUS_OK) {
- goto cleanup;
- }
- /* Gets tag length. */
- status =
- gsec_aead_crypter_tag_length(crypter, &impl->tag_length, error_details);
- if (status != GRPC_STATUS_OK) {
- goto cleanup;
- }
- impl->crypter = crypter;
- impl->is_integrity_only = is_integrity_only;
- impl->is_protect = is_protect;
- *rp = impl;
- return GRPC_STATUS_OK;
-cleanup:
- alts_counter_destroy(impl->ctr);
- gpr_free(impl);
- return GRPC_STATUS_FAILED_PRECONDITION;
-}
-
-void alts_iovec_record_protocol_destroy(alts_iovec_record_protocol* rp) {
- if (rp != nullptr) {
- alts_counter_destroy(rp->ctr);
- gsec_aead_crypter_destroy(rp->crypter);
- gpr_free(rp);
- }
-}
+/*
+ *
+ * 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_iovec_record_protocol.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/tsi/alts/frame_protector/alts_counter.h"
+
+struct alts_iovec_record_protocol {
+ alts_counter* ctr;
+ gsec_aead_crypter* crypter;
+ size_t tag_length;
+ bool is_integrity_only;
+ bool is_protect;
+};
+
+/* Copies error message to destination. */
+static void maybe_copy_error_msg(const char* src, char** dst) {
+ if (dst != nullptr && src != nullptr) {
+ *dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
+ memcpy(*dst, src, strlen(src) + 1);
+ }
+}
+
+/* Appends error message to destination. */
+static void maybe_append_error_msg(const char* appendix, char** dst) {
+ if (dst != nullptr && appendix != nullptr) {
+ int dst_len = static_cast<int>(strlen(*dst));
+ *dst = static_cast<char*>(realloc(*dst, dst_len + strlen(appendix) + 1));
+ assert(*dst != nullptr);
+ memcpy(*dst + dst_len, appendix, strlen(appendix) + 1);
+ }
+}
+
+/* Use little endian to interpret a string of bytes as uint32_t. */
+static uint32_t load_32_le(const unsigned char* buffer) {
+ return (((uint32_t)buffer[3]) << 24) | (((uint32_t)buffer[2]) << 16) |
+ (((uint32_t)buffer[1]) << 8) | ((uint32_t)buffer[0]);
+}
+
+/* Store uint32_t as a string of little endian bytes. */
+static void store_32_le(uint32_t value, unsigned char* buffer) {
+ buffer[3] = (unsigned char)(value >> 24) & 0xFF;
+ buffer[2] = (unsigned char)(value >> 16) & 0xFF;
+ buffer[1] = (unsigned char)(value >> 8) & 0xFF;
+ buffer[0] = (unsigned char)(value)&0xFF;
+}
+
+/* Ensures header and tag iovec have sufficient length. */
+static grpc_status_code ensure_header_and_tag_length(
+ const alts_iovec_record_protocol* rp, iovec_t header, iovec_t tag,
+ char** error_details) {
+ if (rp == nullptr) {
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ if (header.iov_base == nullptr) {
+ maybe_copy_error_msg("Header is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (header.iov_len != alts_iovec_record_protocol_get_header_length()) {
+ maybe_copy_error_msg("Header length is incorrect.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (tag.iov_base == nullptr) {
+ maybe_copy_error_msg("Tag is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (tag.iov_len != rp->tag_length) {
+ maybe_copy_error_msg("Tag length is incorrect.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ return GRPC_STATUS_OK;
+}
+
+/* Increments crypter counter and checks overflow. */
+static grpc_status_code increment_counter(alts_counter* counter,
+ char** error_details) {
+ if (counter == nullptr) {
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ bool is_overflow = false;
+ grpc_status_code status =
+ alts_counter_increment(counter, &is_overflow, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ if (is_overflow) {
+ maybe_copy_error_msg("Crypter counter is overflowed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ return GRPC_STATUS_OK;
+}
+
+/* Given an array of iovec, computes the total length of buffer. */
+static size_t get_total_length(const iovec_t* vec, size_t vec_length) {
+ size_t total_length = 0;
+ for (size_t i = 0; i < vec_length; ++i) {
+ total_length += vec[i].iov_len;
+ }
+ return total_length;
+}
+
+/* Writes frame header given data and tag length. */
+static grpc_status_code write_frame_header(size_t data_length,
+ unsigned char* header,
+ char** error_details) {
+ if (header == nullptr) {
+ maybe_copy_error_msg("Header is nullptr.", error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ size_t frame_length = kZeroCopyFrameMessageTypeFieldSize + data_length;
+ store_32_le(static_cast<uint32_t>(frame_length), header);
+ store_32_le(kZeroCopyFrameMessageType,
+ header + kZeroCopyFrameLengthFieldSize);
+ return GRPC_STATUS_OK;
+}
+
+/* Verifies frame header given protected data length. */
+static grpc_status_code verify_frame_header(size_t data_length,
+ unsigned char* header,
+ char** error_details) {
+ if (header == nullptr) {
+ maybe_copy_error_msg("Header is nullptr.", error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ size_t frame_length = load_32_le(header);
+ if (frame_length != kZeroCopyFrameMessageTypeFieldSize + data_length) {
+ maybe_copy_error_msg("Bad frame length.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ size_t message_type = load_32_le(header + kZeroCopyFrameLengthFieldSize);
+ if (message_type != kZeroCopyFrameMessageType) {
+ maybe_copy_error_msg("Unsupported message type.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ return GRPC_STATUS_OK;
+}
+
+/* --- alts_iovec_record_protocol methods implementation. --- */
+
+size_t alts_iovec_record_protocol_get_header_length() {
+ return kZeroCopyFrameHeaderSize;
+}
+
+size_t alts_iovec_record_protocol_get_tag_length(
+ const alts_iovec_record_protocol* rp) {
+ if (rp != nullptr) {
+ return rp->tag_length;
+ }
+ return 0;
+}
+
+size_t alts_iovec_record_protocol_max_unprotected_data_size(
+ const alts_iovec_record_protocol* rp, size_t max_protected_frame_size) {
+ if (rp == nullptr) {
+ return 0;
+ }
+ size_t overhead_bytes_size =
+ kZeroCopyFrameMessageTypeFieldSize + rp->tag_length;
+ if (max_protected_frame_size <= overhead_bytes_size) return 0;
+ return max_protected_frame_size - overhead_bytes_size;
+}
+
+grpc_status_code alts_iovec_record_protocol_integrity_only_protect(
+ alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
+ size_t unprotected_vec_length, iovec_t header, iovec_t tag,
+ char** error_details) {
+ /* Input sanity checks. */
+ if (rp == nullptr) {
+ maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (!rp->is_integrity_only) {
+ maybe_copy_error_msg(
+ "Integrity-only operations are not allowed for this object.",
+ error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ if (!rp->is_protect) {
+ maybe_copy_error_msg("Protect operations are not allowed for this object.",
+ error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ grpc_status_code status =
+ ensure_header_and_tag_length(rp, header, tag, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Unprotected data should not be zero length. */
+ size_t data_length =
+ get_total_length(unprotected_vec, unprotected_vec_length);
+ /* Sets frame header. */
+ status = write_frame_header(data_length + rp->tag_length,
+ static_cast<unsigned char*>(header.iov_base),
+ error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Computes frame tag by calling AEAD crypter. */
+ size_t bytes_written = 0;
+ status = gsec_aead_crypter_encrypt_iovec(
+ rp->crypter, alts_counter_get_counter(rp->ctr),
+ alts_counter_get_size(rp->ctr), unprotected_vec, unprotected_vec_length,
+ /* plaintext_vec = */ nullptr, /* plaintext_vec_length = */ 0, tag,
+ &bytes_written, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ if (bytes_written != rp->tag_length) {
+ maybe_copy_error_msg("Bytes written expects to be the same as tag length.",
+ error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ /* Increments the crypter counter. */
+ return increment_counter(rp->ctr, error_details);
+}
+
+grpc_status_code alts_iovec_record_protocol_integrity_only_unprotect(
+ alts_iovec_record_protocol* rp, const iovec_t* protected_vec,
+ size_t protected_vec_length, iovec_t header, iovec_t tag,
+ char** error_details) {
+ /* Input sanity checks. */
+ if (rp == nullptr) {
+ maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (!rp->is_integrity_only) {
+ maybe_copy_error_msg(
+ "Integrity-only operations are not allowed for this object.",
+ error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ if (rp->is_protect) {
+ maybe_copy_error_msg(
+ "Unprotect operations are not allowed for this object.", error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ grpc_status_code status =
+ ensure_header_and_tag_length(rp, header, tag, error_details);
+ if (status != GRPC_STATUS_OK) return status;
+ /* Protected data should not be zero length. */
+ size_t data_length = get_total_length(protected_vec, protected_vec_length);
+ /* Verifies frame header. */
+ status = verify_frame_header(data_length + rp->tag_length,
+ static_cast<unsigned char*>(header.iov_base),
+ error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Verifies frame tag by calling AEAD crypter. */
+ iovec_t plaintext = {nullptr, 0};
+ size_t bytes_written = 0;
+ status = gsec_aead_crypter_decrypt_iovec(
+ rp->crypter, alts_counter_get_counter(rp->ctr),
+ alts_counter_get_size(rp->ctr), protected_vec, protected_vec_length, &tag,
+ 1, plaintext, &bytes_written, error_details);
+ if (status != GRPC_STATUS_OK || bytes_written != 0) {
+ maybe_append_error_msg(" Frame tag verification failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ /* Increments the crypter counter. */
+ return increment_counter(rp->ctr, error_details);
+}
+
+grpc_status_code alts_iovec_record_protocol_privacy_integrity_protect(
+ alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
+ size_t unprotected_vec_length, iovec_t protected_frame,
+ char** error_details) {
+ /* Input sanity checks. */
+ if (rp == nullptr) {
+ maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (rp->is_integrity_only) {
+ maybe_copy_error_msg(
+ "Privacy-integrity operations are not allowed for this object.",
+ error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ if (!rp->is_protect) {
+ maybe_copy_error_msg("Protect operations are not allowed for this object.",
+ error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ /* Unprotected data should not be zero length. */
+ size_t data_length =
+ get_total_length(unprotected_vec, unprotected_vec_length);
+ /* Ensures protected frame iovec has sufficient size. */
+ if (protected_frame.iov_base == nullptr) {
+ maybe_copy_error_msg("Protected frame is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (protected_frame.iov_len !=
+ alts_iovec_record_protocol_get_header_length() + data_length +
+ rp->tag_length) {
+ maybe_copy_error_msg("Protected frame size is incorrect.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ /* Writer frame header. */
+ grpc_status_code status = write_frame_header(
+ data_length + rp->tag_length,
+ static_cast<unsigned char*>(protected_frame.iov_base), error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Encrypt unprotected data by calling AEAD crypter. */
+ unsigned char* ciphertext_buffer =
+ static_cast<unsigned char*>(protected_frame.iov_base) +
+ alts_iovec_record_protocol_get_header_length();
+ iovec_t ciphertext = {ciphertext_buffer, data_length + rp->tag_length};
+ size_t bytes_written = 0;
+ status = gsec_aead_crypter_encrypt_iovec(
+ rp->crypter, alts_counter_get_counter(rp->ctr),
+ alts_counter_get_size(rp->ctr), /* aad_vec = */ nullptr,
+ /* aad_vec_length = */ 0, unprotected_vec, unprotected_vec_length,
+ ciphertext, &bytes_written, error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ if (bytes_written != data_length + rp->tag_length) {
+ maybe_copy_error_msg(
+ "Bytes written expects to be data length plus tag length.",
+ error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ /* Increments the crypter counter. */
+ return increment_counter(rp->ctr, error_details);
+}
+
+grpc_status_code alts_iovec_record_protocol_privacy_integrity_unprotect(
+ alts_iovec_record_protocol* rp, iovec_t header,
+ const iovec_t* protected_vec, size_t protected_vec_length,
+ iovec_t unprotected_data, char** error_details) {
+ /* Input sanity checks. */
+ if (rp == nullptr) {
+ maybe_copy_error_msg("Input iovec_record_protocol is nullptr.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (rp->is_integrity_only) {
+ maybe_copy_error_msg(
+ "Privacy-integrity operations are not allowed for this object.",
+ error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ if (rp->is_protect) {
+ maybe_copy_error_msg(
+ "Unprotect operations are not allowed for this object.", error_details);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+ }
+ /* Protected data size should be no less than tag size. */
+ size_t protected_data_length =
+ get_total_length(protected_vec, protected_vec_length);
+ if (protected_data_length < rp->tag_length) {
+ maybe_copy_error_msg(
+ "Protected data length should be more than the tag length.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ /* Ensures header has sufficient size. */
+ if (header.iov_base == nullptr) {
+ maybe_copy_error_msg("Header is nullptr.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ if (header.iov_len != alts_iovec_record_protocol_get_header_length()) {
+ maybe_copy_error_msg("Header length is incorrect.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ /* Ensures unprotected data iovec has sufficient size. */
+ if (unprotected_data.iov_len != protected_data_length - rp->tag_length) {
+ maybe_copy_error_msg("Unprotected data size is incorrect.", error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ /* Verify frame header. */
+ grpc_status_code status = verify_frame_header(
+ protected_data_length, static_cast<unsigned char*>(header.iov_base),
+ error_details);
+ if (status != GRPC_STATUS_OK) {
+ return status;
+ }
+ /* Decrypt protected data by calling AEAD crypter. */
+ size_t bytes_written = 0;
+ status = gsec_aead_crypter_decrypt_iovec(
+ rp->crypter, alts_counter_get_counter(rp->ctr),
+ alts_counter_get_size(rp->ctr), /* aad_vec = */ nullptr,
+ /* aad_vec_length = */ 0, protected_vec, protected_vec_length,
+ unprotected_data, &bytes_written, error_details);
+ if (status != GRPC_STATUS_OK) {
+ maybe_append_error_msg(" Frame decryption failed.", error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ if (bytes_written != protected_data_length - rp->tag_length) {
+ maybe_copy_error_msg(
+ "Bytes written expects to be protected data length minus tag length.",
+ error_details);
+ return GRPC_STATUS_INTERNAL;
+ }
+ /* Increments the crypter counter. */
+ return increment_counter(rp->ctr, error_details);
+}
+
+grpc_status_code alts_iovec_record_protocol_create(
+ gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
+ bool is_integrity_only, bool is_protect, alts_iovec_record_protocol** rp,
+ char** error_details) {
+ if (crypter == nullptr || rp == nullptr) {
+ maybe_copy_error_msg(
+ "Invalid nullptr arguments to alts_iovec_record_protocol create.",
+ error_details);
+ return GRPC_STATUS_INVALID_ARGUMENT;
+ }
+ alts_iovec_record_protocol* impl = static_cast<alts_iovec_record_protocol*>(
+ gpr_zalloc(sizeof(alts_iovec_record_protocol)));
+ /* Gets counter length. */
+ size_t counter_length = 0;
+ grpc_status_code status =
+ gsec_aead_crypter_nonce_length(crypter, &counter_length, error_details);
+ if (status != GRPC_STATUS_OK) {
+ goto cleanup;
+ }
+ /* Creates counters. */
+ status =
+ alts_counter_create(is_protect ? !is_client : is_client, counter_length,
+ overflow_size, &impl->ctr, error_details);
+ if (status != GRPC_STATUS_OK) {
+ goto cleanup;
+ }
+ /* Gets tag length. */
+ status =
+ gsec_aead_crypter_tag_length(crypter, &impl->tag_length, error_details);
+ if (status != GRPC_STATUS_OK) {
+ goto cleanup;
+ }
+ impl->crypter = crypter;
+ impl->is_integrity_only = is_integrity_only;
+ impl->is_protect = is_protect;
+ *rp = impl;
+ return GRPC_STATUS_OK;
+cleanup:
+ alts_counter_destroy(impl->ctr);
+ gpr_free(impl);
+ return GRPC_STATUS_FAILED_PRECONDITION;
+}
+
+void alts_iovec_record_protocol_destroy(alts_iovec_record_protocol* rp) {
+ if (rp != nullptr) {
+ alts_counter_destroy(rp->ctr);
+ gsec_aead_crypter_destroy(rp->crypter);
+ gpr_free(rp);
+ }
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h
index 0b7d1bf5bf3..cdddc4c66b4 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h
@@ -1,199 +1,199 @@
-/*
- *
- * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_IOVEC_RECORD_PROTOCOL_H
-#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_IOVEC_RECORD_PROTOCOL_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include "src/core/tsi/alts/crypt/gsec.h"
-
-constexpr size_t kZeroCopyFrameMessageType = 0x06;
-constexpr size_t kZeroCopyFrameLengthFieldSize = 4;
-constexpr size_t kZeroCopyFrameMessageTypeFieldSize = 4;
-constexpr size_t kZeroCopyFrameHeaderSize =
- kZeroCopyFrameLengthFieldSize + kZeroCopyFrameMessageTypeFieldSize;
-
-// Limit k on number of frames such that at most 2^(8 * k) frames can be sent.
-constexpr size_t kAltsRecordProtocolRekeyFrameLimit = 8;
-constexpr size_t kAltsRecordProtocolFrameLimit = 5;
-
-/* An implementation of alts record protocol. The API is thread-compatible. */
-
-typedef struct iovec iovec_t;
-
-typedef struct alts_iovec_record_protocol alts_iovec_record_protocol;
-
-/**
- * This method gets the length of record protocol frame header.
- */
-size_t alts_iovec_record_protocol_get_header_length();
-
-/**
- * This method gets the length of record protocol frame tag.
- *
- * - rp: an alts_iovec_record_protocol instance.
- *
- * On success, the method returns the length of record protocol frame tag.
- * Otherwise, it returns zero.
- */
-size_t alts_iovec_record_protocol_get_tag_length(
- const alts_iovec_record_protocol* rp);
-
-/**
- * This method returns maximum allowed unprotected data size, given maximum
- * protected frame size.
- *
- * - rp: an alts_iovec_record_protocol instance.
- * - max_protected_frame_size: maximum protected frame size.
- *
- * On success, the method returns the maximum allowed unprotected data size.
- * Otherwise, it returns zero.
- */
-size_t alts_iovec_record_protocol_max_unprotected_data_size(
- const alts_iovec_record_protocol* rp, size_t max_protected_frame_size);
-
-/**
- * This method performs integrity-only protect operation on a
- * alts_iovec_record_protocol instance, i.e., compute frame header and tag. The
- * caller needs to allocate the memory for header and tag prior to calling this
- * method.
- *
- * - rp: an alts_iovec_record_protocol instance.
- * - unprotected_vec: an iovec array containing unprotected data.
- * - unprotected_vec_length: the array length of unprotected_vec.
- * - header: an iovec containing the output frame header.
- * - tag: an iovec containing the output frame tag.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is OK to pass nullptr into error_details.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
- * error status code along with its details specified in error_details (if
- * error_details is not nullptr).
- */
-grpc_status_code alts_iovec_record_protocol_integrity_only_protect(
- alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
- size_t unprotected_vec_length, iovec_t header, iovec_t tag,
- char** error_details);
-
-/**
- * This method performs integrity-only unprotect operation on a
- * alts_iovec_record_protocol instance, i.e., verify frame header and tag.
- *
- * - rp: an alts_iovec_record_protocol instance.
- * - protected_vec: an iovec array containing protected data.
- * - protected_vec_length: the array length of protected_vec.
- * - header: an iovec containing the frame header.
- * - tag: an iovec containing the frame tag.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is OK to pass nullptr into error_details.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
- * error status code along with its details specified in error_details (if
- * error_details is not nullptr).
- */
-grpc_status_code alts_iovec_record_protocol_integrity_only_unprotect(
- alts_iovec_record_protocol* rp, const iovec_t* protected_vec,
- size_t protected_vec_length, iovec_t header, iovec_t tag,
- char** error_details);
-
-/**
- * This method performs privacy-integrity protect operation on a
- * alts_iovec_record_protocol instance, i.e., compute a protected frame. The
- * caller needs to allocate the memory for the protected frame prior to calling
- * this method.
- *
- * - rp: an alts_iovec_record_protocol instance.
- * - unprotected_vec: an iovec array containing unprotected data.
- * - unprotected_vec_length: the array length of unprotected_vec.
- * - protected_frame: an iovec containing the output protected frame.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is OK to pass nullptr into error_details.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
- * error status code along with its details specified in error_details (if
- * error_details is not nullptr).
- */
-grpc_status_code alts_iovec_record_protocol_privacy_integrity_protect(
- alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
- size_t unprotected_vec_length, iovec_t protected_frame,
- char** error_details);
-
-/**
- * This method performs privacy-integrity unprotect operation on a
- * alts_iovec_record_protocol instance given a full protected frame, i.e.,
- * compute the unprotected data. The caller needs to allocated the memory for
- * the unprotected data prior to calling this method.
- *
- * - rp: an alts_iovec_record_protocol instance.
- * - header: an iovec containing the frame header.
- * - protected_vec: an iovec array containing protected data including the tag.
- * - protected_vec_length: the array length of protected_vec.
- * - unprotected_data: an iovec containing the output unprotected data.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is OK to pass nullptr into error_details.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
- * error status code along with its details specified in error_details (if
- * error_details is not nullptr).
- */
-grpc_status_code alts_iovec_record_protocol_privacy_integrity_unprotect(
- alts_iovec_record_protocol* rp, iovec_t header,
- const iovec_t* protected_vec, size_t protected_vec_length,
- iovec_t unprotected_data, char** error_details);
-
-/**
- * This method creates an alts_iovec_record_protocol instance, given a
- * gsec_aead_crypter instance, a flag indicating if the created instance will be
- * used at the client or server side, and a flag indicating if the created
- * instance will be used for integrity-only mode or privacy-integrity mode. The
- * ownership of gsec_aead_crypter instance is transferred to this new object.
- *
- * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption.
- * - overflow_size: overflow size of counter in bytes.
- * - is_client: a flag indicating if the alts_iovec_record_protocol instance
- * will be used at the client or server side.
- * - is_integrity_only: a flag indicating if the alts_iovec_record_protocol
- * instance will be used for integrity-only or privacy-integrity mode.
- * - is_protect: a flag indicating if the alts_grpc_record_protocol instance
- * will be used for protect or unprotect.
- * - rp: an alts_iovec_record_protocol instance to be returned from
- * the method.
- * - error_details: a buffer containing an error message if the method does not
- * function correctly. It is OK to pass nullptr into error_details.
- *
- * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
- * error status code along with its details specified in error_details (if
- * error_details is not nullptr).
- */
-grpc_status_code alts_iovec_record_protocol_create(
- gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
- bool is_integrity_only, bool is_protect, alts_iovec_record_protocol** rp,
- char** error_details);
-
-/**
- * This method destroys an alts_iovec_record_protocol instance by de-allocating
- * all of its occupied memory. A gsec_aead_crypter instance passed in at
- * gsec_alts_crypter instance creation time will be destroyed in this method.
- */
-void alts_iovec_record_protocol_destroy(alts_iovec_record_protocol* rp);
-
-#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_IOVEC_RECORD_PROTOCOL_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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_IOVEC_RECORD_PROTOCOL_H
+#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_IOVEC_RECORD_PROTOCOL_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include "src/core/tsi/alts/crypt/gsec.h"
+
+constexpr size_t kZeroCopyFrameMessageType = 0x06;
+constexpr size_t kZeroCopyFrameLengthFieldSize = 4;
+constexpr size_t kZeroCopyFrameMessageTypeFieldSize = 4;
+constexpr size_t kZeroCopyFrameHeaderSize =
+ kZeroCopyFrameLengthFieldSize + kZeroCopyFrameMessageTypeFieldSize;
+
+// Limit k on number of frames such that at most 2^(8 * k) frames can be sent.
+constexpr size_t kAltsRecordProtocolRekeyFrameLimit = 8;
+constexpr size_t kAltsRecordProtocolFrameLimit = 5;
+
+/* An implementation of alts record protocol. The API is thread-compatible. */
+
+typedef struct iovec iovec_t;
+
+typedef struct alts_iovec_record_protocol alts_iovec_record_protocol;
+
+/**
+ * This method gets the length of record protocol frame header.
+ */
+size_t alts_iovec_record_protocol_get_header_length();
+
+/**
+ * This method gets the length of record protocol frame tag.
+ *
+ * - rp: an alts_iovec_record_protocol instance.
+ *
+ * On success, the method returns the length of record protocol frame tag.
+ * Otherwise, it returns zero.
+ */
+size_t alts_iovec_record_protocol_get_tag_length(
+ const alts_iovec_record_protocol* rp);
+
+/**
+ * This method returns maximum allowed unprotected data size, given maximum
+ * protected frame size.
+ *
+ * - rp: an alts_iovec_record_protocol instance.
+ * - max_protected_frame_size: maximum protected frame size.
+ *
+ * On success, the method returns the maximum allowed unprotected data size.
+ * Otherwise, it returns zero.
+ */
+size_t alts_iovec_record_protocol_max_unprotected_data_size(
+ const alts_iovec_record_protocol* rp, size_t max_protected_frame_size);
+
+/**
+ * This method performs integrity-only protect operation on a
+ * alts_iovec_record_protocol instance, i.e., compute frame header and tag. The
+ * caller needs to allocate the memory for header and tag prior to calling this
+ * method.
+ *
+ * - rp: an alts_iovec_record_protocol instance.
+ * - unprotected_vec: an iovec array containing unprotected data.
+ * - unprotected_vec_length: the array length of unprotected_vec.
+ * - header: an iovec containing the output frame header.
+ * - tag: an iovec containing the output frame tag.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is OK to pass nullptr into error_details.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
+ * error status code along with its details specified in error_details (if
+ * error_details is not nullptr).
+ */
+grpc_status_code alts_iovec_record_protocol_integrity_only_protect(
+ alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
+ size_t unprotected_vec_length, iovec_t header, iovec_t tag,
+ char** error_details);
+
+/**
+ * This method performs integrity-only unprotect operation on a
+ * alts_iovec_record_protocol instance, i.e., verify frame header and tag.
+ *
+ * - rp: an alts_iovec_record_protocol instance.
+ * - protected_vec: an iovec array containing protected data.
+ * - protected_vec_length: the array length of protected_vec.
+ * - header: an iovec containing the frame header.
+ * - tag: an iovec containing the frame tag.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is OK to pass nullptr into error_details.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
+ * error status code along with its details specified in error_details (if
+ * error_details is not nullptr).
+ */
+grpc_status_code alts_iovec_record_protocol_integrity_only_unprotect(
+ alts_iovec_record_protocol* rp, const iovec_t* protected_vec,
+ size_t protected_vec_length, iovec_t header, iovec_t tag,
+ char** error_details);
+
+/**
+ * This method performs privacy-integrity protect operation on a
+ * alts_iovec_record_protocol instance, i.e., compute a protected frame. The
+ * caller needs to allocate the memory for the protected frame prior to calling
+ * this method.
+ *
+ * - rp: an alts_iovec_record_protocol instance.
+ * - unprotected_vec: an iovec array containing unprotected data.
+ * - unprotected_vec_length: the array length of unprotected_vec.
+ * - protected_frame: an iovec containing the output protected frame.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is OK to pass nullptr into error_details.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
+ * error status code along with its details specified in error_details (if
+ * error_details is not nullptr).
+ */
+grpc_status_code alts_iovec_record_protocol_privacy_integrity_protect(
+ alts_iovec_record_protocol* rp, const iovec_t* unprotected_vec,
+ size_t unprotected_vec_length, iovec_t protected_frame,
+ char** error_details);
+
+/**
+ * This method performs privacy-integrity unprotect operation on a
+ * alts_iovec_record_protocol instance given a full protected frame, i.e.,
+ * compute the unprotected data. The caller needs to allocated the memory for
+ * the unprotected data prior to calling this method.
+ *
+ * - rp: an alts_iovec_record_protocol instance.
+ * - header: an iovec containing the frame header.
+ * - protected_vec: an iovec array containing protected data including the tag.
+ * - protected_vec_length: the array length of protected_vec.
+ * - unprotected_data: an iovec containing the output unprotected data.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is OK to pass nullptr into error_details.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
+ * error status code along with its details specified in error_details (if
+ * error_details is not nullptr).
+ */
+grpc_status_code alts_iovec_record_protocol_privacy_integrity_unprotect(
+ alts_iovec_record_protocol* rp, iovec_t header,
+ const iovec_t* protected_vec, size_t protected_vec_length,
+ iovec_t unprotected_data, char** error_details);
+
+/**
+ * This method creates an alts_iovec_record_protocol instance, given a
+ * gsec_aead_crypter instance, a flag indicating if the created instance will be
+ * used at the client or server side, and a flag indicating if the created
+ * instance will be used for integrity-only mode or privacy-integrity mode. The
+ * ownership of gsec_aead_crypter instance is transferred to this new object.
+ *
+ * - crypter: a gsec_aead_crypter instance used to perform AEAD decryption.
+ * - overflow_size: overflow size of counter in bytes.
+ * - is_client: a flag indicating if the alts_iovec_record_protocol instance
+ * will be used at the client or server side.
+ * - is_integrity_only: a flag indicating if the alts_iovec_record_protocol
+ * instance will be used for integrity-only or privacy-integrity mode.
+ * - is_protect: a flag indicating if the alts_grpc_record_protocol instance
+ * will be used for protect or unprotect.
+ * - rp: an alts_iovec_record_protocol instance to be returned from
+ * the method.
+ * - error_details: a buffer containing an error message if the method does not
+ * function correctly. It is OK to pass nullptr into error_details.
+ *
+ * On success, the method returns GRPC_STATUS_OK. Otherwise, it returns an
+ * error status code along with its details specified in error_details (if
+ * error_details is not nullptr).
+ */
+grpc_status_code alts_iovec_record_protocol_create(
+ gsec_aead_crypter* crypter, size_t overflow_size, bool is_client,
+ bool is_integrity_only, bool is_protect, alts_iovec_record_protocol** rp,
+ char** error_details);
+
+/**
+ * This method destroys an alts_iovec_record_protocol instance by de-allocating
+ * all of its occupied memory. A gsec_aead_crypter instance passed in at
+ * gsec_alts_crypter instance creation time will be destroyed in this method.
+ */
+void alts_iovec_record_protocol_destroy(alts_iovec_record_protocol* rp);
+
+#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_IOVEC_RECORD_PROTOCOL_H \
+ */
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 0cdf97465d0..f964d9f1137 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
@@ -1,135 +1,135 @@
-/*
- *
- * 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_zero_copy_grpc_protector.h"
-
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/iomgr/exec_ctx.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/tsi/alts/crypt/gsec.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
-#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
-#include "src/core/tsi/transport_security_grpc.h"
-
-constexpr size_t kMinFrameLength = 1024;
-constexpr size_t kDefaultFrameLength = 16 * 1024;
+/*
+ *
+ * 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_zero_copy_grpc_protector.h"
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/iomgr/exec_ctx.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/tsi/alts/crypt/gsec.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol.h"
+#include "src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.h"
+#include "src/core/tsi/transport_security_grpc.h"
+
+constexpr size_t kMinFrameLength = 1024;
+constexpr size_t kDefaultFrameLength = 16 * 1024;
constexpr size_t kMaxFrameLength = 16 * 1024 * 1024;
-
-/**
- * Main struct for alts_zero_copy_grpc_protector.
- * We choose to have two alts_grpc_record_protocol objects and two sets of slice
- * buffers: one for protect and the other for unprotect, so that protect and
- * unprotect can be executed in parallel. Implementations of this object must be
- * thread compatible.
- */
-typedef struct alts_zero_copy_grpc_protector {
- tsi_zero_copy_grpc_protector base;
- alts_grpc_record_protocol* record_protocol;
- alts_grpc_record_protocol* unrecord_protocol;
- size_t max_protected_frame_size;
- size_t max_unprotected_data_size;
- grpc_slice_buffer unprotected_staging_sb;
- grpc_slice_buffer protected_sb;
- grpc_slice_buffer protected_staging_sb;
- uint32_t parsed_frame_size;
-} alts_zero_copy_grpc_protector;
-
-/**
- * Given a slice buffer, parses the first 4 bytes little-endian unsigned frame
- * size and returns the total frame size including the frame field. Caller
- * needs to make sure the input slice buffer has at least 4 bytes. Returns true
- * on success and false on failure.
- */
-static bool read_frame_size(const grpc_slice_buffer* sb,
- uint32_t* total_frame_size) {
- if (sb == nullptr || sb->length < kZeroCopyFrameLengthFieldSize) {
- return false;
- }
- uint8_t frame_size_buffer[kZeroCopyFrameLengthFieldSize];
- uint8_t* buf = frame_size_buffer;
- /* Copies the first 4 bytes to a temporary buffer. */
- size_t remaining = kZeroCopyFrameLengthFieldSize;
- for (size_t i = 0; i < sb->count; i++) {
- size_t slice_length = GRPC_SLICE_LENGTH(sb->slices[i]);
- if (remaining <= slice_length) {
- memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), remaining);
- remaining = 0;
- break;
- } else {
- memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), slice_length);
- buf += slice_length;
- remaining -= slice_length;
- }
- }
- GPR_ASSERT(remaining == 0);
- /* Gets little-endian frame size. */
- uint32_t frame_size = (((uint32_t)frame_size_buffer[3]) << 24) |
- (((uint32_t)frame_size_buffer[2]) << 16) |
- (((uint32_t)frame_size_buffer[1]) << 8) |
- ((uint32_t)frame_size_buffer[0]);
- if (frame_size > kMaxFrameLength) {
- gpr_log(GPR_ERROR, "Frame size is larger than maximum frame size");
- return false;
- }
- /* Returns frame size including frame length field. */
- *total_frame_size =
- static_cast<uint32_t>(frame_size + kZeroCopyFrameLengthFieldSize);
- return true;
-}
-
-/**
- * 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
+
+/**
+ * Main struct for alts_zero_copy_grpc_protector.
+ * We choose to have two alts_grpc_record_protocol objects and two sets of slice
+ * buffers: one for protect and the other for unprotect, so that protect and
+ * unprotect can be executed in parallel. Implementations of this object must be
+ * thread compatible.
+ */
+typedef struct alts_zero_copy_grpc_protector {
+ tsi_zero_copy_grpc_protector base;
+ alts_grpc_record_protocol* record_protocol;
+ alts_grpc_record_protocol* unrecord_protocol;
+ size_t max_protected_frame_size;
+ size_t max_unprotected_data_size;
+ grpc_slice_buffer unprotected_staging_sb;
+ grpc_slice_buffer protected_sb;
+ grpc_slice_buffer protected_staging_sb;
+ uint32_t parsed_frame_size;
+} alts_zero_copy_grpc_protector;
+
+/**
+ * Given a slice buffer, parses the first 4 bytes little-endian unsigned frame
+ * size and returns the total frame size including the frame field. Caller
+ * needs to make sure the input slice buffer has at least 4 bytes. Returns true
+ * on success and false on failure.
+ */
+static bool read_frame_size(const grpc_slice_buffer* sb,
+ uint32_t* total_frame_size) {
+ if (sb == nullptr || sb->length < kZeroCopyFrameLengthFieldSize) {
+ return false;
+ }
+ uint8_t frame_size_buffer[kZeroCopyFrameLengthFieldSize];
+ uint8_t* buf = frame_size_buffer;
+ /* Copies the first 4 bytes to a temporary buffer. */
+ size_t remaining = kZeroCopyFrameLengthFieldSize;
+ for (size_t i = 0; i < sb->count; i++) {
+ size_t slice_length = GRPC_SLICE_LENGTH(sb->slices[i]);
+ if (remaining <= slice_length) {
+ memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), remaining);
+ remaining = 0;
+ break;
+ } else {
+ memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), slice_length);
+ buf += slice_length;
+ remaining -= slice_length;
+ }
+ }
+ GPR_ASSERT(remaining == 0);
+ /* Gets little-endian frame size. */
+ uint32_t frame_size = (((uint32_t)frame_size_buffer[3]) << 24) |
+ (((uint32_t)frame_size_buffer[2]) << 16) |
+ (((uint32_t)frame_size_buffer[1]) << 8) |
+ ((uint32_t)frame_size_buffer[0]);
+ if (frame_size > kMaxFrameLength) {
+ gpr_log(GPR_ERROR, "Frame size is larger than maximum frame size");
+ return false;
+ }
+ /* Returns frame size including frame length field. */
+ *total_frame_size =
+ static_cast<uint32_t>(frame_size + kZeroCopyFrameLengthFieldSize);
+ return true;
+}
+
+/**
+ * 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
- * for protect or unprotect.
- */
-static tsi_result create_alts_grpc_record_protocol(
- const uint8_t* key, size_t key_size, bool is_rekey, bool is_client,
+ * for protect or unprotect.
+ */
+static tsi_result create_alts_grpc_record_protocol(
+ const uint8_t* key, size_t key_size, bool is_rekey, bool is_client,
bool is_integrity_only, bool is_protect, bool enable_extra_copy,
- alts_grpc_record_protocol** record_protocol) {
- if (key == nullptr || record_protocol == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- grpc_status_code status;
- gsec_aead_crypter* crypter = nullptr;
- char* error_details = nullptr;
- status = gsec_aes_gcm_aead_crypter_create(key, key_size, kAesGcmNonceLength,
- kAesGcmTagLength, is_rekey,
- &crypter, &error_details);
- if (status != GRPC_STATUS_OK) {
- gpr_log(GPR_ERROR, "Failed to create AEAD crypter, %s", error_details);
- gpr_free(error_details);
- return TSI_INTERNAL_ERROR;
- }
- size_t overflow_limit = is_rekey ? kAltsRecordProtocolRekeyFrameLimit
- : kAltsRecordProtocolFrameLimit;
- /* Creates alts_grpc_record_protocol with AEAD crypter ownership transferred.
- */
+ alts_grpc_record_protocol** record_protocol) {
+ if (key == nullptr || record_protocol == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ grpc_status_code status;
+ gsec_aead_crypter* crypter = nullptr;
+ char* error_details = nullptr;
+ status = gsec_aes_gcm_aead_crypter_create(key, key_size, kAesGcmNonceLength,
+ kAesGcmTagLength, is_rekey,
+ &crypter, &error_details);
+ if (status != GRPC_STATUS_OK) {
+ gpr_log(GPR_ERROR, "Failed to create AEAD crypter, %s", error_details);
+ gpr_free(error_details);
+ return TSI_INTERNAL_ERROR;
+ }
+ size_t overflow_limit = is_rekey ? kAltsRecordProtocolRekeyFrameLimit
+ : kAltsRecordProtocolFrameLimit;
+ /* Creates alts_grpc_record_protocol with AEAD crypter ownership transferred.
+ */
tsi_result result = is_integrity_only
? alts_grpc_integrity_only_record_protocol_create(
crypter, overflow_limit, is_client, is_protect,
@@ -137,102 +137,102 @@ static tsi_result create_alts_grpc_record_protocol(
: alts_grpc_privacy_integrity_record_protocol_create(
crypter, overflow_limit, is_client, is_protect,
record_protocol);
- if (result != TSI_OK) {
- gsec_aead_crypter_destroy(crypter);
- return result;
- }
- return TSI_OK;
-}
-
-/* --- tsi_zero_copy_grpc_protector methods implementation. --- */
-
-static tsi_result alts_zero_copy_grpc_protector_protect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices) {
- if (self == nullptr || unprotected_slices == nullptr ||
- protected_slices == nullptr) {
- gpr_log(GPR_ERROR, "Invalid nullptr arguments to zero-copy grpc protect.");
- return TSI_INVALID_ARGUMENT;
- }
- alts_zero_copy_grpc_protector* protector =
- reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
- /* Calls alts_grpc_record_protocol protect repeatly. */
- while (unprotected_slices->length > protector->max_unprotected_data_size) {
- grpc_slice_buffer_move_first(unprotected_slices,
- protector->max_unprotected_data_size,
- &protector->unprotected_staging_sb);
- tsi_result status = alts_grpc_record_protocol_protect(
- protector->record_protocol, &protector->unprotected_staging_sb,
- protected_slices);
- if (status != TSI_OK) {
- return status;
- }
- }
- return alts_grpc_record_protocol_protect(
- protector->record_protocol, unprotected_slices, protected_slices);
-}
-
-static tsi_result alts_zero_copy_grpc_protector_unprotect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices) {
- if (self == nullptr || unprotected_slices == nullptr ||
- protected_slices == nullptr) {
- gpr_log(GPR_ERROR,
- "Invalid nullptr arguments to zero-copy grpc unprotect.");
- return TSI_INVALID_ARGUMENT;
- }
- alts_zero_copy_grpc_protector* protector =
- reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
- grpc_slice_buffer_move_into(protected_slices, &protector->protected_sb);
- /* Keep unprotecting each frame if possible. */
- while (protector->protected_sb.length >= kZeroCopyFrameLengthFieldSize) {
- if (protector->parsed_frame_size == 0) {
- /* We have not parsed frame size yet. Parses frame size. */
- if (!read_frame_size(&protector->protected_sb,
- &protector->parsed_frame_size)) {
- grpc_slice_buffer_reset_and_unref_internal(&protector->protected_sb);
- return TSI_DATA_CORRUPTED;
- }
- }
- if (protector->protected_sb.length < protector->parsed_frame_size) break;
- /* At this point, protected_sb contains at least one frame of data. */
- tsi_result status;
- if (protector->protected_sb.length == protector->parsed_frame_size) {
- status = alts_grpc_record_protocol_unprotect(protector->unrecord_protocol,
- &protector->protected_sb,
- unprotected_slices);
- } else {
- grpc_slice_buffer_move_first(&protector->protected_sb,
- protector->parsed_frame_size,
- &protector->protected_staging_sb);
- status = alts_grpc_record_protocol_unprotect(
- protector->unrecord_protocol, &protector->protected_staging_sb,
- unprotected_slices);
- }
- protector->parsed_frame_size = 0;
- if (status != TSI_OK) {
- grpc_slice_buffer_reset_and_unref_internal(&protector->protected_sb);
- return status;
- }
- }
- return TSI_OK;
-}
-
-static void alts_zero_copy_grpc_protector_destroy(
- tsi_zero_copy_grpc_protector* self) {
- if (self == nullptr) {
- return;
- }
- alts_zero_copy_grpc_protector* protector =
- reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
- alts_grpc_record_protocol_destroy(protector->record_protocol);
- alts_grpc_record_protocol_destroy(protector->unrecord_protocol);
- grpc_slice_buffer_destroy_internal(&protector->unprotected_staging_sb);
- grpc_slice_buffer_destroy_internal(&protector->protected_sb);
- grpc_slice_buffer_destroy_internal(&protector->protected_staging_sb);
- gpr_free(protector);
-}
-
+ if (result != TSI_OK) {
+ gsec_aead_crypter_destroy(crypter);
+ return result;
+ }
+ return TSI_OK;
+}
+
+/* --- tsi_zero_copy_grpc_protector methods implementation. --- */
+
+static tsi_result alts_zero_copy_grpc_protector_protect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices) {
+ if (self == nullptr || unprotected_slices == nullptr ||
+ protected_slices == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid nullptr arguments to zero-copy grpc protect.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_zero_copy_grpc_protector* protector =
+ reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
+ /* Calls alts_grpc_record_protocol protect repeatly. */
+ while (unprotected_slices->length > protector->max_unprotected_data_size) {
+ grpc_slice_buffer_move_first(unprotected_slices,
+ protector->max_unprotected_data_size,
+ &protector->unprotected_staging_sb);
+ tsi_result status = alts_grpc_record_protocol_protect(
+ protector->record_protocol, &protector->unprotected_staging_sb,
+ protected_slices);
+ if (status != TSI_OK) {
+ return status;
+ }
+ }
+ return alts_grpc_record_protocol_protect(
+ protector->record_protocol, unprotected_slices, protected_slices);
+}
+
+static tsi_result alts_zero_copy_grpc_protector_unprotect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices) {
+ if (self == nullptr || unprotected_slices == nullptr ||
+ protected_slices == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Invalid nullptr arguments to zero-copy grpc unprotect.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ alts_zero_copy_grpc_protector* protector =
+ reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
+ grpc_slice_buffer_move_into(protected_slices, &protector->protected_sb);
+ /* Keep unprotecting each frame if possible. */
+ while (protector->protected_sb.length >= kZeroCopyFrameLengthFieldSize) {
+ if (protector->parsed_frame_size == 0) {
+ /* We have not parsed frame size yet. Parses frame size. */
+ if (!read_frame_size(&protector->protected_sb,
+ &protector->parsed_frame_size)) {
+ grpc_slice_buffer_reset_and_unref_internal(&protector->protected_sb);
+ return TSI_DATA_CORRUPTED;
+ }
+ }
+ if (protector->protected_sb.length < protector->parsed_frame_size) break;
+ /* At this point, protected_sb contains at least one frame of data. */
+ tsi_result status;
+ if (protector->protected_sb.length == protector->parsed_frame_size) {
+ status = alts_grpc_record_protocol_unprotect(protector->unrecord_protocol,
+ &protector->protected_sb,
+ unprotected_slices);
+ } else {
+ grpc_slice_buffer_move_first(&protector->protected_sb,
+ protector->parsed_frame_size,
+ &protector->protected_staging_sb);
+ status = alts_grpc_record_protocol_unprotect(
+ protector->unrecord_protocol, &protector->protected_staging_sb,
+ unprotected_slices);
+ }
+ protector->parsed_frame_size = 0;
+ if (status != TSI_OK) {
+ grpc_slice_buffer_reset_and_unref_internal(&protector->protected_sb);
+ return status;
+ }
+ }
+ return TSI_OK;
+}
+
+static void alts_zero_copy_grpc_protector_destroy(
+ tsi_zero_copy_grpc_protector* self) {
+ if (self == nullptr) {
+ return;
+ }
+ alts_zero_copy_grpc_protector* protector =
+ reinterpret_cast<alts_zero_copy_grpc_protector*>(self);
+ alts_grpc_record_protocol_destroy(protector->record_protocol);
+ alts_grpc_record_protocol_destroy(protector->unrecord_protocol);
+ grpc_slice_buffer_destroy_internal(&protector->unprotected_staging_sb);
+ grpc_slice_buffer_destroy_internal(&protector->protected_sb);
+ grpc_slice_buffer_destroy_internal(&protector->protected_staging_sb);
+ gpr_free(protector);
+}
+
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;
@@ -242,66 +242,66 @@ static tsi_result alts_zero_copy_grpc_protector_max_frame_size(
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,
+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};
-
-tsi_result alts_zero_copy_grpc_protector_create(
- const uint8_t* key, size_t key_size, bool is_rekey, bool is_client,
+
+tsi_result alts_zero_copy_grpc_protector_create(
+ const uint8_t* key, size_t key_size, bool is_rekey, bool is_client,
bool is_integrity_only, bool enable_extra_copy,
size_t* max_protected_frame_size,
- tsi_zero_copy_grpc_protector** protector) {
- if (grpc_core::ExecCtx::Get() == nullptr || key == nullptr ||
- protector == nullptr) {
- gpr_log(
- GPR_ERROR,
- "Invalid nullptr arguments to alts_zero_copy_grpc_protector create.");
- return TSI_INVALID_ARGUMENT;
- }
- /* Creates alts_zero_copy_protector. */
- alts_zero_copy_grpc_protector* impl =
- static_cast<alts_zero_copy_grpc_protector*>(
- gpr_zalloc(sizeof(alts_zero_copy_grpc_protector)));
- /* Creates alts_grpc_record_protocol objects. */
- tsi_result status = create_alts_grpc_record_protocol(
- key, key_size, is_rekey, is_client, is_integrity_only,
+ tsi_zero_copy_grpc_protector** protector) {
+ if (grpc_core::ExecCtx::Get() == nullptr || key == nullptr ||
+ protector == nullptr) {
+ gpr_log(
+ GPR_ERROR,
+ "Invalid nullptr arguments to alts_zero_copy_grpc_protector create.");
+ return TSI_INVALID_ARGUMENT;
+ }
+ /* Creates alts_zero_copy_protector. */
+ alts_zero_copy_grpc_protector* impl =
+ static_cast<alts_zero_copy_grpc_protector*>(
+ gpr_zalloc(sizeof(alts_zero_copy_grpc_protector)));
+ /* Creates alts_grpc_record_protocol objects. */
+ tsi_result status = create_alts_grpc_record_protocol(
+ key, key_size, is_rekey, is_client, is_integrity_only,
/*is_protect=*/true, enable_extra_copy, &impl->record_protocol);
- if (status == TSI_OK) {
- status = create_alts_grpc_record_protocol(
- key, key_size, is_rekey, is_client, is_integrity_only,
+ if (status == TSI_OK) {
+ status = create_alts_grpc_record_protocol(
+ key, key_size, is_rekey, is_client, is_integrity_only,
/*is_protect=*/false, enable_extra_copy, &impl->unrecord_protocol);
- if (status == TSI_OK) {
- /* Sets maximum frame size. */
- size_t max_protected_frame_size_to_set = kDefaultFrameLength;
- if (max_protected_frame_size != nullptr) {
- *max_protected_frame_size =
- GPR_MIN(*max_protected_frame_size, kMaxFrameLength);
- *max_protected_frame_size =
- GPR_MAX(*max_protected_frame_size, kMinFrameLength);
- max_protected_frame_size_to_set = *max_protected_frame_size;
- }
- impl->max_protected_frame_size = max_protected_frame_size_to_set;
- impl->max_unprotected_data_size =
- alts_grpc_record_protocol_max_unprotected_data_size(
- impl->record_protocol, max_protected_frame_size_to_set);
- GPR_ASSERT(impl->max_unprotected_data_size > 0);
- /* Allocates internal slice buffers. */
- grpc_slice_buffer_init(&impl->unprotected_staging_sb);
- grpc_slice_buffer_init(&impl->protected_sb);
- grpc_slice_buffer_init(&impl->protected_staging_sb);
- impl->parsed_frame_size = 0;
- impl->base.vtable = &alts_zero_copy_grpc_protector_vtable;
- *protector = &impl->base;
- return TSI_OK;
- }
- }
-
- /* Cleanup if create failed. */
- alts_grpc_record_protocol_destroy(impl->record_protocol);
- alts_grpc_record_protocol_destroy(impl->unrecord_protocol);
- gpr_free(impl);
- return TSI_INTERNAL_ERROR;
-}
+ if (status == TSI_OK) {
+ /* Sets maximum frame size. */
+ size_t max_protected_frame_size_to_set = kDefaultFrameLength;
+ if (max_protected_frame_size != nullptr) {
+ *max_protected_frame_size =
+ GPR_MIN(*max_protected_frame_size, kMaxFrameLength);
+ *max_protected_frame_size =
+ GPR_MAX(*max_protected_frame_size, kMinFrameLength);
+ max_protected_frame_size_to_set = *max_protected_frame_size;
+ }
+ impl->max_protected_frame_size = max_protected_frame_size_to_set;
+ impl->max_unprotected_data_size =
+ alts_grpc_record_protocol_max_unprotected_data_size(
+ impl->record_protocol, max_protected_frame_size_to_set);
+ GPR_ASSERT(impl->max_unprotected_data_size > 0);
+ /* Allocates internal slice buffers. */
+ grpc_slice_buffer_init(&impl->unprotected_staging_sb);
+ grpc_slice_buffer_init(&impl->protected_sb);
+ grpc_slice_buffer_init(&impl->protected_staging_sb);
+ impl->parsed_frame_size = 0;
+ impl->base.vtable = &alts_zero_copy_grpc_protector_vtable;
+ *protector = &impl->base;
+ return TSI_OK;
+ }
+ }
+
+ /* Cleanup if create failed. */
+ alts_grpc_record_protocol_destroy(impl->record_protocol);
+ alts_grpc_record_protocol_destroy(impl->unrecord_protocol);
+ gpr_free(impl);
+ return TSI_INTERNAL_ERROR;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h
index 515c27ea052..3ce3c1b273a 100644
--- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h
+++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h
@@ -1,57 +1,57 @@
-/*
- *
- * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_ZERO_COPY_GRPC_PROTECTOR_H
-#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_ZERO_COPY_GRPC_PROTECTOR_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include "src/core/tsi/transport_security_grpc.h"
-
-/**
- * This method creates an ALTS zero-copy grpc protector.
- *
- * - key: a symmetric key used to seal/unseal frames.
- * - key_size: the size of symmetric key.
- * - is_rekey: use rekeying AEAD crypter.
- * - is_client: a flag indicating if the protector will be used at client or
- * server side.
- * - is_integrity_only: a flag indicating if the protector instance will be
- * used for integrity-only or privacy-integrity mode.
+/*
+ *
+ * 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_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_ZERO_COPY_GRPC_PROTECTOR_H
+#define GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_ZERO_COPY_GRPC_PROTECTOR_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include "src/core/tsi/transport_security_grpc.h"
+
+/**
+ * This method creates an ALTS zero-copy grpc protector.
+ *
+ * - key: a symmetric key used to seal/unseal frames.
+ * - key_size: the size of symmetric key.
+ * - is_rekey: use rekeying AEAD crypter.
+ * - is_client: a flag indicating if the protector will be used at client or
+ * server side.
+ * - is_integrity_only: a flag indicating if the protector instance will be
+ * used for integrity-only or privacy-integrity mode.
* - enable_extra_copy: a flag indicating if the protector instance does one
* extra memory copy during the protect operation for integrity_only mode.
* For the unprotect operation, it is still zero-copy. If application intends
* to modify the data buffer after the protect operation, we can turn on this
* mode to avoid integrity check failure.
- * - max_protected_frame_size: an in/out parameter indicating max frame size
- * to be used by the protector. If it is nullptr, the default frame size will
- * be used. Otherwise, the provided frame size will be adjusted (if not
- * falling into a valid frame range) and used.
- * - protector: a pointer to the zero-copy protector returned from the method.
- *
- * This method returns TSI_OK on success or a specific error code otherwise.
- */
-tsi_result alts_zero_copy_grpc_protector_create(
- const uint8_t* key, size_t key_size, bool is_rekey, bool is_client,
+ * - max_protected_frame_size: an in/out parameter indicating max frame size
+ * to be used by the protector. If it is nullptr, the default frame size will
+ * be used. Otherwise, the provided frame size will be adjusted (if not
+ * falling into a valid frame range) and used.
+ * - protector: a pointer to the zero-copy protector returned from the method.
+ *
+ * This method returns TSI_OK on success or a specific error code otherwise.
+ */
+tsi_result alts_zero_copy_grpc_protector_create(
+ const uint8_t* key, size_t key_size, bool is_rekey, bool is_client,
bool is_integrity_only, bool enable_extra_copy,
size_t* max_protected_frame_size, tsi_zero_copy_grpc_protector** protector);
-
-#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_ZERO_COPY_GRPC_PROTECTOR_H \
- */
+
+#endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_ZERO_COPY_GRPC_PROTECTOR_H \
+ */
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 1b6b8ca07b4..bfd54a01efb 100644
--- a/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc
+++ b/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc
@@ -1,789 +1,789 @@
-/*
- *
- * 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/tsi/fake_transport_security.h"
-
-#include <stdlib.h>
-#include <string.h>
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/slice/slice_internal.h"
-#include "src/core/tsi/transport_security_grpc.h"
-
-/* --- Constants. ---*/
-#define TSI_FAKE_FRAME_HEADER_SIZE 4
-#define TSI_FAKE_FRAME_INITIAL_ALLOCATED_SIZE 64
-#define TSI_FAKE_DEFAULT_FRAME_SIZE 16384
-#define TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 256
-
-/* --- Structure definitions. ---*/
-
-/* a frame is encoded like this:
- | size | data |
- where the size field value is the size of the size field plus the size of
- the data encoded in little endian on 4 bytes. */
+/*
+ *
+ * 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/tsi/fake_transport_security.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/slice/slice_internal.h"
+#include "src/core/tsi/transport_security_grpc.h"
+
+/* --- Constants. ---*/
+#define TSI_FAKE_FRAME_HEADER_SIZE 4
+#define TSI_FAKE_FRAME_INITIAL_ALLOCATED_SIZE 64
+#define TSI_FAKE_DEFAULT_FRAME_SIZE 16384
+#define TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 256
+
+/* --- Structure definitions. ---*/
+
+/* a frame is encoded like this:
+ | size | data |
+ where the size field value is the size of the size field plus the size of
+ the data encoded in little endian on 4 bytes. */
struct tsi_fake_frame {
- unsigned char* data;
- size_t size;
- size_t allocated_size;
- size_t offset;
- int needs_draining;
+ unsigned char* data;
+ size_t size;
+ size_t allocated_size;
+ size_t offset;
+ int needs_draining;
};
-typedef enum {
- TSI_FAKE_CLIENT_INIT = 0,
- TSI_FAKE_SERVER_INIT = 1,
- TSI_FAKE_CLIENT_FINISHED = 2,
- TSI_FAKE_SERVER_FINISHED = 3,
- TSI_FAKE_HANDSHAKE_MESSAGE_MAX = 4
-} tsi_fake_handshake_message;
-
+typedef enum {
+ TSI_FAKE_CLIENT_INIT = 0,
+ TSI_FAKE_SERVER_INIT = 1,
+ TSI_FAKE_CLIENT_FINISHED = 2,
+ TSI_FAKE_SERVER_FINISHED = 3,
+ TSI_FAKE_HANDSHAKE_MESSAGE_MAX = 4
+} tsi_fake_handshake_message;
+
struct tsi_fake_handshaker {
- tsi_handshaker base;
- int is_client;
- tsi_fake_handshake_message next_message_to_send;
- int needs_incoming_message;
- tsi_fake_frame incoming_frame;
- tsi_fake_frame outgoing_frame;
- unsigned char* outgoing_bytes_buffer;
- size_t outgoing_bytes_buffer_size;
- tsi_result result;
+ tsi_handshaker base;
+ int is_client;
+ tsi_fake_handshake_message next_message_to_send;
+ int needs_incoming_message;
+ tsi_fake_frame incoming_frame;
+ tsi_fake_frame outgoing_frame;
+ unsigned char* outgoing_bytes_buffer;
+ size_t outgoing_bytes_buffer_size;
+ tsi_result result;
};
struct tsi_fake_frame_protector {
- tsi_frame_protector base;
- tsi_fake_frame protect_frame;
- tsi_fake_frame unprotect_frame;
- size_t max_frame_size;
+ tsi_frame_protector base;
+ tsi_fake_frame protect_frame;
+ tsi_fake_frame unprotect_frame;
+ size_t max_frame_size;
};
struct tsi_fake_zero_copy_grpc_protector {
- tsi_zero_copy_grpc_protector base;
- grpc_slice_buffer header_sb;
- grpc_slice_buffer protected_sb;
- size_t max_frame_size;
- size_t parsed_frame_size;
+ tsi_zero_copy_grpc_protector base;
+ grpc_slice_buffer header_sb;
+ grpc_slice_buffer protected_sb;
+ size_t max_frame_size;
+ size_t parsed_frame_size;
};
-/* --- Utils. ---*/
-
-static const char* tsi_fake_handshake_message_strings[] = {
- "CLIENT_INIT", "SERVER_INIT", "CLIENT_FINISHED", "SERVER_FINISHED"};
-
-static const char* tsi_fake_handshake_message_to_string(int msg) {
- if (msg < 0 || msg >= TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
- gpr_log(GPR_ERROR, "Invalid message %d", msg);
- return "UNKNOWN";
- }
- return tsi_fake_handshake_message_strings[msg];
-}
-
-static tsi_result tsi_fake_handshake_message_from_string(
- const char* msg_string, tsi_fake_handshake_message* msg) {
- for (int i = 0; i < TSI_FAKE_HANDSHAKE_MESSAGE_MAX; i++) {
- if (strncmp(msg_string, tsi_fake_handshake_message_strings[i],
- strlen(tsi_fake_handshake_message_strings[i])) == 0) {
- *msg = static_cast<tsi_fake_handshake_message>(i);
- return TSI_OK;
- }
- }
- gpr_log(GPR_ERROR, "Invalid handshake message.");
- return TSI_DATA_CORRUPTED;
-}
-
-static uint32_t load32_little_endian(const unsigned char* buf) {
- return (static_cast<uint32_t>(buf[0]) | static_cast<uint32_t>(buf[1] << 8) |
- static_cast<uint32_t>(buf[2] << 16) |
- static_cast<uint32_t>(buf[3] << 24));
-}
-
-static void store32_little_endian(uint32_t value, unsigned char* buf) {
- buf[3] = static_cast<unsigned char>((value >> 24) & 0xFF);
- buf[2] = static_cast<unsigned char>((value >> 16) & 0xFF);
- buf[1] = static_cast<unsigned char>((value >> 8) & 0xFF);
- buf[0] = static_cast<unsigned char>((value)&0xFF);
-}
-
-static uint32_t read_frame_size(const grpc_slice_buffer* sb) {
- GPR_ASSERT(sb != nullptr && sb->length >= TSI_FAKE_FRAME_HEADER_SIZE);
- uint8_t frame_size_buffer[TSI_FAKE_FRAME_HEADER_SIZE];
- uint8_t* buf = frame_size_buffer;
- /* Copies the first 4 bytes to a temporary buffer. */
- size_t remaining = TSI_FAKE_FRAME_HEADER_SIZE;
- for (size_t i = 0; i < sb->count; i++) {
- size_t slice_length = GRPC_SLICE_LENGTH(sb->slices[i]);
- if (remaining <= slice_length) {
- memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), remaining);
- remaining = 0;
- break;
- } else {
- memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), slice_length);
- buf += slice_length;
- remaining -= slice_length;
- }
- }
- GPR_ASSERT(remaining == 0);
- return load32_little_endian(frame_size_buffer);
-}
-
-static void tsi_fake_frame_reset(tsi_fake_frame* frame, int needs_draining) {
- frame->offset = 0;
- frame->needs_draining = needs_draining;
- if (!needs_draining) frame->size = 0;
-}
-
-/* Checks if the frame's allocated size is at least frame->size, and reallocs
- * more memory if necessary. */
-static void tsi_fake_frame_ensure_size(tsi_fake_frame* frame) {
- if (frame->data == nullptr) {
- frame->allocated_size = frame->size;
- frame->data =
- static_cast<unsigned char*>(gpr_malloc(frame->allocated_size));
- } else if (frame->size > frame->allocated_size) {
- unsigned char* new_data =
- static_cast<unsigned char*>(gpr_realloc(frame->data, frame->size));
- frame->data = new_data;
- frame->allocated_size = frame->size;
- }
-}
-
-/* Decodes the serialized fake frame contained in incoming_bytes, and fills
- * frame with the contents of the decoded frame.
- * This method should not be called if frame->needs_framing is not 0. */
-static tsi_result tsi_fake_frame_decode(const unsigned char* incoming_bytes,
- size_t* incoming_bytes_size,
- tsi_fake_frame* frame) {
- size_t available_size = *incoming_bytes_size;
- size_t to_read_size = 0;
- const unsigned char* bytes_cursor = incoming_bytes;
-
- if (frame->needs_draining) return TSI_INTERNAL_ERROR;
- if (frame->data == nullptr) {
- frame->allocated_size = TSI_FAKE_FRAME_INITIAL_ALLOCATED_SIZE;
- frame->data =
- static_cast<unsigned char*>(gpr_malloc(frame->allocated_size));
- }
-
- if (frame->offset < TSI_FAKE_FRAME_HEADER_SIZE) {
- to_read_size = TSI_FAKE_FRAME_HEADER_SIZE - frame->offset;
- if (to_read_size > available_size) {
- /* Just fill what we can and exit. */
- memcpy(frame->data + frame->offset, bytes_cursor, available_size);
- bytes_cursor += available_size;
- frame->offset += available_size;
- *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
- return TSI_INCOMPLETE_DATA;
- }
- memcpy(frame->data + frame->offset, bytes_cursor, to_read_size);
- bytes_cursor += to_read_size;
- frame->offset += to_read_size;
- available_size -= to_read_size;
- frame->size = load32_little_endian(frame->data);
- tsi_fake_frame_ensure_size(frame);
- }
-
- to_read_size = frame->size - frame->offset;
- if (to_read_size > available_size) {
- memcpy(frame->data + frame->offset, bytes_cursor, available_size);
- frame->offset += available_size;
- bytes_cursor += available_size;
- *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
- return TSI_INCOMPLETE_DATA;
- }
- memcpy(frame->data + frame->offset, bytes_cursor, to_read_size);
- bytes_cursor += to_read_size;
- *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
- tsi_fake_frame_reset(frame, 1 /* needs_draining */);
- return TSI_OK;
-}
-
-/* Encodes a fake frame into its wire format and places the result in
- * outgoing_bytes. outgoing_bytes_size indicates the size of the encoded frame.
- * This method should not be called if frame->needs_framing is 0. */
-static tsi_result tsi_fake_frame_encode(unsigned char* outgoing_bytes,
- size_t* outgoing_bytes_size,
- tsi_fake_frame* frame) {
- size_t to_write_size = frame->size - frame->offset;
- if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
- if (*outgoing_bytes_size < to_write_size) {
- memcpy(outgoing_bytes, frame->data + frame->offset, *outgoing_bytes_size);
- frame->offset += *outgoing_bytes_size;
- return TSI_INCOMPLETE_DATA;
- }
- memcpy(outgoing_bytes, frame->data + frame->offset, to_write_size);
- *outgoing_bytes_size = to_write_size;
- tsi_fake_frame_reset(frame, 0 /* needs_draining */);
- return TSI_OK;
-}
-
-/* Sets the payload of a fake frame to contain the given data blob, where
- * data_size indicates the size of data. */
-static tsi_result tsi_fake_frame_set_data(unsigned char* data, size_t data_size,
- tsi_fake_frame* frame) {
- frame->offset = 0;
- frame->size = data_size + TSI_FAKE_FRAME_HEADER_SIZE;
- tsi_fake_frame_ensure_size(frame);
- store32_little_endian(static_cast<uint32_t>(frame->size), frame->data);
- memcpy(frame->data + TSI_FAKE_FRAME_HEADER_SIZE, data, data_size);
- tsi_fake_frame_reset(frame, 1 /* needs draining */);
- return TSI_OK;
-}
-
-/* Destroys the contents of a fake frame. */
-static void tsi_fake_frame_destruct(tsi_fake_frame* frame) {
- if (frame->data != nullptr) gpr_free(frame->data);
-}
-
-/* --- tsi_frame_protector methods implementation. ---*/
-
-static tsi_result fake_protector_protect(tsi_frame_protector* self,
- const unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size) {
- tsi_result result = TSI_OK;
- tsi_fake_frame_protector* impl =
- reinterpret_cast<tsi_fake_frame_protector*>(self);
- unsigned char frame_header[TSI_FAKE_FRAME_HEADER_SIZE];
- tsi_fake_frame* frame = &impl->protect_frame;
- size_t saved_output_size = *protected_output_frames_size;
- size_t drained_size = 0;
- size_t* num_bytes_written = protected_output_frames_size;
- *num_bytes_written = 0;
-
- /* Try to drain first. */
- if (frame->needs_draining) {
- drained_size = saved_output_size - *num_bytes_written;
- result =
- tsi_fake_frame_encode(protected_output_frames, &drained_size, frame);
- *num_bytes_written += drained_size;
- protected_output_frames += drained_size;
- if (result != TSI_OK) {
- if (result == TSI_INCOMPLETE_DATA) {
- *unprotected_bytes_size = 0;
- result = TSI_OK;
- }
- return result;
- }
- }
-
- /* Now process the unprotected_bytes. */
- if (frame->needs_draining) return TSI_INTERNAL_ERROR;
- if (frame->size == 0) {
- /* New frame, create a header. */
- size_t written_in_frame_size = 0;
- store32_little_endian(static_cast<uint32_t>(impl->max_frame_size),
- frame_header);
- written_in_frame_size = TSI_FAKE_FRAME_HEADER_SIZE;
- result = tsi_fake_frame_decode(frame_header, &written_in_frame_size, frame);
- if (result != TSI_INCOMPLETE_DATA) {
- gpr_log(GPR_ERROR, "tsi_fake_frame_decode returned %s",
- tsi_result_to_string(result));
- return result;
- }
- }
- result =
- tsi_fake_frame_decode(unprotected_bytes, unprotected_bytes_size, frame);
- if (result != TSI_OK) {
- if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
- return result;
- }
-
- /* Try to drain again. */
- if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
- if (frame->offset != 0) return TSI_INTERNAL_ERROR;
- drained_size = saved_output_size - *num_bytes_written;
- result = tsi_fake_frame_encode(protected_output_frames, &drained_size, frame);
- *num_bytes_written += drained_size;
- if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
- return result;
-}
-
-static tsi_result fake_protector_protect_flush(
- tsi_frame_protector* self, unsigned char* protected_output_frames,
- size_t* protected_output_frames_size, size_t* still_pending_size) {
- tsi_result result = TSI_OK;
- tsi_fake_frame_protector* impl =
- reinterpret_cast<tsi_fake_frame_protector*>(self);
- tsi_fake_frame* frame = &impl->protect_frame;
- if (!frame->needs_draining) {
- /* Create a short frame. */
- frame->size = frame->offset;
- frame->offset = 0;
- frame->needs_draining = 1;
- store32_little_endian(static_cast<uint32_t>(frame->size),
- frame->data); /* Overwrite header. */
- }
- result = tsi_fake_frame_encode(protected_output_frames,
- protected_output_frames_size, frame);
- if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
- *still_pending_size = frame->size - frame->offset;
- return result;
-}
-
-static tsi_result fake_protector_unprotect(
- tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
- size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size) {
- tsi_result result = TSI_OK;
- tsi_fake_frame_protector* impl =
- reinterpret_cast<tsi_fake_frame_protector*>(self);
- tsi_fake_frame* frame = &impl->unprotect_frame;
- size_t saved_output_size = *unprotected_bytes_size;
- size_t drained_size = 0;
- size_t* num_bytes_written = unprotected_bytes_size;
- *num_bytes_written = 0;
-
- /* Try to drain first. */
- if (frame->needs_draining) {
- /* Go past the header if needed. */
- if (frame->offset == 0) frame->offset = TSI_FAKE_FRAME_HEADER_SIZE;
- drained_size = saved_output_size - *num_bytes_written;
- result = tsi_fake_frame_encode(unprotected_bytes, &drained_size, frame);
- unprotected_bytes += drained_size;
- *num_bytes_written += drained_size;
- if (result != TSI_OK) {
- if (result == TSI_INCOMPLETE_DATA) {
- *protected_frames_bytes_size = 0;
- result = TSI_OK;
- }
- return result;
- }
- }
-
- /* Now process the protected_bytes. */
- if (frame->needs_draining) return TSI_INTERNAL_ERROR;
- result = tsi_fake_frame_decode(protected_frames_bytes,
- protected_frames_bytes_size, frame);
- if (result != TSI_OK) {
- if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
- return result;
- }
-
- /* Try to drain again. */
- if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
- if (frame->offset != 0) return TSI_INTERNAL_ERROR;
- frame->offset = TSI_FAKE_FRAME_HEADER_SIZE; /* Go past the header. */
- drained_size = saved_output_size - *num_bytes_written;
- result = tsi_fake_frame_encode(unprotected_bytes, &drained_size, frame);
- *num_bytes_written += drained_size;
- if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
- return result;
-}
-
-static void fake_protector_destroy(tsi_frame_protector* self) {
- tsi_fake_frame_protector* impl =
- reinterpret_cast<tsi_fake_frame_protector*>(self);
- tsi_fake_frame_destruct(&impl->protect_frame);
- tsi_fake_frame_destruct(&impl->unprotect_frame);
- gpr_free(self);
-}
-
-static const tsi_frame_protector_vtable frame_protector_vtable = {
- fake_protector_protect,
- fake_protector_protect_flush,
- fake_protector_unprotect,
- fake_protector_destroy,
-};
-
-/* --- tsi_zero_copy_grpc_protector methods implementation. ---*/
-
-static tsi_result fake_zero_copy_grpc_protector_protect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices) {
- if (self == nullptr || unprotected_slices == nullptr ||
- protected_slices == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- tsi_fake_zero_copy_grpc_protector* impl =
- reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
- /* Protects each frame. */
- while (unprotected_slices->length > 0) {
- size_t frame_length =
- GPR_MIN(impl->max_frame_size,
- unprotected_slices->length + TSI_FAKE_FRAME_HEADER_SIZE);
- grpc_slice slice = GRPC_SLICE_MALLOC(TSI_FAKE_FRAME_HEADER_SIZE);
- store32_little_endian(static_cast<uint32_t>(frame_length),
- GRPC_SLICE_START_PTR(slice));
- grpc_slice_buffer_add(protected_slices, slice);
- size_t data_length = frame_length - TSI_FAKE_FRAME_HEADER_SIZE;
- grpc_slice_buffer_move_first(unprotected_slices, data_length,
- protected_slices);
- }
- return TSI_OK;
-}
-
-static tsi_result fake_zero_copy_grpc_protector_unprotect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices) {
- if (self == nullptr || unprotected_slices == nullptr ||
- protected_slices == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- tsi_fake_zero_copy_grpc_protector* impl =
- reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
- grpc_slice_buffer_move_into(protected_slices, &impl->protected_sb);
- /* Unprotect each frame, if we get a full frame. */
- while (impl->protected_sb.length >= TSI_FAKE_FRAME_HEADER_SIZE) {
- if (impl->parsed_frame_size == 0) {
- impl->parsed_frame_size = read_frame_size(&impl->protected_sb);
- if (impl->parsed_frame_size <= 4) {
- gpr_log(GPR_ERROR, "Invalid frame size.");
- return TSI_DATA_CORRUPTED;
- }
- }
- /* If we do not have a full frame, return with OK status. */
- if (impl->protected_sb.length < impl->parsed_frame_size) break;
- /* Strips header bytes. */
- grpc_slice_buffer_move_first(&impl->protected_sb,
- TSI_FAKE_FRAME_HEADER_SIZE, &impl->header_sb);
- /* Moves data to unprotected slices. */
- grpc_slice_buffer_move_first(
- &impl->protected_sb,
- impl->parsed_frame_size - TSI_FAKE_FRAME_HEADER_SIZE,
- unprotected_slices);
- impl->parsed_frame_size = 0;
- grpc_slice_buffer_reset_and_unref_internal(&impl->header_sb);
- }
- return TSI_OK;
-}
-
-static void fake_zero_copy_grpc_protector_destroy(
- tsi_zero_copy_grpc_protector* self) {
- if (self == nullptr) return;
- tsi_fake_zero_copy_grpc_protector* impl =
- reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
- grpc_slice_buffer_destroy_internal(&impl->header_sb);
- grpc_slice_buffer_destroy_internal(&impl->protected_sb);
- gpr_free(impl);
-}
-
-static const tsi_zero_copy_grpc_protector_vtable
- zero_copy_grpc_protector_vtable = {
- fake_zero_copy_grpc_protector_protect,
- fake_zero_copy_grpc_protector_unprotect,
- fake_zero_copy_grpc_protector_destroy,
+/* --- Utils. ---*/
+
+static const char* tsi_fake_handshake_message_strings[] = {
+ "CLIENT_INIT", "SERVER_INIT", "CLIENT_FINISHED", "SERVER_FINISHED"};
+
+static const char* tsi_fake_handshake_message_to_string(int msg) {
+ if (msg < 0 || msg >= TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
+ gpr_log(GPR_ERROR, "Invalid message %d", msg);
+ return "UNKNOWN";
+ }
+ return tsi_fake_handshake_message_strings[msg];
+}
+
+static tsi_result tsi_fake_handshake_message_from_string(
+ const char* msg_string, tsi_fake_handshake_message* msg) {
+ for (int i = 0; i < TSI_FAKE_HANDSHAKE_MESSAGE_MAX; i++) {
+ if (strncmp(msg_string, tsi_fake_handshake_message_strings[i],
+ strlen(tsi_fake_handshake_message_strings[i])) == 0) {
+ *msg = static_cast<tsi_fake_handshake_message>(i);
+ return TSI_OK;
+ }
+ }
+ gpr_log(GPR_ERROR, "Invalid handshake message.");
+ return TSI_DATA_CORRUPTED;
+}
+
+static uint32_t load32_little_endian(const unsigned char* buf) {
+ return (static_cast<uint32_t>(buf[0]) | static_cast<uint32_t>(buf[1] << 8) |
+ static_cast<uint32_t>(buf[2] << 16) |
+ static_cast<uint32_t>(buf[3] << 24));
+}
+
+static void store32_little_endian(uint32_t value, unsigned char* buf) {
+ buf[3] = static_cast<unsigned char>((value >> 24) & 0xFF);
+ buf[2] = static_cast<unsigned char>((value >> 16) & 0xFF);
+ buf[1] = static_cast<unsigned char>((value >> 8) & 0xFF);
+ buf[0] = static_cast<unsigned char>((value)&0xFF);
+}
+
+static uint32_t read_frame_size(const grpc_slice_buffer* sb) {
+ GPR_ASSERT(sb != nullptr && sb->length >= TSI_FAKE_FRAME_HEADER_SIZE);
+ uint8_t frame_size_buffer[TSI_FAKE_FRAME_HEADER_SIZE];
+ uint8_t* buf = frame_size_buffer;
+ /* Copies the first 4 bytes to a temporary buffer. */
+ size_t remaining = TSI_FAKE_FRAME_HEADER_SIZE;
+ for (size_t i = 0; i < sb->count; i++) {
+ size_t slice_length = GRPC_SLICE_LENGTH(sb->slices[i]);
+ if (remaining <= slice_length) {
+ memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), remaining);
+ remaining = 0;
+ break;
+ } else {
+ memcpy(buf, GRPC_SLICE_START_PTR(sb->slices[i]), slice_length);
+ buf += slice_length;
+ remaining -= slice_length;
+ }
+ }
+ GPR_ASSERT(remaining == 0);
+ return load32_little_endian(frame_size_buffer);
+}
+
+static void tsi_fake_frame_reset(tsi_fake_frame* frame, int needs_draining) {
+ frame->offset = 0;
+ frame->needs_draining = needs_draining;
+ if (!needs_draining) frame->size = 0;
+}
+
+/* Checks if the frame's allocated size is at least frame->size, and reallocs
+ * more memory if necessary. */
+static void tsi_fake_frame_ensure_size(tsi_fake_frame* frame) {
+ if (frame->data == nullptr) {
+ frame->allocated_size = frame->size;
+ frame->data =
+ static_cast<unsigned char*>(gpr_malloc(frame->allocated_size));
+ } else if (frame->size > frame->allocated_size) {
+ unsigned char* new_data =
+ static_cast<unsigned char*>(gpr_realloc(frame->data, frame->size));
+ frame->data = new_data;
+ frame->allocated_size = frame->size;
+ }
+}
+
+/* Decodes the serialized fake frame contained in incoming_bytes, and fills
+ * frame with the contents of the decoded frame.
+ * This method should not be called if frame->needs_framing is not 0. */
+static tsi_result tsi_fake_frame_decode(const unsigned char* incoming_bytes,
+ size_t* incoming_bytes_size,
+ tsi_fake_frame* frame) {
+ size_t available_size = *incoming_bytes_size;
+ size_t to_read_size = 0;
+ const unsigned char* bytes_cursor = incoming_bytes;
+
+ if (frame->needs_draining) return TSI_INTERNAL_ERROR;
+ if (frame->data == nullptr) {
+ frame->allocated_size = TSI_FAKE_FRAME_INITIAL_ALLOCATED_SIZE;
+ frame->data =
+ static_cast<unsigned char*>(gpr_malloc(frame->allocated_size));
+ }
+
+ if (frame->offset < TSI_FAKE_FRAME_HEADER_SIZE) {
+ to_read_size = TSI_FAKE_FRAME_HEADER_SIZE - frame->offset;
+ if (to_read_size > available_size) {
+ /* Just fill what we can and exit. */
+ memcpy(frame->data + frame->offset, bytes_cursor, available_size);
+ bytes_cursor += available_size;
+ frame->offset += available_size;
+ *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
+ return TSI_INCOMPLETE_DATA;
+ }
+ memcpy(frame->data + frame->offset, bytes_cursor, to_read_size);
+ bytes_cursor += to_read_size;
+ frame->offset += to_read_size;
+ available_size -= to_read_size;
+ frame->size = load32_little_endian(frame->data);
+ tsi_fake_frame_ensure_size(frame);
+ }
+
+ to_read_size = frame->size - frame->offset;
+ if (to_read_size > available_size) {
+ memcpy(frame->data + frame->offset, bytes_cursor, available_size);
+ frame->offset += available_size;
+ bytes_cursor += available_size;
+ *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
+ return TSI_INCOMPLETE_DATA;
+ }
+ memcpy(frame->data + frame->offset, bytes_cursor, to_read_size);
+ bytes_cursor += to_read_size;
+ *incoming_bytes_size = static_cast<size_t>(bytes_cursor - incoming_bytes);
+ tsi_fake_frame_reset(frame, 1 /* needs_draining */);
+ return TSI_OK;
+}
+
+/* Encodes a fake frame into its wire format and places the result in
+ * outgoing_bytes. outgoing_bytes_size indicates the size of the encoded frame.
+ * This method should not be called if frame->needs_framing is 0. */
+static tsi_result tsi_fake_frame_encode(unsigned char* outgoing_bytes,
+ size_t* outgoing_bytes_size,
+ tsi_fake_frame* frame) {
+ size_t to_write_size = frame->size - frame->offset;
+ if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
+ if (*outgoing_bytes_size < to_write_size) {
+ memcpy(outgoing_bytes, frame->data + frame->offset, *outgoing_bytes_size);
+ frame->offset += *outgoing_bytes_size;
+ return TSI_INCOMPLETE_DATA;
+ }
+ memcpy(outgoing_bytes, frame->data + frame->offset, to_write_size);
+ *outgoing_bytes_size = to_write_size;
+ tsi_fake_frame_reset(frame, 0 /* needs_draining */);
+ return TSI_OK;
+}
+
+/* Sets the payload of a fake frame to contain the given data blob, where
+ * data_size indicates the size of data. */
+static tsi_result tsi_fake_frame_set_data(unsigned char* data, size_t data_size,
+ tsi_fake_frame* frame) {
+ frame->offset = 0;
+ frame->size = data_size + TSI_FAKE_FRAME_HEADER_SIZE;
+ tsi_fake_frame_ensure_size(frame);
+ store32_little_endian(static_cast<uint32_t>(frame->size), frame->data);
+ memcpy(frame->data + TSI_FAKE_FRAME_HEADER_SIZE, data, data_size);
+ tsi_fake_frame_reset(frame, 1 /* needs draining */);
+ return TSI_OK;
+}
+
+/* Destroys the contents of a fake frame. */
+static void tsi_fake_frame_destruct(tsi_fake_frame* frame) {
+ if (frame->data != nullptr) gpr_free(frame->data);
+}
+
+/* --- tsi_frame_protector methods implementation. ---*/
+
+static tsi_result fake_protector_protect(tsi_frame_protector* self,
+ const unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size) {
+ tsi_result result = TSI_OK;
+ tsi_fake_frame_protector* impl =
+ reinterpret_cast<tsi_fake_frame_protector*>(self);
+ unsigned char frame_header[TSI_FAKE_FRAME_HEADER_SIZE];
+ tsi_fake_frame* frame = &impl->protect_frame;
+ size_t saved_output_size = *protected_output_frames_size;
+ size_t drained_size = 0;
+ size_t* num_bytes_written = protected_output_frames_size;
+ *num_bytes_written = 0;
+
+ /* Try to drain first. */
+ if (frame->needs_draining) {
+ drained_size = saved_output_size - *num_bytes_written;
+ result =
+ tsi_fake_frame_encode(protected_output_frames, &drained_size, frame);
+ *num_bytes_written += drained_size;
+ protected_output_frames += drained_size;
+ if (result != TSI_OK) {
+ if (result == TSI_INCOMPLETE_DATA) {
+ *unprotected_bytes_size = 0;
+ result = TSI_OK;
+ }
+ return result;
+ }
+ }
+
+ /* Now process the unprotected_bytes. */
+ if (frame->needs_draining) return TSI_INTERNAL_ERROR;
+ if (frame->size == 0) {
+ /* New frame, create a header. */
+ size_t written_in_frame_size = 0;
+ store32_little_endian(static_cast<uint32_t>(impl->max_frame_size),
+ frame_header);
+ written_in_frame_size = TSI_FAKE_FRAME_HEADER_SIZE;
+ result = tsi_fake_frame_decode(frame_header, &written_in_frame_size, frame);
+ if (result != TSI_INCOMPLETE_DATA) {
+ gpr_log(GPR_ERROR, "tsi_fake_frame_decode returned %s",
+ tsi_result_to_string(result));
+ return result;
+ }
+ }
+ result =
+ tsi_fake_frame_decode(unprotected_bytes, unprotected_bytes_size, frame);
+ if (result != TSI_OK) {
+ if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
+ return result;
+ }
+
+ /* Try to drain again. */
+ if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
+ if (frame->offset != 0) return TSI_INTERNAL_ERROR;
+ drained_size = saved_output_size - *num_bytes_written;
+ result = tsi_fake_frame_encode(protected_output_frames, &drained_size, frame);
+ *num_bytes_written += drained_size;
+ if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
+ return result;
+}
+
+static tsi_result fake_protector_protect_flush(
+ tsi_frame_protector* self, unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size, size_t* still_pending_size) {
+ tsi_result result = TSI_OK;
+ tsi_fake_frame_protector* impl =
+ reinterpret_cast<tsi_fake_frame_protector*>(self);
+ tsi_fake_frame* frame = &impl->protect_frame;
+ if (!frame->needs_draining) {
+ /* Create a short frame. */
+ frame->size = frame->offset;
+ frame->offset = 0;
+ frame->needs_draining = 1;
+ store32_little_endian(static_cast<uint32_t>(frame->size),
+ frame->data); /* Overwrite header. */
+ }
+ result = tsi_fake_frame_encode(protected_output_frames,
+ protected_output_frames_size, frame);
+ if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
+ *still_pending_size = frame->size - frame->offset;
+ return result;
+}
+
+static tsi_result fake_protector_unprotect(
+ tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
+ size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size) {
+ tsi_result result = TSI_OK;
+ tsi_fake_frame_protector* impl =
+ reinterpret_cast<tsi_fake_frame_protector*>(self);
+ tsi_fake_frame* frame = &impl->unprotect_frame;
+ size_t saved_output_size = *unprotected_bytes_size;
+ size_t drained_size = 0;
+ size_t* num_bytes_written = unprotected_bytes_size;
+ *num_bytes_written = 0;
+
+ /* Try to drain first. */
+ if (frame->needs_draining) {
+ /* Go past the header if needed. */
+ if (frame->offset == 0) frame->offset = TSI_FAKE_FRAME_HEADER_SIZE;
+ drained_size = saved_output_size - *num_bytes_written;
+ result = tsi_fake_frame_encode(unprotected_bytes, &drained_size, frame);
+ unprotected_bytes += drained_size;
+ *num_bytes_written += drained_size;
+ if (result != TSI_OK) {
+ if (result == TSI_INCOMPLETE_DATA) {
+ *protected_frames_bytes_size = 0;
+ result = TSI_OK;
+ }
+ return result;
+ }
+ }
+
+ /* Now process the protected_bytes. */
+ if (frame->needs_draining) return TSI_INTERNAL_ERROR;
+ result = tsi_fake_frame_decode(protected_frames_bytes,
+ protected_frames_bytes_size, frame);
+ if (result != TSI_OK) {
+ if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
+ return result;
+ }
+
+ /* Try to drain again. */
+ if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
+ if (frame->offset != 0) return TSI_INTERNAL_ERROR;
+ frame->offset = TSI_FAKE_FRAME_HEADER_SIZE; /* Go past the header. */
+ drained_size = saved_output_size - *num_bytes_written;
+ result = tsi_fake_frame_encode(unprotected_bytes, &drained_size, frame);
+ *num_bytes_written += drained_size;
+ if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
+ return result;
+}
+
+static void fake_protector_destroy(tsi_frame_protector* self) {
+ tsi_fake_frame_protector* impl =
+ reinterpret_cast<tsi_fake_frame_protector*>(self);
+ tsi_fake_frame_destruct(&impl->protect_frame);
+ tsi_fake_frame_destruct(&impl->unprotect_frame);
+ gpr_free(self);
+}
+
+static const tsi_frame_protector_vtable frame_protector_vtable = {
+ fake_protector_protect,
+ fake_protector_protect_flush,
+ fake_protector_unprotect,
+ fake_protector_destroy,
+};
+
+/* --- tsi_zero_copy_grpc_protector methods implementation. ---*/
+
+static tsi_result fake_zero_copy_grpc_protector_protect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices) {
+ if (self == nullptr || unprotected_slices == nullptr ||
+ protected_slices == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ tsi_fake_zero_copy_grpc_protector* impl =
+ reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
+ /* Protects each frame. */
+ while (unprotected_slices->length > 0) {
+ size_t frame_length =
+ GPR_MIN(impl->max_frame_size,
+ unprotected_slices->length + TSI_FAKE_FRAME_HEADER_SIZE);
+ grpc_slice slice = GRPC_SLICE_MALLOC(TSI_FAKE_FRAME_HEADER_SIZE);
+ store32_little_endian(static_cast<uint32_t>(frame_length),
+ GRPC_SLICE_START_PTR(slice));
+ grpc_slice_buffer_add(protected_slices, slice);
+ size_t data_length = frame_length - TSI_FAKE_FRAME_HEADER_SIZE;
+ grpc_slice_buffer_move_first(unprotected_slices, data_length,
+ protected_slices);
+ }
+ return TSI_OK;
+}
+
+static tsi_result fake_zero_copy_grpc_protector_unprotect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices) {
+ if (self == nullptr || unprotected_slices == nullptr ||
+ protected_slices == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ tsi_fake_zero_copy_grpc_protector* impl =
+ reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
+ grpc_slice_buffer_move_into(protected_slices, &impl->protected_sb);
+ /* Unprotect each frame, if we get a full frame. */
+ while (impl->protected_sb.length >= TSI_FAKE_FRAME_HEADER_SIZE) {
+ if (impl->parsed_frame_size == 0) {
+ impl->parsed_frame_size = read_frame_size(&impl->protected_sb);
+ if (impl->parsed_frame_size <= 4) {
+ gpr_log(GPR_ERROR, "Invalid frame size.");
+ return TSI_DATA_CORRUPTED;
+ }
+ }
+ /* If we do not have a full frame, return with OK status. */
+ if (impl->protected_sb.length < impl->parsed_frame_size) break;
+ /* Strips header bytes. */
+ grpc_slice_buffer_move_first(&impl->protected_sb,
+ TSI_FAKE_FRAME_HEADER_SIZE, &impl->header_sb);
+ /* Moves data to unprotected slices. */
+ grpc_slice_buffer_move_first(
+ &impl->protected_sb,
+ impl->parsed_frame_size - TSI_FAKE_FRAME_HEADER_SIZE,
+ unprotected_slices);
+ impl->parsed_frame_size = 0;
+ grpc_slice_buffer_reset_and_unref_internal(&impl->header_sb);
+ }
+ return TSI_OK;
+}
+
+static void fake_zero_copy_grpc_protector_destroy(
+ tsi_zero_copy_grpc_protector* self) {
+ if (self == nullptr) return;
+ tsi_fake_zero_copy_grpc_protector* impl =
+ reinterpret_cast<tsi_fake_zero_copy_grpc_protector*>(self);
+ grpc_slice_buffer_destroy_internal(&impl->header_sb);
+ grpc_slice_buffer_destroy_internal(&impl->protected_sb);
+ gpr_free(impl);
+}
+
+static const tsi_zero_copy_grpc_protector_vtable
+ 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 */
-};
-
-/* --- tsi_handshaker_result methods implementation. ---*/
-
+};
+
+/* --- tsi_handshaker_result methods implementation. ---*/
+
struct fake_handshaker_result {
- tsi_handshaker_result base;
- unsigned char* unused_bytes;
- size_t unused_bytes_size;
+ tsi_handshaker_result base;
+ unsigned char* unused_bytes;
+ size_t unused_bytes_size;
};
-static tsi_result fake_handshaker_result_extract_peer(
+static tsi_result fake_handshaker_result_extract_peer(
const tsi_handshaker_result* self, tsi_peer* peer) {
/* Construct a tsi_peer with 1 property: certificate type, security_level. */
tsi_result result = tsi_construct_peer(2, peer);
- if (result != TSI_OK) return result;
- result = tsi_construct_string_peer_property_from_cstring(
- TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_FAKE_CERTIFICATE_TYPE,
- &peer->properties[0]);
- if (result != TSI_OK) tsi_peer_destruct(peer);
+ if (result != TSI_OK) return result;
+ result = tsi_construct_string_peer_property_from_cstring(
+ TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_FAKE_CERTIFICATE_TYPE,
+ &peer->properties[0]);
+ if (result != TSI_OK) tsi_peer_destruct(peer);
result = tsi_construct_string_peer_property_from_cstring(
TSI_SECURITY_LEVEL_PEER_PROPERTY,
tsi_security_level_to_string(TSI_SECURITY_NONE), &peer->properties[1]);
if (result != TSI_OK) tsi_peer_destruct(peer);
- return result;
-}
-
-static tsi_result fake_handshaker_result_create_zero_copy_grpc_protector(
+ return result;
+}
+
+static tsi_result fake_handshaker_result_create_zero_copy_grpc_protector(
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);
- return TSI_OK;
-}
-
-static tsi_result fake_handshaker_result_create_frame_protector(
+ tsi_zero_copy_grpc_protector** protector) {
+ *protector =
+ tsi_create_fake_zero_copy_grpc_protector(max_output_protected_frame_size);
+ return TSI_OK;
+}
+
+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) {
- *protector = tsi_create_fake_frame_protector(max_output_protected_frame_size);
- return TSI_OK;
-}
-
-static tsi_result fake_handshaker_result_get_unused_bytes(
- const tsi_handshaker_result* self, const unsigned char** bytes,
- size_t* bytes_size) {
- fake_handshaker_result* result = (fake_handshaker_result*)self;
- *bytes_size = result->unused_bytes_size;
- *bytes = result->unused_bytes;
- return TSI_OK;
-}
-
-static void fake_handshaker_result_destroy(tsi_handshaker_result* self) {
- fake_handshaker_result* result =
- reinterpret_cast<fake_handshaker_result*>(self);
- gpr_free(result->unused_bytes);
- gpr_free(self);
-}
-
-static const tsi_handshaker_result_vtable handshaker_result_vtable = {
- fake_handshaker_result_extract_peer,
- fake_handshaker_result_create_zero_copy_grpc_protector,
- fake_handshaker_result_create_frame_protector,
- fake_handshaker_result_get_unused_bytes,
- fake_handshaker_result_destroy,
-};
-
-static tsi_result fake_handshaker_result_create(
- const unsigned char* unused_bytes, size_t unused_bytes_size,
- tsi_handshaker_result** handshaker_result) {
- if ((unused_bytes_size > 0 && unused_bytes == nullptr) ||
- handshaker_result == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- fake_handshaker_result* result =
- static_cast<fake_handshaker_result*>(gpr_zalloc(sizeof(*result)));
- result->base.vtable = &handshaker_result_vtable;
- if (unused_bytes_size > 0) {
- result->unused_bytes =
- static_cast<unsigned char*>(gpr_malloc(unused_bytes_size));
- memcpy(result->unused_bytes, unused_bytes, unused_bytes_size);
- }
- result->unused_bytes_size = unused_bytes_size;
- *handshaker_result = &result->base;
- return TSI_OK;
-}
-
-/* --- tsi_handshaker methods implementation. ---*/
-
-static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
- tsi_handshaker* self, unsigned char* bytes, size_t* bytes_size) {
- tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
- tsi_result result = TSI_OK;
- if (impl->needs_incoming_message || impl->result == TSI_OK) {
- *bytes_size = 0;
- return TSI_OK;
- }
- if (!impl->outgoing_frame.needs_draining) {
- tsi_fake_handshake_message next_message_to_send =
- static_cast<tsi_fake_handshake_message>(impl->next_message_to_send + 2);
- const char* msg_string =
- tsi_fake_handshake_message_to_string(impl->next_message_to_send);
- result = tsi_fake_frame_set_data((unsigned char*)msg_string,
- strlen(msg_string), &impl->outgoing_frame);
- if (result != TSI_OK) return result;
- if (next_message_to_send > TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
- next_message_to_send = TSI_FAKE_HANDSHAKE_MESSAGE_MAX;
- }
+ *protector = tsi_create_fake_frame_protector(max_output_protected_frame_size);
+ return TSI_OK;
+}
+
+static tsi_result fake_handshaker_result_get_unused_bytes(
+ const tsi_handshaker_result* self, const unsigned char** bytes,
+ size_t* bytes_size) {
+ fake_handshaker_result* result = (fake_handshaker_result*)self;
+ *bytes_size = result->unused_bytes_size;
+ *bytes = result->unused_bytes;
+ return TSI_OK;
+}
+
+static void fake_handshaker_result_destroy(tsi_handshaker_result* self) {
+ fake_handshaker_result* result =
+ reinterpret_cast<fake_handshaker_result*>(self);
+ gpr_free(result->unused_bytes);
+ gpr_free(self);
+}
+
+static const tsi_handshaker_result_vtable handshaker_result_vtable = {
+ fake_handshaker_result_extract_peer,
+ fake_handshaker_result_create_zero_copy_grpc_protector,
+ fake_handshaker_result_create_frame_protector,
+ fake_handshaker_result_get_unused_bytes,
+ fake_handshaker_result_destroy,
+};
+
+static tsi_result fake_handshaker_result_create(
+ const unsigned char* unused_bytes, size_t unused_bytes_size,
+ tsi_handshaker_result** handshaker_result) {
+ if ((unused_bytes_size > 0 && unused_bytes == nullptr) ||
+ handshaker_result == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ fake_handshaker_result* result =
+ static_cast<fake_handshaker_result*>(gpr_zalloc(sizeof(*result)));
+ result->base.vtable = &handshaker_result_vtable;
+ if (unused_bytes_size > 0) {
+ result->unused_bytes =
+ static_cast<unsigned char*>(gpr_malloc(unused_bytes_size));
+ memcpy(result->unused_bytes, unused_bytes, unused_bytes_size);
+ }
+ result->unused_bytes_size = unused_bytes_size;
+ *handshaker_result = &result->base;
+ return TSI_OK;
+}
+
+/* --- tsi_handshaker methods implementation. ---*/
+
+static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
+ tsi_handshaker* self, unsigned char* bytes, size_t* bytes_size) {
+ tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
+ tsi_result result = TSI_OK;
+ if (impl->needs_incoming_message || impl->result == TSI_OK) {
+ *bytes_size = 0;
+ return TSI_OK;
+ }
+ if (!impl->outgoing_frame.needs_draining) {
+ tsi_fake_handshake_message next_message_to_send =
+ static_cast<tsi_fake_handshake_message>(impl->next_message_to_send + 2);
+ const char* msg_string =
+ tsi_fake_handshake_message_to_string(impl->next_message_to_send);
+ result = tsi_fake_frame_set_data((unsigned char*)msg_string,
+ strlen(msg_string), &impl->outgoing_frame);
+ if (result != TSI_OK) return result;
+ 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)) {
- gpr_log(GPR_INFO, "%s prepared %s.",
- impl->is_client ? "Client" : "Server",
- tsi_fake_handshake_message_to_string(impl->next_message_to_send));
- }
- impl->next_message_to_send = next_message_to_send;
- }
- result = tsi_fake_frame_encode(bytes, bytes_size, &impl->outgoing_frame);
- if (result != TSI_OK) return result;
- if (!impl->is_client &&
- impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
- /* We're done. */
+ gpr_log(GPR_INFO, "%s prepared %s.",
+ impl->is_client ? "Client" : "Server",
+ tsi_fake_handshake_message_to_string(impl->next_message_to_send));
+ }
+ impl->next_message_to_send = next_message_to_send;
+ }
+ result = tsi_fake_frame_encode(bytes, bytes_size, &impl->outgoing_frame);
+ if (result != TSI_OK) return result;
+ 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)) {
- gpr_log(GPR_INFO, "Server is done.");
- }
- impl->result = TSI_OK;
- } else {
- impl->needs_incoming_message = 1;
- }
- return TSI_OK;
-}
-
-static tsi_result fake_handshaker_process_bytes_from_peer(
- tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) {
- tsi_result result = TSI_OK;
- tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
- tsi_fake_handshake_message expected_msg =
- static_cast<tsi_fake_handshake_message>(impl->next_message_to_send - 1);
- tsi_fake_handshake_message received_msg;
-
- if (!impl->needs_incoming_message || impl->result == TSI_OK) {
- *bytes_size = 0;
- return TSI_OK;
- }
- result = tsi_fake_frame_decode(bytes, bytes_size, &impl->incoming_frame);
- if (result != TSI_OK) return result;
-
- /* We now have a complete frame. */
- result = tsi_fake_handshake_message_from_string(
- reinterpret_cast<const char*>(impl->incoming_frame.data) +
- TSI_FAKE_FRAME_HEADER_SIZE,
- &received_msg);
- if (result != TSI_OK) {
- impl->result = result;
- return result;
- }
- if (received_msg != expected_msg) {
- gpr_log(GPR_ERROR, "Invalid received message (%s instead of %s)",
- tsi_fake_handshake_message_to_string(received_msg),
- tsi_fake_handshake_message_to_string(expected_msg));
- }
+ gpr_log(GPR_INFO, "Server is done.");
+ }
+ impl->result = TSI_OK;
+ } else {
+ impl->needs_incoming_message = 1;
+ }
+ return TSI_OK;
+}
+
+static tsi_result fake_handshaker_process_bytes_from_peer(
+ tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) {
+ tsi_result result = TSI_OK;
+ tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
+ tsi_fake_handshake_message expected_msg =
+ static_cast<tsi_fake_handshake_message>(impl->next_message_to_send - 1);
+ tsi_fake_handshake_message received_msg;
+
+ if (!impl->needs_incoming_message || impl->result == TSI_OK) {
+ *bytes_size = 0;
+ return TSI_OK;
+ }
+ result = tsi_fake_frame_decode(bytes, bytes_size, &impl->incoming_frame);
+ if (result != TSI_OK) return result;
+
+ /* We now have a complete frame. */
+ result = tsi_fake_handshake_message_from_string(
+ reinterpret_cast<const char*>(impl->incoming_frame.data) +
+ TSI_FAKE_FRAME_HEADER_SIZE,
+ &received_msg);
+ if (result != TSI_OK) {
+ impl->result = result;
+ return result;
+ }
+ if (received_msg != expected_msg) {
+ gpr_log(GPR_ERROR, "Invalid received message (%s instead of %s)",
+ tsi_fake_handshake_message_to_string(received_msg),
+ tsi_fake_handshake_message_to_string(expected_msg));
+ }
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));
- }
- tsi_fake_frame_reset(&impl->incoming_frame, 0 /* needs_draining */);
- impl->needs_incoming_message = 0;
- if (impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) {
- /* We're done. */
+ gpr_log(GPR_INFO, "%s received %s.", impl->is_client ? "Client" : "Server",
+ tsi_fake_handshake_message_to_string(received_msg));
+ }
+ tsi_fake_frame_reset(&impl->incoming_frame, 0 /* needs_draining */);
+ 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)) {
- gpr_log(GPR_INFO, "%s is done.", impl->is_client ? "Client" : "Server");
- }
- impl->result = TSI_OK;
- }
- return TSI_OK;
-}
-
-static tsi_result fake_handshaker_get_result(tsi_handshaker* self) {
- tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
- return impl->result;
-}
-
-static void fake_handshaker_destroy(tsi_handshaker* self) {
- tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
- tsi_fake_frame_destruct(&impl->incoming_frame);
- tsi_fake_frame_destruct(&impl->outgoing_frame);
- gpr_free(impl->outgoing_bytes_buffer);
- gpr_free(self);
-}
-
-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,
+ gpr_log(GPR_INFO, "%s is done.", impl->is_client ? "Client" : "Server");
+ }
+ impl->result = TSI_OK;
+ }
+ return TSI_OK;
+}
+
+static tsi_result fake_handshaker_get_result(tsi_handshaker* self) {
+ tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
+ return impl->result;
+}
+
+static void fake_handshaker_destroy(tsi_handshaker* self) {
+ tsi_fake_handshaker* impl = reinterpret_cast<tsi_fake_handshaker*>(self);
+ tsi_fake_frame_destruct(&impl->incoming_frame);
+ tsi_fake_frame_destruct(&impl->outgoing_frame);
+ gpr_free(impl->outgoing_bytes_buffer);
+ gpr_free(self);
+}
+
+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*/) {
- /* Sanity check the arguments. */
- if ((received_bytes_size > 0 && received_bytes == nullptr) ||
- bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
- handshaker_result == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- tsi_fake_handshaker* handshaker =
- reinterpret_cast<tsi_fake_handshaker*>(self);
- tsi_result result = TSI_OK;
-
- /* Decode and process a handshake frame from the peer. */
- size_t consumed_bytes_size = received_bytes_size;
- if (received_bytes_size > 0) {
- result = fake_handshaker_process_bytes_from_peer(self, received_bytes,
- &consumed_bytes_size);
- if (result != TSI_OK) return result;
- }
-
- /* Create a handshake message to send to the peer and encode it as a fake
- * frame. */
- size_t offset = 0;
- do {
- size_t sent_bytes_size = handshaker->outgoing_bytes_buffer_size - offset;
- result = fake_handshaker_get_bytes_to_send_to_peer(
- self, handshaker->outgoing_bytes_buffer + offset, &sent_bytes_size);
- offset += sent_bytes_size;
- if (result == TSI_INCOMPLETE_DATA) {
- handshaker->outgoing_bytes_buffer_size *= 2;
- handshaker->outgoing_bytes_buffer = static_cast<unsigned char*>(
- gpr_realloc(handshaker->outgoing_bytes_buffer,
- handshaker->outgoing_bytes_buffer_size));
- }
- } while (result == TSI_INCOMPLETE_DATA);
- if (result != TSI_OK) return result;
- *bytes_to_send = handshaker->outgoing_bytes_buffer;
- *bytes_to_send_size = offset;
-
- /* Check if the handshake was completed. */
- if (fake_handshaker_get_result(self) == TSI_HANDSHAKE_IN_PROGRESS) {
- *handshaker_result = nullptr;
- } else {
- /* Calculate the unused bytes. */
- const unsigned char* unused_bytes = nullptr;
- size_t unused_bytes_size = received_bytes_size - consumed_bytes_size;
- if (unused_bytes_size > 0) {
- unused_bytes = received_bytes + consumed_bytes_size;
- }
-
- /* Create a handshaker_result containing the unused bytes. */
- result = fake_handshaker_result_create(unused_bytes, unused_bytes_size,
- handshaker_result);
- if (result == TSI_OK) {
- /* Indicate that the handshake has completed and that a handshaker_result
- * has been created. */
- self->handshaker_result_created = true;
- }
- }
- return result;
-}
-
-static const tsi_handshaker_vtable handshaker_vtable = {
- nullptr, /* get_bytes_to_send_to_peer -- deprecated */
- nullptr, /* process_bytes_from_peer -- deprecated */
- nullptr, /* get_result -- deprecated */
- nullptr, /* extract_peer -- deprecated */
- nullptr, /* create_frame_protector -- deprecated */
- fake_handshaker_destroy,
- fake_handshaker_next,
+ /* Sanity check the arguments. */
+ if ((received_bytes_size > 0 && received_bytes == nullptr) ||
+ bytes_to_send == nullptr || bytes_to_send_size == nullptr ||
+ handshaker_result == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ tsi_fake_handshaker* handshaker =
+ reinterpret_cast<tsi_fake_handshaker*>(self);
+ tsi_result result = TSI_OK;
+
+ /* Decode and process a handshake frame from the peer. */
+ size_t consumed_bytes_size = received_bytes_size;
+ if (received_bytes_size > 0) {
+ result = fake_handshaker_process_bytes_from_peer(self, received_bytes,
+ &consumed_bytes_size);
+ if (result != TSI_OK) return result;
+ }
+
+ /* Create a handshake message to send to the peer and encode it as a fake
+ * frame. */
+ size_t offset = 0;
+ do {
+ size_t sent_bytes_size = handshaker->outgoing_bytes_buffer_size - offset;
+ result = fake_handshaker_get_bytes_to_send_to_peer(
+ self, handshaker->outgoing_bytes_buffer + offset, &sent_bytes_size);
+ offset += sent_bytes_size;
+ if (result == TSI_INCOMPLETE_DATA) {
+ handshaker->outgoing_bytes_buffer_size *= 2;
+ handshaker->outgoing_bytes_buffer = static_cast<unsigned char*>(
+ gpr_realloc(handshaker->outgoing_bytes_buffer,
+ handshaker->outgoing_bytes_buffer_size));
+ }
+ } while (result == TSI_INCOMPLETE_DATA);
+ if (result != TSI_OK) return result;
+ *bytes_to_send = handshaker->outgoing_bytes_buffer;
+ *bytes_to_send_size = offset;
+
+ /* Check if the handshake was completed. */
+ if (fake_handshaker_get_result(self) == TSI_HANDSHAKE_IN_PROGRESS) {
+ *handshaker_result = nullptr;
+ } else {
+ /* Calculate the unused bytes. */
+ const unsigned char* unused_bytes = nullptr;
+ size_t unused_bytes_size = received_bytes_size - consumed_bytes_size;
+ if (unused_bytes_size > 0) {
+ unused_bytes = received_bytes + consumed_bytes_size;
+ }
+
+ /* Create a handshaker_result containing the unused bytes. */
+ result = fake_handshaker_result_create(unused_bytes, unused_bytes_size,
+ handshaker_result);
+ if (result == TSI_OK) {
+ /* Indicate that the handshake has completed and that a handshaker_result
+ * has been created. */
+ self->handshaker_result_created = true;
+ }
+ }
+ return result;
+}
+
+static const tsi_handshaker_vtable handshaker_vtable = {
+ nullptr, /* get_bytes_to_send_to_peer -- deprecated */
+ nullptr, /* process_bytes_from_peer -- deprecated */
+ nullptr, /* get_result -- deprecated */
+ nullptr, /* extract_peer -- deprecated */
+ nullptr, /* create_frame_protector -- deprecated */
+ fake_handshaker_destroy,
+ fake_handshaker_next,
nullptr, /* shutdown */
-};
-
-tsi_handshaker* tsi_create_fake_handshaker(int is_client) {
- tsi_fake_handshaker* impl =
- static_cast<tsi_fake_handshaker*>(gpr_zalloc(sizeof(*impl)));
- impl->base.vtable = &handshaker_vtable;
- impl->is_client = is_client;
- impl->result = TSI_HANDSHAKE_IN_PROGRESS;
- impl->outgoing_bytes_buffer_size =
- TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
- impl->outgoing_bytes_buffer =
- static_cast<unsigned char*>(gpr_malloc(impl->outgoing_bytes_buffer_size));
- if (is_client) {
- impl->needs_incoming_message = 0;
- impl->next_message_to_send = TSI_FAKE_CLIENT_INIT;
- } else {
- impl->needs_incoming_message = 1;
- impl->next_message_to_send = TSI_FAKE_SERVER_INIT;
- }
- return &impl->base;
-}
-
-tsi_frame_protector* tsi_create_fake_frame_protector(
- size_t* max_protected_frame_size) {
- tsi_fake_frame_protector* impl =
- static_cast<tsi_fake_frame_protector*>(gpr_zalloc(sizeof(*impl)));
- impl->max_frame_size = (max_protected_frame_size == nullptr)
- ? TSI_FAKE_DEFAULT_FRAME_SIZE
- : *max_protected_frame_size;
- impl->base.vtable = &frame_protector_vtable;
- return &impl->base;
-}
-
-tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector(
- size_t* max_protected_frame_size) {
- tsi_fake_zero_copy_grpc_protector* impl =
- static_cast<tsi_fake_zero_copy_grpc_protector*>(
- gpr_zalloc(sizeof(*impl)));
- grpc_slice_buffer_init(&impl->header_sb);
- grpc_slice_buffer_init(&impl->protected_sb);
- impl->max_frame_size = (max_protected_frame_size == nullptr)
- ? TSI_FAKE_DEFAULT_FRAME_SIZE
- : *max_protected_frame_size;
- impl->parsed_frame_size = 0;
- impl->base.vtable = &zero_copy_grpc_protector_vtable;
- return &impl->base;
-}
+};
+
+tsi_handshaker* tsi_create_fake_handshaker(int is_client) {
+ tsi_fake_handshaker* impl =
+ static_cast<tsi_fake_handshaker*>(gpr_zalloc(sizeof(*impl)));
+ impl->base.vtable = &handshaker_vtable;
+ impl->is_client = is_client;
+ impl->result = TSI_HANDSHAKE_IN_PROGRESS;
+ impl->outgoing_bytes_buffer_size =
+ TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
+ impl->outgoing_bytes_buffer =
+ static_cast<unsigned char*>(gpr_malloc(impl->outgoing_bytes_buffer_size));
+ if (is_client) {
+ impl->needs_incoming_message = 0;
+ impl->next_message_to_send = TSI_FAKE_CLIENT_INIT;
+ } else {
+ impl->needs_incoming_message = 1;
+ impl->next_message_to_send = TSI_FAKE_SERVER_INIT;
+ }
+ return &impl->base;
+}
+
+tsi_frame_protector* tsi_create_fake_frame_protector(
+ size_t* max_protected_frame_size) {
+ tsi_fake_frame_protector* impl =
+ static_cast<tsi_fake_frame_protector*>(gpr_zalloc(sizeof(*impl)));
+ impl->max_frame_size = (max_protected_frame_size == nullptr)
+ ? TSI_FAKE_DEFAULT_FRAME_SIZE
+ : *max_protected_frame_size;
+ impl->base.vtable = &frame_protector_vtable;
+ return &impl->base;
+}
+
+tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector(
+ size_t* max_protected_frame_size) {
+ tsi_fake_zero_copy_grpc_protector* impl =
+ static_cast<tsi_fake_zero_copy_grpc_protector*>(
+ gpr_zalloc(sizeof(*impl)));
+ grpc_slice_buffer_init(&impl->header_sb);
+ grpc_slice_buffer_init(&impl->protected_sb);
+ impl->max_frame_size = (max_protected_frame_size == nullptr)
+ ? TSI_FAKE_DEFAULT_FRAME_SIZE
+ : *max_protected_frame_size;
+ impl->parsed_frame_size = 0;
+ impl->base.vtable = &zero_copy_grpc_protector_vtable;
+ return &impl->base;
+}
diff --git a/contrib/libs/grpc/src/core/tsi/fake_transport_security.h b/contrib/libs/grpc/src/core/tsi/fake_transport_security.h
index 704d9fb1a12..c9101fc21aa 100644
--- a/contrib/libs/grpc/src/core/tsi/fake_transport_security.h
+++ b/contrib/libs/grpc/src/core/tsi/fake_transport_security.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_CORE_TSI_FAKE_TRANSPORT_SECURITY_H
-#define GRPC_CORE_TSI_FAKE_TRANSPORT_SECURITY_H
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/tsi/transport_security_interface.h"
-
-/* Value for the TSI_CERTIFICATE_TYPE_PEER_PROPERTY property for FAKE certs. */
-#define TSI_FAKE_CERTIFICATE_TYPE "FAKE"
+/*
+ *
+ * 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_TSI_FAKE_TRANSPORT_SECURITY_H
+#define GRPC_CORE_TSI_FAKE_TRANSPORT_SECURITY_H
+
+#include <grpc/support/port_platform.h>
+
+#include "src/core/tsi/transport_security_interface.h"
+
+/* Value for the TSI_CERTIFICATE_TYPE_PEER_PROPERTY property for FAKE certs. */
+#define TSI_FAKE_CERTIFICATE_TYPE "FAKE"
/* Value of the TSI_SECURITY_LEVEL_PEER_PROPERTY property for FAKE certs. */
#define TSI_FAKE_SECURITY_LEVEL "TSI_SECURITY_NONE"
-
-/* Creates a fake handshaker that will create a fake frame protector.
-
- No cryptography is performed in these objects. They just simulate handshake
- messages going back and forth for the handshaker and do some framing on
- cleartext data for the protector. */
-tsi_handshaker* tsi_create_fake_handshaker(int is_client);
-
-/* Creates a protector directly without going through the handshake phase. */
-tsi_frame_protector* tsi_create_fake_frame_protector(
- size_t* max_protected_frame_size);
-
-/* Creates a zero-copy protector directly without going through the handshake
- * phase. */
-tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector(
- size_t* max_protected_frame_size);
-
-#endif /* GRPC_CORE_TSI_FAKE_TRANSPORT_SECURITY_H */
+
+/* Creates a fake handshaker that will create a fake frame protector.
+
+ No cryptography is performed in these objects. They just simulate handshake
+ messages going back and forth for the handshaker and do some framing on
+ cleartext data for the protector. */
+tsi_handshaker* tsi_create_fake_handshaker(int is_client);
+
+/* Creates a protector directly without going through the handshake phase. */
+tsi_frame_protector* tsi_create_fake_frame_protector(
+ size_t* max_protected_frame_size);
+
+/* Creates a zero-copy protector directly without going through the handshake
+ * phase. */
+tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector(
+ size_t* max_protected_frame_size);
+
+#endif /* GRPC_CORE_TSI_FAKE_TRANSPORT_SECURITY_H */
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 108c0cd1338..c4591fd0bbe 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
@@ -1,71 +1,71 @@
-/*
- *
- * 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_TSI_SSL_SESSION_CACHE_SSL_SESSION_H
-#define GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.h>
-
-extern "C" {
-#include <openssl/ssl.h>
-}
-
-#include "src/core/lib/gprpp/ref_counted.h"
-
-// The main purpose of code here is to provide means to cache SSL sessions
-// in a way that they can be shared between connections.
-//
-// SSL_SESSION stands for single instance of session and is not generally safe
-// to share between SSL contexts with different lifetimes. It happens because
-// not all SSL implementations guarantee immutability of SSL_SESSION object.
-// See SSL_SESSION documentation in BoringSSL and OpenSSL for more details.
-
-namespace tsi {
-
-struct SslSessionDeleter {
- void operator()(SSL_SESSION* session) { SSL_SESSION_free(session); }
-};
-
-typedef std::unique_ptr<SSL_SESSION, SslSessionDeleter> SslSessionPtr;
-
-/// SslCachedSession is an immutable thread-safe storage for single session
-/// representation. It provides means to share SSL session data (e.g. TLS
-/// ticket) between encrypted connections regardless of SSL context lifetime.
-class SslCachedSession {
- public:
- // Not copyable nor movable.
- SslCachedSession(const SslCachedSession&) = delete;
- SslCachedSession& operator=(const SslCachedSession&) = delete;
-
- /// Create single cached instance of \a session.
+/*
+ *
+ * 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_TSI_SSL_SESSION_CACHE_SSL_SESSION_H
+#define GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice.h>
+
+extern "C" {
+#include <openssl/ssl.h>
+}
+
+#include "src/core/lib/gprpp/ref_counted.h"
+
+// The main purpose of code here is to provide means to cache SSL sessions
+// in a way that they can be shared between connections.
+//
+// SSL_SESSION stands for single instance of session and is not generally safe
+// to share between SSL contexts with different lifetimes. It happens because
+// not all SSL implementations guarantee immutability of SSL_SESSION object.
+// See SSL_SESSION documentation in BoringSSL and OpenSSL for more details.
+
+namespace tsi {
+
+struct SslSessionDeleter {
+ void operator()(SSL_SESSION* session) { SSL_SESSION_free(session); }
+};
+
+typedef std::unique_ptr<SSL_SESSION, SslSessionDeleter> SslSessionPtr;
+
+/// SslCachedSession is an immutable thread-safe storage for single session
+/// representation. It provides means to share SSL session data (e.g. TLS
+/// ticket) between encrypted connections regardless of SSL context lifetime.
+class SslCachedSession {
+ public:
+ // Not copyable nor movable.
+ SslCachedSession(const SslCachedSession&) = delete;
+ SslCachedSession& operator=(const SslCachedSession&) = delete;
+
+ /// Create single cached instance of \a session.
static std::unique_ptr<SslCachedSession> Create(SslSessionPtr session);
-
- virtual ~SslCachedSession() = default;
-
- /// Returns a copy of previously cached session.
+
+ virtual ~SslCachedSession() = default;
+
+ /// Returns a copy of previously cached session.
virtual SslSessionPtr CopySession() const = 0;
-
- protected:
- SslCachedSession() = default;
-};
-
-} // namespace tsi
-
-#endif /* GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_H */
+
+ protected:
+ SslCachedSession() = default;
+};
+
+} // namespace tsi
+
+#endif /* GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_H */
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 a77b17c5dd5..55599020726 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
@@ -1,57 +1,57 @@
-/*
- *
- * 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/ssl/session_cache/ssl_session.h"
-
-#ifdef OPENSSL_IS_BORINGSSL
-
-// BoringSSL allows SSL_SESSION to outlive SSL and SSL_CTX objects which are
-// re-created by gRPC on every certificate rotation or subchannel creation.
-// BoringSSL guarantees that SSL_SESSION is immutable so it's safe to share
-// the same original session object between different threads and connections.
-
-namespace tsi {
-namespace {
-
-class BoringSslCachedSession : public SslCachedSession {
- public:
- BoringSslCachedSession(SslSessionPtr session)
- : session_(std::move(session)) {}
-
- SslSessionPtr CopySession() const override {
- // SslSessionPtr will dereference on destruction.
- SSL_SESSION_up_ref(session_.get());
- return SslSessionPtr(session_.get());
- }
-
- private:
- SslSessionPtr session_;
-};
-
-} // 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 <grpc/support/port_platform.h>
+
+#include "src/core/tsi/ssl/session_cache/ssl_session.h"
+
+#ifdef OPENSSL_IS_BORINGSSL
+
+// BoringSSL allows SSL_SESSION to outlive SSL and SSL_CTX objects which are
+// re-created by gRPC on every certificate rotation or subchannel creation.
+// BoringSSL guarantees that SSL_SESSION is immutable so it's safe to share
+// the same original session object between different threads and connections.
+
+namespace tsi {
+namespace {
+
+class BoringSslCachedSession : public SslCachedSession {
+ public:
+ BoringSslCachedSession(SslSessionPtr session)
+ : session_(std::move(session)) {}
+
+ SslSessionPtr CopySession() const override {
+ // SslSessionPtr will dereference on destruction.
+ SSL_SESSION_up_ref(session_.get());
+ return SslSessionPtr(session_.get());
+ }
+
+ private:
+ SslSessionPtr session_;
+};
+
+} // namespace
+
std::unique_ptr<SslCachedSession> SslCachedSession::Create(
- SslSessionPtr session) {
+ SslSessionPtr session) {
return y_absl::make_unique<BoringSslCachedSession>(std::move(session));
-}
-
-} // namespace tsi
-
-#endif /* OPENSSL_IS_BORINGSSL */
+}
+
+} // namespace tsi
+
+#endif /* OPENSSL_IS_BORINGSSL */
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 6da4fb4ee1c..007a8c50dc8 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
@@ -1,214 +1,214 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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/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"
-
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-namespace tsi {
-
+#include "src/core/tsi/ssl/session_cache/ssl_session_cache.h"
+
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+namespace tsi {
+
static void cache_key_avl_destroy(void* /*key*/, void* /*unused*/) {}
-
+
static void* cache_key_avl_copy(void* key, void* /*unused*/) { return key; }
-
+
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));
-}
-
+ 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_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 = {
- cache_key_avl_destroy, cache_key_avl_copy, cache_key_avl_compare,
- cache_value_avl_destroy, cache_value_avl_copy,
-};
-
-/// Node for single cached session.
-class SslSessionLRUCache::Node {
- public:
- Node(const grpc_slice& key, SslSessionPtr session) : key_(key) {
- SetSession(std::move(session));
- }
-
+
+// AVL only stores pointers, ownership belonges to the linked list.
+static const grpc_avl_vtable cache_avl_vtable = {
+ cache_key_avl_destroy, cache_key_avl_copy, cache_key_avl_compare,
+ cache_value_avl_destroy, cache_value_avl_copy,
+};
+
+/// Node for single cached session.
+class SslSessionLRUCache::Node {
+ public:
+ Node(const grpc_slice& key, SslSessionPtr session) : key_(key) {
+ SetSession(std::move(session));
+ }
+
~Node() { grpc_slice_unref_internal(key_); }
-
- // Not copyable nor movable.
- Node(const Node&) = delete;
- Node& operator=(const Node&) = delete;
-
- void* AvlKey() { return &key_; }
-
- /// Returns a copy of the node's cache session.
- SslSessionPtr CopySession() const { return session_->CopySession(); }
-
- /// Set the \a session (which is moved) for the node.
- void SetSession(SslSessionPtr session) {
- session_ = SslCachedSession::Create(std::move(session));
- }
-
- private:
- friend class SslSessionLRUCache;
-
- grpc_slice key_;
+
+ // Not copyable nor movable.
+ Node(const Node&) = delete;
+ Node& operator=(const Node&) = delete;
+
+ void* AvlKey() { return &key_; }
+
+ /// Returns a copy of the node's cache session.
+ SslSessionPtr CopySession() const { return session_->CopySession(); }
+
+ /// Set the \a session (which is moved) for the node.
+ void SetSession(SslSessionPtr session) {
+ session_ = SslCachedSession::Create(std::move(session));
+ }
+
+ private:
+ friend class SslSessionLRUCache;
+
+ grpc_slice key_;
std::unique_ptr<SslCachedSession> session_;
-
- Node* next_ = nullptr;
- Node* prev_ = nullptr;
-};
-
-SslSessionLRUCache::SslSessionLRUCache(size_t capacity) : capacity_(capacity) {
- GPR_ASSERT(capacity > 0);
- gpr_mu_init(&lock_);
- entry_by_key_ = grpc_avl_create(&cache_avl_vtable);
-}
-
-SslSessionLRUCache::~SslSessionLRUCache() {
- Node* node = use_order_list_head_;
- while (node) {
- Node* next = node->next_;
+
+ Node* next_ = nullptr;
+ Node* prev_ = nullptr;
+};
+
+SslSessionLRUCache::SslSessionLRUCache(size_t capacity) : capacity_(capacity) {
+ GPR_ASSERT(capacity > 0);
+ gpr_mu_init(&lock_);
+ entry_by_key_ = grpc_avl_create(&cache_avl_vtable);
+}
+
+SslSessionLRUCache::~SslSessionLRUCache() {
+ Node* node = use_order_list_head_;
+ while (node) {
+ Node* next = node->next_;
delete node;
- node = next;
- }
- grpc_avl_unref(entry_by_key_, nullptr);
- gpr_mu_destroy(&lock_);
-}
-
-size_t SslSessionLRUCache::Size() {
+ node = next;
+ }
+ grpc_avl_unref(entry_by_key_, nullptr);
+ gpr_mu_destroy(&lock_);
+}
+
+size_t SslSessionLRUCache::Size() {
grpc_core::MutexLock lock(&lock_);
- return use_order_list_size_;
-}
-
-SslSessionLRUCache::Node* SslSessionLRUCache::FindLocked(
- const grpc_slice& key) {
- void* value =
- grpc_avl_get(entry_by_key_, const_cast<grpc_slice*>(&key), nullptr);
- if (value == nullptr) {
- return nullptr;
- }
- Node* node = static_cast<Node*>(value);
- // Move to the beginning.
- Remove(node);
- PushFront(node);
- AssertInvariants();
- return node;
-}
-
-void SslSessionLRUCache::Put(const char* key, SslSessionPtr session) {
+ return use_order_list_size_;
+}
+
+SslSessionLRUCache::Node* SslSessionLRUCache::FindLocked(
+ const grpc_slice& key) {
+ void* value =
+ grpc_avl_get(entry_by_key_, const_cast<grpc_slice*>(&key), nullptr);
+ if (value == nullptr) {
+ return nullptr;
+ }
+ Node* node = static_cast<Node*>(value);
+ // Move to the beginning.
+ Remove(node);
+ PushFront(node);
+ AssertInvariants();
+ return node;
+}
+
+void SslSessionLRUCache::Put(const char* key, SslSessionPtr session) {
grpc_core::MutexLock lock(&lock_);
- Node* node = FindLocked(grpc_slice_from_static_string(key));
- if (node != nullptr) {
- node->SetSession(std::move(session));
- return;
- }
- grpc_slice key_slice = grpc_slice_from_copied_string(key);
+ Node* node = FindLocked(grpc_slice_from_static_string(key));
+ if (node != nullptr) {
+ node->SetSession(std::move(session));
+ return;
+ }
+ grpc_slice key_slice = grpc_slice_from_copied_string(key);
node = new Node(key_slice, std::move(session));
- PushFront(node);
- entry_by_key_ = grpc_avl_add(entry_by_key_, node->AvlKey(), node, nullptr);
- AssertInvariants();
- if (use_order_list_size_ > capacity_) {
- GPR_ASSERT(use_order_list_tail_);
- node = use_order_list_tail_;
- Remove(node);
- // Order matters, key is destroyed after deleting node.
- entry_by_key_ = grpc_avl_remove(entry_by_key_, node->AvlKey(), nullptr);
+ PushFront(node);
+ entry_by_key_ = grpc_avl_add(entry_by_key_, node->AvlKey(), node, nullptr);
+ AssertInvariants();
+ if (use_order_list_size_ > capacity_) {
+ GPR_ASSERT(use_order_list_tail_);
+ node = use_order_list_tail_;
+ Remove(node);
+ // Order matters, key is destroyed after deleting node.
+ entry_by_key_ = grpc_avl_remove(entry_by_key_, node->AvlKey(), nullptr);
delete node;
- AssertInvariants();
- }
-}
-
-SslSessionPtr SslSessionLRUCache::Get(const char* key) {
+ AssertInvariants();
+ }
+}
+
+SslSessionPtr SslSessionLRUCache::Get(const char* key) {
grpc_core::MutexLock lock(&lock_);
- // Key is only used for lookups.
- grpc_slice key_slice = grpc_slice_from_static_string(key);
- Node* node = FindLocked(key_slice);
- if (node == nullptr) {
- return nullptr;
- }
- return node->CopySession();
-}
-
-void SslSessionLRUCache::Remove(SslSessionLRUCache::Node* node) {
- if (node->prev_ == nullptr) {
- use_order_list_head_ = node->next_;
- } else {
- node->prev_->next_ = node->next_;
- }
- if (node->next_ == nullptr) {
- use_order_list_tail_ = node->prev_;
- } else {
- node->next_->prev_ = node->prev_;
- }
- GPR_ASSERT(use_order_list_size_ >= 1);
- use_order_list_size_--;
-}
-
-void SslSessionLRUCache::PushFront(SslSessionLRUCache::Node* node) {
- if (use_order_list_head_ == nullptr) {
- use_order_list_head_ = node;
- use_order_list_tail_ = node;
- node->next_ = nullptr;
- node->prev_ = nullptr;
- } else {
- node->next_ = use_order_list_head_;
- node->next_->prev_ = node;
- use_order_list_head_ = node;
- node->prev_ = nullptr;
- }
- use_order_list_size_++;
-}
-
-#ifndef NDEBUG
-static size_t calculate_tree_size(grpc_avl_node* node) {
- if (node == nullptr) {
- return 0;
- }
- return 1 + calculate_tree_size(node->left) + calculate_tree_size(node->right);
-}
-
-void SslSessionLRUCache::AssertInvariants() {
- size_t size = 0;
- Node* prev = nullptr;
- Node* current = use_order_list_head_;
- while (current != nullptr) {
- size++;
- GPR_ASSERT(current->prev_ == prev);
- void* node = grpc_avl_get(entry_by_key_, current->AvlKey(), nullptr);
- GPR_ASSERT(node == current);
- prev = current;
- current = current->next_;
- }
- GPR_ASSERT(prev == use_order_list_tail_);
- GPR_ASSERT(size == use_order_list_size_);
- GPR_ASSERT(calculate_tree_size(entry_by_key_.root) == use_order_list_size_);
-}
-#else
-void SslSessionLRUCache::AssertInvariants() {}
-#endif
-
-} // namespace tsi
+ // Key is only used for lookups.
+ grpc_slice key_slice = grpc_slice_from_static_string(key);
+ Node* node = FindLocked(key_slice);
+ if (node == nullptr) {
+ return nullptr;
+ }
+ return node->CopySession();
+}
+
+void SslSessionLRUCache::Remove(SslSessionLRUCache::Node* node) {
+ if (node->prev_ == nullptr) {
+ use_order_list_head_ = node->next_;
+ } else {
+ node->prev_->next_ = node->next_;
+ }
+ if (node->next_ == nullptr) {
+ use_order_list_tail_ = node->prev_;
+ } else {
+ node->next_->prev_ = node->prev_;
+ }
+ GPR_ASSERT(use_order_list_size_ >= 1);
+ use_order_list_size_--;
+}
+
+void SslSessionLRUCache::PushFront(SslSessionLRUCache::Node* node) {
+ if (use_order_list_head_ == nullptr) {
+ use_order_list_head_ = node;
+ use_order_list_tail_ = node;
+ node->next_ = nullptr;
+ node->prev_ = nullptr;
+ } else {
+ node->next_ = use_order_list_head_;
+ node->next_->prev_ = node;
+ use_order_list_head_ = node;
+ node->prev_ = nullptr;
+ }
+ use_order_list_size_++;
+}
+
+#ifndef NDEBUG
+static size_t calculate_tree_size(grpc_avl_node* node) {
+ if (node == nullptr) {
+ return 0;
+ }
+ return 1 + calculate_tree_size(node->left) + calculate_tree_size(node->right);
+}
+
+void SslSessionLRUCache::AssertInvariants() {
+ size_t size = 0;
+ Node* prev = nullptr;
+ Node* current = use_order_list_head_;
+ while (current != nullptr) {
+ size++;
+ GPR_ASSERT(current->prev_ == prev);
+ void* node = grpc_avl_get(entry_by_key_, current->AvlKey(), nullptr);
+ GPR_ASSERT(node == current);
+ prev = current;
+ current = current->next_;
+ }
+ GPR_ASSERT(prev == use_order_list_tail_);
+ GPR_ASSERT(size == use_order_list_size_);
+ GPR_ASSERT(calculate_tree_size(entry_by_key_.root) == use_order_list_size_);
+}
+#else
+void SslSessionLRUCache::AssertInvariants() {}
+#endif
+
+} // namespace tsi
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 5d91af7b18d..cdda851847f 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
@@ -1,90 +1,90 @@
-/*
- *
- * 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_TSI_SSL_SESSION_CACHE_SSL_SESSION_CACHE_H
-#define GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_CACHE_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice.h>
-#include <grpc/support/sync.h>
-
-extern "C" {
-#include <openssl/ssl.h>
-}
-
-#include "src/core/lib/avl/avl.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/ref_counted.h"
-#include "src/core/tsi/ssl/session_cache/ssl_session.h"
-
-/// Cache for SSL sessions for sessions resumption.
-///
-/// Older sessions may be evicted from the cache using LRU policy if capacity
-/// limit is hit. All sessions are associated with some key, usually server
-/// name. Note that servers are required to share session ticket encryption keys
-/// in order for cache to be effective.
-///
-/// This class is thread safe.
-
-namespace tsi {
-
-class SslSessionLRUCache : public grpc_core::RefCounted<SslSessionLRUCache> {
- public:
- /// Create new LRU cache with the given capacity.
- static grpc_core::RefCountedPtr<SslSessionLRUCache> Create(size_t capacity) {
- return grpc_core::MakeRefCounted<SslSessionLRUCache>(capacity);
- }
-
+/*
+ *
+ * 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_TSI_SSL_SESSION_CACHE_SSL_SESSION_CACHE_H
+#define GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_CACHE_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice.h>
+#include <grpc/support/sync.h>
+
+extern "C" {
+#include <openssl/ssl.h>
+}
+
+#include "src/core/lib/avl/avl.h"
+#include "src/core/lib/gprpp/memory.h"
+#include "src/core/lib/gprpp/ref_counted.h"
+#include "src/core/tsi/ssl/session_cache/ssl_session.h"
+
+/// Cache for SSL sessions for sessions resumption.
+///
+/// Older sessions may be evicted from the cache using LRU policy if capacity
+/// limit is hit. All sessions are associated with some key, usually server
+/// name. Note that servers are required to share session ticket encryption keys
+/// in order for cache to be effective.
+///
+/// This class is thread safe.
+
+namespace tsi {
+
+class SslSessionLRUCache : public grpc_core::RefCounted<SslSessionLRUCache> {
+ public:
+ /// Create new LRU cache with the given capacity.
+ static grpc_core::RefCountedPtr<SslSessionLRUCache> Create(size_t capacity) {
+ return grpc_core::MakeRefCounted<SslSessionLRUCache>(capacity);
+ }
+
// 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;
-
- /// Returns current number of sessions in the cache.
- size_t Size();
- /// Add \a session in the cache using \a key. This operation may discard older
- /// sessions.
- void Put(const char* key, SslSessionPtr session);
- /// Returns the session from the cache associated with \a key or null if not
- /// found.
- SslSessionPtr Get(const char* key);
-
- private:
- class Node;
-
- Node* FindLocked(const grpc_slice& key);
- void Remove(Node* node);
- void PushFront(Node* node);
- void AssertInvariants();
-
- gpr_mu lock_;
- size_t capacity_;
-
- Node* use_order_list_head_ = nullptr;
- Node* use_order_list_tail_ = nullptr;
- size_t use_order_list_size_ = 0;
- grpc_avl entry_by_key_;
-};
-
-} // namespace tsi
-
-#endif /* GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_CACHE_H */
+ // Not copyable nor movable.
+ SslSessionLRUCache(const SslSessionLRUCache&) = delete;
+ SslSessionLRUCache& operator=(const SslSessionLRUCache&) = delete;
+
+ /// Returns current number of sessions in the cache.
+ size_t Size();
+ /// Add \a session in the cache using \a key. This operation may discard older
+ /// sessions.
+ void Put(const char* key, SslSessionPtr session);
+ /// Returns the session from the cache associated with \a key or null if not
+ /// found.
+ SslSessionPtr Get(const char* key);
+
+ private:
+ class Node;
+
+ Node* FindLocked(const grpc_slice& key);
+ void Remove(Node* node);
+ void PushFront(Node* node);
+ void AssertInvariants();
+
+ gpr_mu lock_;
+ size_t capacity_;
+
+ Node* use_order_list_head_ = nullptr;
+ Node* use_order_list_tail_ = nullptr;
+ size_t use_order_list_size_ = 0;
+ grpc_avl entry_by_key_;
+};
+
+} // namespace tsi
+
+#endif /* GRPC_CORE_TSI_SSL_SESSION_CACHE_SSL_SESSION_CACHE_H */
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 1df81396816..1e328559eb1 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
@@ -1,75 +1,75 @@
-/*
- *
- * 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/ssl/session_cache/ssl_session.h"
-
-#include <grpc/support/log.h>
-
-#ifndef OPENSSL_IS_BORINGSSL
-
-// OpenSSL invalidates SSL_SESSION on SSL destruction making it pointless
-// to cache sessions. The workaround is to serialize (relatively expensive)
-// session into binary blob and re-create it from blob on every handshake.
-// Note that it's safe to keep serialized session outside of SSL lifetime
-// as openssl performs all necessary validation while attempting to use a
-// session and creates a new one if something is wrong (e.g. server changed
-// set of allowed codecs).
-
-namespace tsi {
-namespace {
-
-class OpenSslCachedSession : public SslCachedSession {
- public:
- OpenSslCachedSession(SslSessionPtr session) {
- int size = i2d_SSL_SESSION(session.get(), nullptr);
- GPR_ASSERT(size > 0);
- grpc_slice slice = grpc_slice_malloc(size_t(size));
- unsigned char* start = GRPC_SLICE_START_PTR(slice);
- int second_size = i2d_SSL_SESSION(session.get(), &start);
- GPR_ASSERT(size == second_size);
- serialized_session_ = slice;
- }
-
- virtual ~OpenSslCachedSession() { grpc_slice_unref(serialized_session_); }
-
- SslSessionPtr CopySession() const override {
- const unsigned char* data = GRPC_SLICE_START_PTR(serialized_session_);
- size_t length = GRPC_SLICE_LENGTH(serialized_session_);
- SSL_SESSION* session = d2i_SSL_SESSION(nullptr, &data, length);
- if (session == nullptr) {
- return SslSessionPtr();
- }
- return SslSessionPtr(session);
- }
-
- private:
- grpc_slice serialized_session_;
-};
-
-} // 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 <grpc/support/port_platform.h>
+
+#include "src/core/tsi/ssl/session_cache/ssl_session.h"
+
+#include <grpc/support/log.h>
+
+#ifndef OPENSSL_IS_BORINGSSL
+
+// OpenSSL invalidates SSL_SESSION on SSL destruction making it pointless
+// to cache sessions. The workaround is to serialize (relatively expensive)
+// session into binary blob and re-create it from blob on every handshake.
+// Note that it's safe to keep serialized session outside of SSL lifetime
+// as openssl performs all necessary validation while attempting to use a
+// session and creates a new one if something is wrong (e.g. server changed
+// set of allowed codecs).
+
+namespace tsi {
+namespace {
+
+class OpenSslCachedSession : public SslCachedSession {
+ public:
+ OpenSslCachedSession(SslSessionPtr session) {
+ int size = i2d_SSL_SESSION(session.get(), nullptr);
+ GPR_ASSERT(size > 0);
+ grpc_slice slice = grpc_slice_malloc(size_t(size));
+ unsigned char* start = GRPC_SLICE_START_PTR(slice);
+ int second_size = i2d_SSL_SESSION(session.get(), &start);
+ GPR_ASSERT(size == second_size);
+ serialized_session_ = slice;
+ }
+
+ virtual ~OpenSslCachedSession() { grpc_slice_unref(serialized_session_); }
+
+ SslSessionPtr CopySession() const override {
+ const unsigned char* data = GRPC_SLICE_START_PTR(serialized_session_);
+ size_t length = GRPC_SLICE_LENGTH(serialized_session_);
+ SSL_SESSION* session = d2i_SSL_SESSION(nullptr, &data, length);
+ if (session == nullptr) {
+ return SslSessionPtr();
+ }
+ return SslSessionPtr(session);
+ }
+
+ private:
+ grpc_slice serialized_session_;
+};
+
+} // namespace
+
std::unique_ptr<SslCachedSession> SslCachedSession::Create(
- SslSessionPtr session) {
+ SslSessionPtr session) {
return y_absl::make_unique<OpenSslCachedSession>(std::move(session));
-}
-
-} // namespace tsi
-
-#endif /* OPENSSL_IS_BORINGSSL */
+}
+
+} // namespace tsi
+
+#endif /* OPENSSL_IS_BORINGSSL */
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 374f8e583ff..1f8cc8020ae 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc
+++ b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc
@@ -1,122 +1,122 @@
-/*
- *
- * 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/tsi/ssl_transport_security.h"
-
-#include <limits.h>
-#include <string.h>
-
-/* TODO(jboeuf): refactor inet_ntop into a portability header. */
-/* Note: for whomever reads this and tries to refactor this, this
- can't be in grpc, it has to be in gpr. */
-#ifdef GPR_WINDOWS
-#include <ws2tcpip.h>
-#else
-#include <arpa/inet.h>
-#include <sys/socket.h>
-#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 <grpc/support/port_platform.h>
+
+#include "src/core/tsi/ssl_transport_security.h"
+
+#include <limits.h>
+#include <string.h>
+
+/* TODO(jboeuf): refactor inet_ntop into a portability header. */
+/* Note: for whomever reads this and tries to refactor this, this
+ can't be in grpc, it has to be in gpr. */
+#ifdef GPR_WINDOWS
+#include <ws2tcpip.h>
+#else
+#include <arpa/inet.h>
+#include <sys/socket.h>
+#endif
+
#include <util/generic/string.h>
#include <grpc/grpc_security.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/thd_id.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/thd_id.h>
+
#include "y_absl/strings/match.h"
#include "y_absl/strings/string_view.h"
-extern "C" {
-#include <openssl/bio.h>
-#include <openssl/crypto.h> /* For OPENSSL_free */
+extern "C" {
+#include <openssl/bio.h>
+#include <openssl/crypto.h> /* For OPENSSL_free */
#include <openssl/engine.h>
-#include <openssl/err.h>
-#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/ssl.h>
#include <openssl/tls1.h>
-#include <openssl/x509.h>
-#include <openssl/x509v3.h>
-}
-
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/tsi/ssl/session_cache/ssl_session_cache.h"
-#include "src/core/tsi/ssl_types.h"
-#include "src/core/tsi/transport_security.h"
-
-/* --- Constants. ---*/
-
-#define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND 16384
-#define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND 1024
+#include <openssl/x509.h>
+#include <openssl/x509v3.h>
+}
+
+#include "src/core/lib/gpr/useful.h"
+#include "src/core/tsi/ssl/session_cache/ssl_session_cache.h"
+#include "src/core/tsi/ssl_types.h"
+#include "src/core/tsi/transport_security.h"
+
+/* --- Constants. ---*/
+
+#define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND 16384
+#define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND 1024
#define TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 1024
-
-/* Putting a macro like this and littering the source file with #if is really
- bad practice.
- TODO(jboeuf): refactor all the #if / #endif in a separate module. */
-#ifndef TSI_OPENSSL_ALPN_SUPPORT
-#define TSI_OPENSSL_ALPN_SUPPORT 1
-#endif
-
-/* TODO(jboeuf): I have not found a way to get this number dynamically from the
- SSL structure. This is what we would ultimately want though... */
-#define TSI_SSL_MAX_PROTECTION_OVERHEAD 100
-
-/* --- Structure definitions. ---*/
-
-struct tsi_ssl_root_certs_store {
- X509_STORE* store;
-};
-
-struct tsi_ssl_handshaker_factory {
- const tsi_ssl_handshaker_factory_vtable* vtable;
- gpr_refcount refcount;
-};
-
-struct tsi_ssl_client_handshaker_factory {
- tsi_ssl_handshaker_factory base;
- SSL_CTX* ssl_context;
- unsigned char* alpn_protocol_list;
- size_t alpn_protocol_list_length;
- grpc_core::RefCountedPtr<tsi::SslSessionLRUCache> session_cache;
-};
-
-struct tsi_ssl_server_handshaker_factory {
- /* Several contexts to support SNI.
- The tsi_peer array contains the subject names of the server certificates
- associated with the contexts at the same index. */
- tsi_ssl_handshaker_factory base;
- SSL_CTX** ssl_contexts;
- tsi_peer* ssl_context_x509_subject_names;
- size_t ssl_context_count;
- unsigned char* alpn_protocol_list;
- size_t alpn_protocol_list_length;
-};
-
+
+/* Putting a macro like this and littering the source file with #if is really
+ bad practice.
+ TODO(jboeuf): refactor all the #if / #endif in a separate module. */
+#ifndef TSI_OPENSSL_ALPN_SUPPORT
+#define TSI_OPENSSL_ALPN_SUPPORT 1
+#endif
+
+/* TODO(jboeuf): I have not found a way to get this number dynamically from the
+ SSL structure. This is what we would ultimately want though... */
+#define TSI_SSL_MAX_PROTECTION_OVERHEAD 100
+
+/* --- Structure definitions. ---*/
+
+struct tsi_ssl_root_certs_store {
+ X509_STORE* store;
+};
+
+struct tsi_ssl_handshaker_factory {
+ const tsi_ssl_handshaker_factory_vtable* vtable;
+ gpr_refcount refcount;
+};
+
+struct tsi_ssl_client_handshaker_factory {
+ tsi_ssl_handshaker_factory base;
+ SSL_CTX* ssl_context;
+ unsigned char* alpn_protocol_list;
+ size_t alpn_protocol_list_length;
+ grpc_core::RefCountedPtr<tsi::SslSessionLRUCache> session_cache;
+};
+
+struct tsi_ssl_server_handshaker_factory {
+ /* Several contexts to support SNI.
+ The tsi_peer array contains the subject names of the server certificates
+ associated with the contexts at the same index. */
+ tsi_ssl_handshaker_factory base;
+ SSL_CTX** ssl_contexts;
+ tsi_peer* ssl_context_x509_subject_names;
+ size_t ssl_context_count;
+ unsigned char* alpn_protocol_list;
+ size_t alpn_protocol_list_length;
+};
+
struct tsi_ssl_handshaker {
- tsi_handshaker base;
- SSL* ssl;
- BIO* network_io;
- tsi_result result;
+ tsi_handshaker base;
+ SSL* ssl;
+ BIO* network_io;
+ tsi_result result;
unsigned char* outgoing_bytes_buffer;
size_t outgoing_bytes_buffer_size;
- tsi_ssl_handshaker_factory* factory_ref;
+ tsi_ssl_handshaker_factory* factory_ref;
};
struct tsi_ssl_handshaker_result {
tsi_handshaker_result base;
@@ -126,16 +126,16 @@ struct tsi_ssl_handshaker_result {
size_t unused_bytes_size;
};
struct tsi_ssl_frame_protector {
- tsi_frame_protector base;
- SSL* ssl;
- BIO* network_io;
- unsigned char* buffer;
- size_t buffer_size;
- size_t buffer_offset;
+ tsi_frame_protector base;
+ SSL* ssl;
+ BIO* network_io;
+ unsigned char* buffer;
+ size_t buffer_size;
+ size_t buffer_offset;
};
-/* --- Library Initialization. ---*/
-
-static gpr_once g_init_openssl_once = GPR_ONCE_INIT;
+/* --- Library Initialization. ---*/
+
+static gpr_once g_init_openssl_once = GPR_ONCE_INIT;
static int g_ssl_ctx_ex_factory_index = -1;
static const unsigned char kSslSessionIdContext[] = {'g', 'r', 'p', 'c'};
#ifndef OPENSSL_IS_BORINGSSL
@@ -143,31 +143,31 @@ static const char kSslEnginePrefix[] = "engine:";
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000
-static gpr_mu* g_openssl_mutexes = nullptr;
-static void openssl_locking_cb(int mode, int type, const char* file,
- int line) GRPC_UNUSED;
-static unsigned long openssl_thread_id_cb(void) GRPC_UNUSED;
-
-static void openssl_locking_cb(int mode, int type, const char* file, int line) {
- if (mode & CRYPTO_LOCK) {
- gpr_mu_lock(&g_openssl_mutexes[type]);
- } else {
- gpr_mu_unlock(&g_openssl_mutexes[type]);
- }
-}
-
-static unsigned long openssl_thread_id_cb(void) {
- return static_cast<unsigned long>(gpr_thd_currentid());
-}
+static gpr_mu* g_openssl_mutexes = nullptr;
+static void openssl_locking_cb(int mode, int type, const char* file,
+ int line) GRPC_UNUSED;
+static unsigned long openssl_thread_id_cb(void) GRPC_UNUSED;
+
+static void openssl_locking_cb(int mode, int type, const char* file, int line) {
+ if (mode & CRYPTO_LOCK) {
+ gpr_mu_lock(&g_openssl_mutexes[type]);
+ } else {
+ gpr_mu_unlock(&g_openssl_mutexes[type]);
+ }
+}
+
+static unsigned long openssl_thread_id_cb(void) {
+ return static_cast<unsigned long>(gpr_thd_currentid());
+}
#endif
-
-static void init_openssl(void) {
+
+static void init_openssl(void) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000
OPENSSL_init_ssl(0, nullptr);
#else
- SSL_library_init();
- SSL_load_error_strings();
- OpenSSL_add_all_algorithms();
+ SSL_library_init();
+ SSL_load_error_strings();
+ OpenSSL_add_all_algorithms();
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000
if (!CRYPTO_get_locking_callback()) {
@@ -182,13 +182,13 @@ static void init_openssl(void) {
CRYPTO_set_id_callback(openssl_thread_id_cb);
} else {
gpr_log(GPR_INFO, "OpenSSL callback has already been set.");
- }
+ }
#endif
- g_ssl_ctx_ex_factory_index =
- SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
- GPR_ASSERT(g_ssl_ctx_ex_factory_index != -1);
-}
-
+ g_ssl_ctx_ex_factory_index =
+ SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
+ GPR_ASSERT(g_ssl_ctx_ex_factory_index != -1);
+}
+
static void do_nothing(void) {}
extern "C" void grpc_dont_init_openssl(void) {
@@ -199,175 +199,175 @@ extern "C" void grpc_init_openssl(void) {
gpr_once_init(&g_init_openssl_once, init_openssl);
}
-/* --- Ssl utils. ---*/
-
-static const char* ssl_error_string(int error) {
- switch (error) {
- case SSL_ERROR_NONE:
- return "SSL_ERROR_NONE";
- case SSL_ERROR_ZERO_RETURN:
- return "SSL_ERROR_ZERO_RETURN";
- case SSL_ERROR_WANT_READ:
- return "SSL_ERROR_WANT_READ";
- case SSL_ERROR_WANT_WRITE:
- return "SSL_ERROR_WANT_WRITE";
- case SSL_ERROR_WANT_CONNECT:
- return "SSL_ERROR_WANT_CONNECT";
- case SSL_ERROR_WANT_ACCEPT:
- return "SSL_ERROR_WANT_ACCEPT";
- case SSL_ERROR_WANT_X509_LOOKUP:
- return "SSL_ERROR_WANT_X509_LOOKUP";
- case SSL_ERROR_SYSCALL:
- return "SSL_ERROR_SYSCALL";
- case SSL_ERROR_SSL:
- return "SSL_ERROR_SSL";
- default:
- return "Unknown 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) {
+/* --- Ssl utils. ---*/
+
+static const char* ssl_error_string(int error) {
+ switch (error) {
+ case SSL_ERROR_NONE:
+ return "SSL_ERROR_NONE";
+ case SSL_ERROR_ZERO_RETURN:
+ return "SSL_ERROR_ZERO_RETURN";
+ case SSL_ERROR_WANT_READ:
+ return "SSL_ERROR_WANT_READ";
+ case SSL_ERROR_WANT_WRITE:
+ return "SSL_ERROR_WANT_WRITE";
+ case SSL_ERROR_WANT_CONNECT:
+ return "SSL_ERROR_WANT_CONNECT";
+ case SSL_ERROR_WANT_ACCEPT:
+ return "SSL_ERROR_WANT_ACCEPT";
+ case SSL_ERROR_WANT_X509_LOOKUP:
+ return "SSL_ERROR_WANT_X509_LOOKUP";
+ case SSL_ERROR_SYSCALL:
+ return "SSL_ERROR_SYSCALL";
+ case SSL_ERROR_SSL:
+ return "SSL_ERROR_SSL";
+ default:
+ return "Unknown 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)) {
- gpr_log(GPR_INFO, "%20.20s - %30.30s - %5.10s", msg,
- SSL_state_string_long(ssl), SSL_state_string(ssl));
- }
-}
-
-/* Used for debugging. TODO(jboeuf): Remove when code is mature enough. */
-static void ssl_info_callback(const SSL* ssl, int where, int ret) {
- if (ret == 0) {
+ gpr_log(GPR_INFO, "%20.20s - %30.30s - %5.10s", msg,
+ SSL_state_string_long(ssl), SSL_state_string(ssl));
+ }
+}
+
+/* Used for debugging. TODO(jboeuf): Remove when code is mature enough. */
+static void ssl_info_callback(const SSL* ssl, int where, int ret) {
+ if (ret == 0) {
gpr_log(GPR_ERROR, "ssl_info_callback: error occurred.\n");
- return;
- }
-
- ssl_log_where_info(ssl, where, SSL_CB_LOOP, "LOOP");
- ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_START, "HANDSHAKE START");
- ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_DONE, "HANDSHAKE DONE");
-}
-
-/* Returns 1 if name looks like an IP address, 0 otherwise.
- This is a very rough heuristic, and only handles IPv6 in hexadecimal form. */
+ return;
+ }
+
+ ssl_log_where_info(ssl, where, SSL_CB_LOOP, "LOOP");
+ ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_START, "HANDSHAKE START");
+ ssl_log_where_info(ssl, where, SSL_CB_HANDSHAKE_DONE, "HANDSHAKE DONE");
+}
+
+/* Returns 1 if name looks like an IP address, 0 otherwise.
+ This is a very rough heuristic, and only handles IPv6 in hexadecimal form. */
static int looks_like_ip_address(y_absl::string_view name) {
- size_t dot_count = 0;
- size_t num_size = 0;
+ size_t dot_count = 0;
+ size_t num_size = 0;
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;
- }
- if (name[i] >= '0' && name[i] <= '9') {
- if (num_size > 3) return 0;
- num_size++;
- } else if (name[i] == '.') {
- if (dot_count > 3 || num_size == 0) return 0;
- dot_count++;
- num_size = 0;
- } else {
- return 0;
- }
- }
- if (dot_count < 3 || num_size == 0) return 0;
- return 1;
-}
-
-/* Gets the subject CN from an X509 cert. */
-static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
- size_t* utf8_size) {
- int common_name_index = -1;
- X509_NAME_ENTRY* common_name_entry = nullptr;
- ASN1_STRING* common_name_asn1 = nullptr;
- X509_NAME* subject_name = X509_get_subject_name(cert);
- int utf8_returned_size = 0;
- if (subject_name == nullptr) {
+ if (name[i] == ':') {
+ /* IPv6 Address in hexadecimal form, : is not allowed in DNS names. */
+ return 1;
+ }
+ if (name[i] >= '0' && name[i] <= '9') {
+ if (num_size > 3) return 0;
+ num_size++;
+ } else if (name[i] == '.') {
+ if (dot_count > 3 || num_size == 0) return 0;
+ dot_count++;
+ num_size = 0;
+ } else {
+ return 0;
+ }
+ }
+ if (dot_count < 3 || num_size == 0) return 0;
+ return 1;
+}
+
+/* Gets the subject CN from an X509 cert. */
+static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
+ size_t* utf8_size) {
+ int common_name_index = -1;
+ X509_NAME_ENTRY* common_name_entry = nullptr;
+ ASN1_STRING* common_name_asn1 = nullptr;
+ X509_NAME* subject_name = X509_get_subject_name(cert);
+ int utf8_returned_size = 0;
+ if (subject_name == nullptr) {
gpr_log(GPR_INFO, "Could not get subject name from certificate.");
- return TSI_NOT_FOUND;
- }
- common_name_index =
- X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
- if (common_name_index == -1) {
+ return TSI_NOT_FOUND;
+ }
+ common_name_index =
+ X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
+ if (common_name_index == -1) {
gpr_log(GPR_INFO, "Could not get common name of subject from certificate.");
- return TSI_NOT_FOUND;
- }
- common_name_entry = X509_NAME_get_entry(subject_name, common_name_index);
- if (common_name_entry == nullptr) {
- gpr_log(GPR_ERROR, "Could not get common name entry from certificate.");
- return TSI_INTERNAL_ERROR;
- }
- common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
- if (common_name_asn1 == nullptr) {
- gpr_log(GPR_ERROR,
- "Could not get common name entry asn1 from certificate.");
- return TSI_INTERNAL_ERROR;
- }
- utf8_returned_size = ASN1_STRING_to_UTF8(utf8, common_name_asn1);
- if (utf8_returned_size < 0) {
- gpr_log(GPR_ERROR, "Could not extract utf8 from asn1 string.");
- return TSI_OUT_OF_RESOURCES;
- }
- *utf8_size = static_cast<size_t>(utf8_returned_size);
- return TSI_OK;
-}
-
-/* Gets the subject CN of an X509 cert as a tsi_peer_property. */
-static tsi_result peer_property_from_x509_common_name(
- X509* cert, tsi_peer_property* property) {
- unsigned char* common_name;
- size_t common_name_size;
- tsi_result result =
- ssl_get_x509_common_name(cert, &common_name, &common_name_size);
- if (result != TSI_OK) {
- if (result == TSI_NOT_FOUND) {
- common_name = nullptr;
- common_name_size = 0;
- } else {
- return result;
- }
- }
- result = tsi_construct_string_peer_property(
- TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY,
- common_name == nullptr ? "" : reinterpret_cast<const char*>(common_name),
- common_name_size, property);
- OPENSSL_free(common_name);
- return result;
-}
-
-/* Gets the X509 cert in PEM format as a tsi_peer_property. */
-static tsi_result add_pem_certificate(X509* cert, tsi_peer_property* property) {
- BIO* bio = BIO_new(BIO_s_mem());
- if (!PEM_write_bio_X509(bio, cert)) {
- BIO_free(bio);
- return TSI_INTERNAL_ERROR;
- }
- char* contents;
- long len = BIO_get_mem_data(bio, &contents);
- if (len <= 0) {
- BIO_free(bio);
- return TSI_INTERNAL_ERROR;
- }
- tsi_result result = tsi_construct_string_peer_property(
- TSI_X509_PEM_CERT_PROPERTY, (const char*)contents,
- static_cast<size_t>(len), property);
- BIO_free(bio);
- return result;
-}
-
-/* Gets the subject SANs from an X509 cert as a tsi_peer_property. */
-static tsi_result add_subject_alt_names_properties_to_peer(
- tsi_peer* peer, GENERAL_NAMES* subject_alt_names,
+ return TSI_NOT_FOUND;
+ }
+ common_name_entry = X509_NAME_get_entry(subject_name, common_name_index);
+ if (common_name_entry == nullptr) {
+ gpr_log(GPR_ERROR, "Could not get common name entry from certificate.");
+ return TSI_INTERNAL_ERROR;
+ }
+ common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
+ if (common_name_asn1 == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Could not get common name entry asn1 from certificate.");
+ return TSI_INTERNAL_ERROR;
+ }
+ utf8_returned_size = ASN1_STRING_to_UTF8(utf8, common_name_asn1);
+ if (utf8_returned_size < 0) {
+ gpr_log(GPR_ERROR, "Could not extract utf8 from asn1 string.");
+ return TSI_OUT_OF_RESOURCES;
+ }
+ *utf8_size = static_cast<size_t>(utf8_returned_size);
+ return TSI_OK;
+}
+
+/* Gets the subject CN of an X509 cert as a tsi_peer_property. */
+static tsi_result peer_property_from_x509_common_name(
+ X509* cert, tsi_peer_property* property) {
+ unsigned char* common_name;
+ size_t common_name_size;
+ tsi_result result =
+ ssl_get_x509_common_name(cert, &common_name, &common_name_size);
+ if (result != TSI_OK) {
+ if (result == TSI_NOT_FOUND) {
+ common_name = nullptr;
+ common_name_size = 0;
+ } else {
+ return result;
+ }
+ }
+ result = tsi_construct_string_peer_property(
+ TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY,
+ common_name == nullptr ? "" : reinterpret_cast<const char*>(common_name),
+ common_name_size, property);
+ OPENSSL_free(common_name);
+ return result;
+}
+
+/* Gets the X509 cert in PEM format as a tsi_peer_property. */
+static tsi_result add_pem_certificate(X509* cert, tsi_peer_property* property) {
+ BIO* bio = BIO_new(BIO_s_mem());
+ if (!PEM_write_bio_X509(bio, cert)) {
+ BIO_free(bio);
+ return TSI_INTERNAL_ERROR;
+ }
+ char* contents;
+ long len = BIO_get_mem_data(bio, &contents);
+ if (len <= 0) {
+ BIO_free(bio);
+ return TSI_INTERNAL_ERROR;
+ }
+ tsi_result result = tsi_construct_string_peer_property(
+ TSI_X509_PEM_CERT_PROPERTY, (const char*)contents,
+ static_cast<size_t>(len), property);
+ BIO_free(bio);
+ return result;
+}
+
+/* Gets the subject SANs from an X509 cert as a tsi_peer_property. */
+static tsi_result add_subject_alt_names_properties_to_peer(
+ tsi_peer* peer, GENERAL_NAMES* subject_alt_names,
size_t subject_alt_name_count, int* current_insert_index) {
- size_t i;
- tsi_result result = TSI_OK;
-
- 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));
+ size_t i;
+ tsi_result result = TSI_OK;
+
+ 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) {
- unsigned char* name = nullptr;
- int name_size;
+ 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) {
@@ -376,14 +376,14 @@ static tsi_result add_subject_alt_names_properties_to_peer(
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;
- break;
- }
- result = tsi_construct_string_peer_property(
- TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY,
- reinterpret_cast<const char*>(name), static_cast<size_t>(name_size),
+ if (name_size < 0) {
+ gpr_log(GPR_ERROR, "Could not get utf8 from asn1 string.");
+ result = TSI_INTERNAL_ERROR;
+ break;
+ }
+ result = tsi_construct_string_peer_property(
+ TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY,
+ reinterpret_cast<const char*>(name), static_cast<size_t>(name_size),
&peer->properties[(*current_insert_index)++]);
if (result != TSI_OK) {
OPENSSL_free(name);
@@ -395,53 +395,53 @@ static tsi_result add_subject_alt_names_properties_to_peer(
static_cast<size_t>(name_size),
&peer->properties[(*current_insert_index)++]);
}
- OPENSSL_free(name);
- } else if (subject_alt_name->type == GEN_IPADD) {
- char ntop_buf[INET6_ADDRSTRLEN];
- int af;
-
- if (subject_alt_name->d.iPAddress->length == 4) {
- af = AF_INET;
- } else if (subject_alt_name->d.iPAddress->length == 16) {
- af = AF_INET6;
- } else {
- gpr_log(GPR_ERROR, "SAN IP Address contained invalid IP");
- result = TSI_INTERNAL_ERROR;
- break;
- }
- const char* name = inet_ntop(af, subject_alt_name->d.iPAddress->data,
- ntop_buf, INET6_ADDRSTRLEN);
- if (name == nullptr) {
- gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet.");
- result = TSI_INTERNAL_ERROR;
- break;
- }
-
- result = tsi_construct_string_peer_property_from_cstring(
- TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, name,
+ OPENSSL_free(name);
+ } else if (subject_alt_name->type == GEN_IPADD) {
+ char ntop_buf[INET6_ADDRSTRLEN];
+ int af;
+
+ if (subject_alt_name->d.iPAddress->length == 4) {
+ af = AF_INET;
+ } else if (subject_alt_name->d.iPAddress->length == 16) {
+ af = AF_INET6;
+ } else {
+ gpr_log(GPR_ERROR, "SAN IP Address contained invalid IP");
+ result = TSI_INTERNAL_ERROR;
+ break;
+ }
+ const char* name = inet_ntop(af, subject_alt_name->d.iPAddress->data,
+ ntop_buf, INET6_ADDRSTRLEN);
+ if (name == nullptr) {
+ gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet.");
+ result = TSI_INTERNAL_ERROR;
+ break;
+ }
+
+ result = tsi_construct_string_peer_property_from_cstring(
+ TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, name,
&peer->properties[(*current_insert_index)++]);
- }
- if (result != TSI_OK) break;
- }
- return result;
-}
-
-/* Gets information about the peer's X509 cert as a tsi_peer object. */
-static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
- tsi_peer* peer) {
- /* TODO(jboeuf): Maybe add more properties. */
- GENERAL_NAMES* subject_alt_names = static_cast<GENERAL_NAMES*>(
- X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
- int subject_alt_name_count =
- (subject_alt_names != nullptr)
- ? static_cast<int>(sk_GENERAL_NAME_num(subject_alt_names))
- : 0;
- size_t property_count;
- tsi_result result;
- GPR_ASSERT(subject_alt_name_count >= 0);
- property_count = (include_certificate_type ? static_cast<size_t>(1) : 0) +
- 2 /* common name, certificate */ +
- static_cast<size_t>(subject_alt_name_count);
+ }
+ if (result != TSI_OK) break;
+ }
+ return result;
+}
+
+/* Gets information about the peer's X509 cert as a tsi_peer object. */
+static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
+ tsi_peer* peer) {
+ /* TODO(jboeuf): Maybe add more properties. */
+ GENERAL_NAMES* subject_alt_names = static_cast<GENERAL_NAMES*>(
+ X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
+ int subject_alt_name_count =
+ (subject_alt_names != nullptr)
+ ? static_cast<int>(sk_GENERAL_NAME_num(subject_alt_names))
+ : 0;
+ size_t property_count;
+ tsi_result result;
+ GPR_ASSERT(subject_alt_name_count >= 0);
+ property_count = (include_certificate_type ? static_cast<size_t>(1) : 0) +
+ 2 /* common name, certificate */ +
+ static_cast<size_t>(subject_alt_name_count);
for (int 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));
@@ -449,158 +449,158 @@ static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
property_count += 1;
}
}
- result = tsi_construct_peer(property_count, peer);
- if (result != TSI_OK) return result;
+ result = tsi_construct_peer(property_count, peer);
+ if (result != TSI_OK) return result;
int current_insert_index = 0;
- do {
- if (include_certificate_type) {
- result = tsi_construct_string_peer_property_from_cstring(
- TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_X509_CERTIFICATE_TYPE,
+ do {
+ if (include_certificate_type) {
+ result = tsi_construct_string_peer_property_from_cstring(
+ TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_X509_CERTIFICATE_TYPE,
&peer->properties[current_insert_index++]);
- if (result != TSI_OK) break;
- }
- result = peer_property_from_x509_common_name(
+ if (result != TSI_OK) break;
+ }
+ result = peer_property_from_x509_common_name(
cert, &peer->properties[current_insert_index++]);
- if (result != TSI_OK) break;
-
+ if (result != TSI_OK) break;
+
result =
add_pem_certificate(cert, &peer->properties[current_insert_index++]);
- if (result != TSI_OK) break;
-
- if (subject_alt_name_count != 0) {
- result = add_subject_alt_names_properties_to_peer(
+ if (result != TSI_OK) break;
+
+ if (subject_alt_name_count != 0) {
+ result = add_subject_alt_names_properties_to_peer(
peer, subject_alt_names, static_cast<size_t>(subject_alt_name_count),
&current_insert_index);
- if (result != TSI_OK) break;
- }
- } while (0);
-
- if (subject_alt_names != nullptr) {
- sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free);
- }
- if (result != TSI_OK) tsi_peer_destruct(peer);
+ if (result != TSI_OK) break;
+ }
+ } while (0);
+
+ if (subject_alt_names != nullptr) {
+ sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free);
+ }
+ if (result != TSI_OK) tsi_peer_destruct(peer);
GPR_ASSERT((int)peer->property_count == current_insert_index);
- return result;
-}
-
-/* Logs the SSL error stack. */
-static void log_ssl_error_stack(void) {
- unsigned long err;
- while ((err = ERR_get_error()) != 0) {
- char details[256];
- ERR_error_string_n(static_cast<uint32_t>(err), details, sizeof(details));
- gpr_log(GPR_ERROR, "%s", details);
- }
-}
-
-/* Performs an SSL_read and handle errors. */
-static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size) {
- int read_from_ssl;
- GPR_ASSERT(*unprotected_bytes_size <= INT_MAX);
- read_from_ssl = SSL_read(ssl, unprotected_bytes,
- static_cast<int>(*unprotected_bytes_size));
- if (read_from_ssl <= 0) {
- read_from_ssl = SSL_get_error(ssl, read_from_ssl);
- switch (read_from_ssl) {
- case SSL_ERROR_ZERO_RETURN: /* Received a close_notify alert. */
- case SSL_ERROR_WANT_READ: /* We need more data to finish the frame. */
- *unprotected_bytes_size = 0;
- return TSI_OK;
- case SSL_ERROR_WANT_WRITE:
- gpr_log(
- GPR_ERROR,
- "Peer tried to renegotiate SSL connection. This is unsupported.");
- return TSI_UNIMPLEMENTED;
- case SSL_ERROR_SSL:
- gpr_log(GPR_ERROR, "Corruption detected.");
- log_ssl_error_stack();
- return TSI_DATA_CORRUPTED;
- default:
- gpr_log(GPR_ERROR, "SSL_read failed with error %s.",
- ssl_error_string(read_from_ssl));
- return TSI_PROTOCOL_FAILURE;
- }
- }
- *unprotected_bytes_size = static_cast<size_t>(read_from_ssl);
- return TSI_OK;
-}
-
-/* Performs an SSL_write and handle errors. */
-static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
- size_t unprotected_bytes_size) {
- int ssl_write_result;
- GPR_ASSERT(unprotected_bytes_size <= INT_MAX);
- ssl_write_result = SSL_write(ssl, unprotected_bytes,
- static_cast<int>(unprotected_bytes_size));
- if (ssl_write_result < 0) {
- ssl_write_result = SSL_get_error(ssl, ssl_write_result);
- if (ssl_write_result == SSL_ERROR_WANT_READ) {
- gpr_log(GPR_ERROR,
- "Peer tried to renegotiate SSL connection. This is unsupported.");
- return TSI_UNIMPLEMENTED;
- } else {
- gpr_log(GPR_ERROR, "SSL_write failed with error %s.",
- ssl_error_string(ssl_write_result));
- return TSI_INTERNAL_ERROR;
- }
- }
- return TSI_OK;
-}
-
-/* Loads an in-memory PEM certificate chain into the SSL context. */
-static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context,
- const char* pem_cert_chain,
- size_t pem_cert_chain_size) {
- tsi_result result = TSI_OK;
- X509* certificate = nullptr;
- BIO* pem;
- GPR_ASSERT(pem_cert_chain_size <= INT_MAX);
- pem = BIO_new_mem_buf((void*)pem_cert_chain,
- static_cast<int>(pem_cert_chain_size));
- if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
-
- do {
- certificate = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
- if (certificate == nullptr) {
- result = TSI_INVALID_ARGUMENT;
- break;
- }
- if (!SSL_CTX_use_certificate(context, certificate)) {
- result = TSI_INVALID_ARGUMENT;
- break;
- }
- while (1) {
- X509* certificate_authority =
- PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
- if (certificate_authority == nullptr) {
- ERR_clear_error();
- break; /* Done reading. */
- }
- if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
- X509_free(certificate_authority);
- result = TSI_INVALID_ARGUMENT;
- break;
- }
- /* We don't need to free certificate_authority as its ownership has been
+ return result;
+}
+
+/* Logs the SSL error stack. */
+static void log_ssl_error_stack(void) {
+ unsigned long err;
+ while ((err = ERR_get_error()) != 0) {
+ char details[256];
+ ERR_error_string_n(static_cast<uint32_t>(err), details, sizeof(details));
+ gpr_log(GPR_ERROR, "%s", details);
+ }
+}
+
+/* Performs an SSL_read and handle errors. */
+static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size) {
+ int read_from_ssl;
+ GPR_ASSERT(*unprotected_bytes_size <= INT_MAX);
+ read_from_ssl = SSL_read(ssl, unprotected_bytes,
+ static_cast<int>(*unprotected_bytes_size));
+ if (read_from_ssl <= 0) {
+ read_from_ssl = SSL_get_error(ssl, read_from_ssl);
+ switch (read_from_ssl) {
+ case SSL_ERROR_ZERO_RETURN: /* Received a close_notify alert. */
+ case SSL_ERROR_WANT_READ: /* We need more data to finish the frame. */
+ *unprotected_bytes_size = 0;
+ return TSI_OK;
+ case SSL_ERROR_WANT_WRITE:
+ gpr_log(
+ GPR_ERROR,
+ "Peer tried to renegotiate SSL connection. This is unsupported.");
+ return TSI_UNIMPLEMENTED;
+ case SSL_ERROR_SSL:
+ gpr_log(GPR_ERROR, "Corruption detected.");
+ log_ssl_error_stack();
+ return TSI_DATA_CORRUPTED;
+ default:
+ gpr_log(GPR_ERROR, "SSL_read failed with error %s.",
+ ssl_error_string(read_from_ssl));
+ return TSI_PROTOCOL_FAILURE;
+ }
+ }
+ *unprotected_bytes_size = static_cast<size_t>(read_from_ssl);
+ return TSI_OK;
+}
+
+/* Performs an SSL_write and handle errors. */
+static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
+ size_t unprotected_bytes_size) {
+ int ssl_write_result;
+ GPR_ASSERT(unprotected_bytes_size <= INT_MAX);
+ ssl_write_result = SSL_write(ssl, unprotected_bytes,
+ static_cast<int>(unprotected_bytes_size));
+ if (ssl_write_result < 0) {
+ ssl_write_result = SSL_get_error(ssl, ssl_write_result);
+ if (ssl_write_result == SSL_ERROR_WANT_READ) {
+ gpr_log(GPR_ERROR,
+ "Peer tried to renegotiate SSL connection. This is unsupported.");
+ return TSI_UNIMPLEMENTED;
+ } else {
+ gpr_log(GPR_ERROR, "SSL_write failed with error %s.",
+ ssl_error_string(ssl_write_result));
+ return TSI_INTERNAL_ERROR;
+ }
+ }
+ return TSI_OK;
+}
+
+/* Loads an in-memory PEM certificate chain into the SSL context. */
+static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context,
+ const char* pem_cert_chain,
+ size_t pem_cert_chain_size) {
+ tsi_result result = TSI_OK;
+ X509* certificate = nullptr;
+ BIO* pem;
+ GPR_ASSERT(pem_cert_chain_size <= INT_MAX);
+ pem = BIO_new_mem_buf((void*)pem_cert_chain,
+ static_cast<int>(pem_cert_chain_size));
+ if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
+
+ do {
+ certificate = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
+ if (certificate == nullptr) {
+ result = TSI_INVALID_ARGUMENT;
+ break;
+ }
+ if (!SSL_CTX_use_certificate(context, certificate)) {
+ result = TSI_INVALID_ARGUMENT;
+ break;
+ }
+ while (1) {
+ X509* certificate_authority =
+ PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
+ if (certificate_authority == nullptr) {
+ ERR_clear_error();
+ break; /* Done reading. */
+ }
+ if (!SSL_CTX_add_extra_chain_cert(context, certificate_authority)) {
+ X509_free(certificate_authority);
+ result = TSI_INVALID_ARGUMENT;
+ 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.
- */
- }
- } while (0);
-
- if (certificate != nullptr) X509_free(certificate);
- BIO_free(pem);
- return result;
-}
-
+ */
+ }
+ } while (0);
+
+ if (certificate != nullptr) X509_free(certificate);
+ BIO_free(pem);
+ return result;
+}
+
#ifndef OPENSSL_IS_BORINGSSL
static tsi_result ssl_ctx_use_engine_private_key(SSL_CTX* context,
const char* pem_key,
size_t pem_key_size) {
- tsi_result result = TSI_OK;
- EVP_PKEY* private_key = nullptr;
+ tsi_result result = TSI_OK;
+ EVP_PKEY* private_key = nullptr;
ENGINE* engine = nullptr;
char* engine_name = nullptr;
// Parse key which is in following format engine:<engine_id>:<key_id>
@@ -675,26 +675,26 @@ static tsi_result ssl_ctx_use_pem_private_key(SSL_CTX* context,
size_t pem_key_size) {
tsi_result result = TSI_OK;
EVP_PKEY* private_key = nullptr;
- BIO* pem;
- GPR_ASSERT(pem_key_size <= INT_MAX);
- pem = BIO_new_mem_buf((void*)pem_key, static_cast<int>(pem_key_size));
- if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
- do {
- private_key = PEM_read_bio_PrivateKey(pem, nullptr, nullptr, (void*)"");
- if (private_key == nullptr) {
- result = TSI_INVALID_ARGUMENT;
- break;
- }
- if (!SSL_CTX_use_PrivateKey(context, private_key)) {
- result = TSI_INVALID_ARGUMENT;
- break;
- }
- } while (0);
- if (private_key != nullptr) EVP_PKEY_free(private_key);
- BIO_free(pem);
- return result;
-}
-
+ BIO* pem;
+ GPR_ASSERT(pem_key_size <= INT_MAX);
+ pem = BIO_new_mem_buf((void*)pem_key, static_cast<int>(pem_key_size));
+ if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
+ do {
+ private_key = PEM_read_bio_PrivateKey(pem, nullptr, nullptr, (void*)"");
+ if (private_key == nullptr) {
+ result = TSI_INVALID_ARGUMENT;
+ break;
+ }
+ if (!SSL_CTX_use_PrivateKey(context, private_key)) {
+ result = TSI_INVALID_ARGUMENT;
+ break;
+ }
+ } while (0);
+ if (private_key != nullptr) EVP_PKEY_free(private_key);
+ BIO_free(pem);
+ return result;
+}
+
/* Loads an in-memory PEM private key into the SSL context. */
static tsi_result ssl_ctx_use_private_key(SSL_CTX* context, const char* pem_key,
size_t pem_key_size) {
@@ -709,49 +709,49 @@ static tsi_result ssl_ctx_use_private_key(SSL_CTX* context, const char* pem_key,
}
}
-/* Loads in-memory PEM verification certs into the SSL context and optionally
- returns the verification cert names (root_names can be NULL). */
-static tsi_result x509_store_load_certs(X509_STORE* cert_store,
- const char* pem_roots,
- size_t pem_roots_size,
- STACK_OF(X509_NAME) * *root_names) {
- tsi_result result = TSI_OK;
- size_t num_roots = 0;
- X509* root = nullptr;
- X509_NAME* root_name = nullptr;
- BIO* pem;
- GPR_ASSERT(pem_roots_size <= INT_MAX);
- pem = BIO_new_mem_buf((void*)pem_roots, static_cast<int>(pem_roots_size));
- if (cert_store == nullptr) return TSI_INVALID_ARGUMENT;
- if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
- if (root_names != nullptr) {
- *root_names = sk_X509_NAME_new_null();
- if (*root_names == nullptr) return TSI_OUT_OF_RESOURCES;
- }
-
- while (1) {
- root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
- if (root == nullptr) {
- ERR_clear_error();
- break; /* We're at the end of stream. */
- }
- if (root_names != nullptr) {
- root_name = X509_get_subject_name(root);
- if (root_name == nullptr) {
- gpr_log(GPR_ERROR, "Could not get name from root certificate.");
- result = TSI_INVALID_ARGUMENT;
- break;
- }
- root_name = X509_NAME_dup(root_name);
- if (root_name == nullptr) {
- result = TSI_OUT_OF_RESOURCES;
- break;
- }
- sk_X509_NAME_push(*root_names, root_name);
- root_name = nullptr;
- }
+/* Loads in-memory PEM verification certs into the SSL context and optionally
+ returns the verification cert names (root_names can be NULL). */
+static tsi_result x509_store_load_certs(X509_STORE* cert_store,
+ const char* pem_roots,
+ size_t pem_roots_size,
+ STACK_OF(X509_NAME) * *root_names) {
+ tsi_result result = TSI_OK;
+ size_t num_roots = 0;
+ X509* root = nullptr;
+ X509_NAME* root_name = nullptr;
+ BIO* pem;
+ GPR_ASSERT(pem_roots_size <= INT_MAX);
+ pem = BIO_new_mem_buf((void*)pem_roots, static_cast<int>(pem_roots_size));
+ if (cert_store == nullptr) return TSI_INVALID_ARGUMENT;
+ if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
+ if (root_names != nullptr) {
+ *root_names = sk_X509_NAME_new_null();
+ if (*root_names == nullptr) return TSI_OUT_OF_RESOURCES;
+ }
+
+ while (1) {
+ root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)"");
+ if (root == nullptr) {
+ ERR_clear_error();
+ break; /* We're at the end of stream. */
+ }
+ if (root_names != nullptr) {
+ root_name = X509_get_subject_name(root);
+ if (root_name == nullptr) {
+ gpr_log(GPR_ERROR, "Could not get name from root certificate.");
+ result = TSI_INVALID_ARGUMENT;
+ break;
+ }
+ root_name = X509_NAME_dup(root_name);
+ if (root_name == nullptr) {
+ result = TSI_OUT_OF_RESOURCES;
+ break;
+ }
+ sk_X509_NAME_push(*root_names, root_name);
+ root_name = nullptr;
+ }
ERR_clear_error();
- if (!X509_STORE_add_cert(cert_store, root)) {
+ if (!X509_STORE_add_cert(cert_store, root)) {
unsigned long error = ERR_get_error();
if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
@@ -759,148 +759,148 @@ static tsi_result x509_store_load_certs(X509_STORE* cert_store,
result = TSI_INTERNAL_ERROR;
break;
}
- }
- X509_free(root);
- num_roots++;
- }
- if (num_roots == 0) {
- gpr_log(GPR_ERROR, "Could not load any root certificate.");
- result = TSI_INVALID_ARGUMENT;
- }
-
- if (result != TSI_OK) {
- if (root != nullptr) X509_free(root);
- if (root_names != nullptr) {
- sk_X509_NAME_pop_free(*root_names, X509_NAME_free);
- *root_names = nullptr;
- if (root_name != nullptr) X509_NAME_free(root_name);
- }
- }
- BIO_free(pem);
- return result;
-}
-
-static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context,
- const char* pem_roots,
- size_t pem_roots_size,
- STACK_OF(X509_NAME) *
- *root_name) {
- X509_STORE* cert_store = SSL_CTX_get_cert_store(context);
+ }
+ X509_free(root);
+ num_roots++;
+ }
+ if (num_roots == 0) {
+ gpr_log(GPR_ERROR, "Could not load any root certificate.");
+ result = TSI_INVALID_ARGUMENT;
+ }
+
+ if (result != TSI_OK) {
+ if (root != nullptr) X509_free(root);
+ if (root_names != nullptr) {
+ sk_X509_NAME_pop_free(*root_names, X509_NAME_free);
+ *root_names = nullptr;
+ if (root_name != nullptr) X509_NAME_free(root_name);
+ }
+ }
+ BIO_free(pem);
+ return result;
+}
+
+static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context,
+ const char* pem_roots,
+ size_t pem_roots_size,
+ STACK_OF(X509_NAME) *
+ *root_name) {
+ X509_STORE* cert_store = SSL_CTX_get_cert_store(context);
X509_STORE_set_flags(cert_store,
X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_TRUSTED_FIRST);
- return x509_store_load_certs(cert_store, pem_roots, pem_roots_size,
- root_name);
-}
-
-/* Populates the SSL context with a private key and a cert chain, and sets the
- cipher list and the ephemeral ECDH key. */
-static tsi_result populate_ssl_context(
- SSL_CTX* context, const tsi_ssl_pem_key_cert_pair* key_cert_pair,
- const char* cipher_list) {
- tsi_result result = TSI_OK;
- if (key_cert_pair != nullptr) {
- if (key_cert_pair->cert_chain != nullptr) {
- result = ssl_ctx_use_certificate_chain(context, key_cert_pair->cert_chain,
- strlen(key_cert_pair->cert_chain));
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Invalid cert chain file.");
- return result;
- }
- }
- if (key_cert_pair->private_key != nullptr) {
- result = ssl_ctx_use_private_key(context, key_cert_pair->private_key,
- strlen(key_cert_pair->private_key));
- if (result != TSI_OK || !SSL_CTX_check_private_key(context)) {
- gpr_log(GPR_ERROR, "Invalid private key.");
- return result != TSI_OK ? result : TSI_INVALID_ARGUMENT;
- }
- }
- }
- if ((cipher_list != nullptr) &&
- !SSL_CTX_set_cipher_list(context, cipher_list)) {
- gpr_log(GPR_ERROR, "Invalid cipher list: %s.", cipher_list);
- return TSI_INVALID_ARGUMENT;
- }
- {
- EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
- if (!SSL_CTX_set_tmp_ecdh(context, ecdh)) {
- gpr_log(GPR_ERROR, "Could not set ephemeral ECDH key.");
- EC_KEY_free(ecdh);
- return TSI_INTERNAL_ERROR;
- }
- SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
- EC_KEY_free(ecdh);
- }
- return TSI_OK;
-}
-
-/* Extracts the CN and the SANs from an X509 cert as a peer object. */
+ return x509_store_load_certs(cert_store, pem_roots, pem_roots_size,
+ root_name);
+}
+
+/* Populates the SSL context with a private key and a cert chain, and sets the
+ cipher list and the ephemeral ECDH key. */
+static tsi_result populate_ssl_context(
+ SSL_CTX* context, const tsi_ssl_pem_key_cert_pair* key_cert_pair,
+ const char* cipher_list) {
+ tsi_result result = TSI_OK;
+ if (key_cert_pair != nullptr) {
+ if (key_cert_pair->cert_chain != nullptr) {
+ result = ssl_ctx_use_certificate_chain(context, key_cert_pair->cert_chain,
+ strlen(key_cert_pair->cert_chain));
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Invalid cert chain file.");
+ return result;
+ }
+ }
+ if (key_cert_pair->private_key != nullptr) {
+ result = ssl_ctx_use_private_key(context, key_cert_pair->private_key,
+ strlen(key_cert_pair->private_key));
+ if (result != TSI_OK || !SSL_CTX_check_private_key(context)) {
+ gpr_log(GPR_ERROR, "Invalid private key.");
+ return result != TSI_OK ? result : TSI_INVALID_ARGUMENT;
+ }
+ }
+ }
+ if ((cipher_list != nullptr) &&
+ !SSL_CTX_set_cipher_list(context, cipher_list)) {
+ gpr_log(GPR_ERROR, "Invalid cipher list: %s.", cipher_list);
+ return TSI_INVALID_ARGUMENT;
+ }
+ {
+ EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
+ if (!SSL_CTX_set_tmp_ecdh(context, ecdh)) {
+ gpr_log(GPR_ERROR, "Could not set ephemeral ECDH key.");
+ EC_KEY_free(ecdh);
+ return TSI_INTERNAL_ERROR;
+ }
+ SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
+ EC_KEY_free(ecdh);
+ }
+ return TSI_OK;
+}
+
+/* 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 result = TSI_OK;
- X509* cert = nullptr;
- BIO* pem;
- pem = BIO_new_mem_buf((void*)pem_cert, static_cast<int>(strlen(pem_cert)));
- if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
-
- cert = PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
- if (cert == nullptr) {
- gpr_log(GPR_ERROR, "Invalid certificate");
- result = TSI_INVALID_ARGUMENT;
- } else {
- result = peer_from_x509(cert, 0, peer);
- }
- if (cert != nullptr) X509_free(cert);
- BIO_free(pem);
- return result;
-}
-
-/* Builds the alpn protocol name list according to rfc 7301. */
-static tsi_result build_alpn_protocol_name_list(
- const char** alpn_protocols, uint16_t num_alpn_protocols,
- unsigned char** protocol_name_list, size_t* protocol_name_list_length) {
- uint16_t i;
- unsigned char* current;
- *protocol_name_list = nullptr;
- *protocol_name_list_length = 0;
- if (num_alpn_protocols == 0) return TSI_INVALID_ARGUMENT;
- for (i = 0; i < num_alpn_protocols; i++) {
- size_t length =
- alpn_protocols[i] == nullptr ? 0 : strlen(alpn_protocols[i]);
- if (length == 0 || length > 255) {
- gpr_log(GPR_ERROR, "Invalid protocol name length: %d.",
- static_cast<int>(length));
- return TSI_INVALID_ARGUMENT;
- }
- *protocol_name_list_length += length + 1;
- }
- *protocol_name_list =
- static_cast<unsigned char*>(gpr_malloc(*protocol_name_list_length));
- if (*protocol_name_list == nullptr) return TSI_OUT_OF_RESOURCES;
- current = *protocol_name_list;
- for (i = 0; i < num_alpn_protocols; i++) {
- size_t length = strlen(alpn_protocols[i]);
- *(current++) = static_cast<uint8_t>(length); /* max checked above. */
- memcpy(current, alpn_protocols[i], length);
- current += length;
- }
- /* Safety check. */
- if ((current < *protocol_name_list) ||
- (static_cast<uintptr_t>(current - *protocol_name_list) !=
- *protocol_name_list_length)) {
- return TSI_INTERNAL_ERROR;
- }
- return TSI_OK;
-}
-
-// The verification callback is used for clients that don't really care about
-// 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.
+ tsi_result result = TSI_OK;
+ X509* cert = nullptr;
+ BIO* pem;
+ pem = BIO_new_mem_buf((void*)pem_cert, static_cast<int>(strlen(pem_cert)));
+ if (pem == nullptr) return TSI_OUT_OF_RESOURCES;
+
+ cert = PEM_read_bio_X509(pem, nullptr, nullptr, (void*)"");
+ if (cert == nullptr) {
+ gpr_log(GPR_ERROR, "Invalid certificate");
+ result = TSI_INVALID_ARGUMENT;
+ } else {
+ result = peer_from_x509(cert, 0, peer);
+ }
+ if (cert != nullptr) X509_free(cert);
+ BIO_free(pem);
+ return result;
+}
+
+/* Builds the alpn protocol name list according to rfc 7301. */
+static tsi_result build_alpn_protocol_name_list(
+ const char** alpn_protocols, uint16_t num_alpn_protocols,
+ unsigned char** protocol_name_list, size_t* protocol_name_list_length) {
+ uint16_t i;
+ unsigned char* current;
+ *protocol_name_list = nullptr;
+ *protocol_name_list_length = 0;
+ if (num_alpn_protocols == 0) return TSI_INVALID_ARGUMENT;
+ for (i = 0; i < num_alpn_protocols; i++) {
+ size_t length =
+ alpn_protocols[i] == nullptr ? 0 : strlen(alpn_protocols[i]);
+ if (length == 0 || length > 255) {
+ gpr_log(GPR_ERROR, "Invalid protocol name length: %d.",
+ static_cast<int>(length));
+ return TSI_INVALID_ARGUMENT;
+ }
+ *protocol_name_list_length += length + 1;
+ }
+ *protocol_name_list =
+ static_cast<unsigned char*>(gpr_malloc(*protocol_name_list_length));
+ if (*protocol_name_list == nullptr) return TSI_OUT_OF_RESOURCES;
+ current = *protocol_name_list;
+ for (i = 0; i < num_alpn_protocols; i++) {
+ size_t length = strlen(alpn_protocols[i]);
+ *(current++) = static_cast<uint8_t>(length); /* max checked above. */
+ memcpy(current, alpn_protocols[i], length);
+ current += length;
+ }
+ /* Safety check. */
+ if ((current < *protocol_name_list) ||
+ (static_cast<uintptr_t>(current - *protocol_name_list) !=
+ *protocol_name_list_length)) {
+ return TSI_INTERNAL_ERROR;
+ }
+ return TSI_OK;
+}
+
+// The verification callback is used for clients that don't really care about
+// 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*/) {
- return 1;
-}
-
+ return 1;
+}
+
// Sets the min and max TLS version of |ssl_context| to |min_tls_version| and
// |max_tls_version|, respectively. Calling this method is a no-op when using
// OpenSSL versions < 1.1.
@@ -945,252 +945,252 @@ static tsi_result tsi_set_min_and_max_tls_versions(
return TSI_OK;
}
-/* --- tsi_ssl_root_certs_store methods implementation. ---*/
-
-tsi_ssl_root_certs_store* tsi_ssl_root_certs_store_create(
- const char* pem_roots) {
- if (pem_roots == nullptr) {
- gpr_log(GPR_ERROR, "The root certificates are empty.");
- return nullptr;
- }
- tsi_ssl_root_certs_store* root_store = static_cast<tsi_ssl_root_certs_store*>(
- gpr_zalloc(sizeof(tsi_ssl_root_certs_store)));
- if (root_store == nullptr) {
- gpr_log(GPR_ERROR, "Could not allocate buffer for ssl_root_certs_store.");
- return nullptr;
- }
- root_store->store = X509_STORE_new();
- if (root_store->store == nullptr) {
- gpr_log(GPR_ERROR, "Could not allocate buffer for X509_STORE.");
- gpr_free(root_store);
- return nullptr;
- }
- tsi_result result = x509_store_load_certs(root_store->store, pem_roots,
- strlen(pem_roots), nullptr);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Could not load root certificates.");
- X509_STORE_free(root_store->store);
- gpr_free(root_store);
- return nullptr;
- }
- return root_store;
-}
-
-void tsi_ssl_root_certs_store_destroy(tsi_ssl_root_certs_store* self) {
- if (self == nullptr) return;
- X509_STORE_free(self->store);
- gpr_free(self);
-}
-
-/* --- tsi_ssl_session_cache methods implementation. ---*/
-
-tsi_ssl_session_cache* tsi_ssl_session_cache_create_lru(size_t capacity) {
- /* Pointer will be dereferenced by unref call. */
- return reinterpret_cast<tsi_ssl_session_cache*>(
- tsi::SslSessionLRUCache::Create(capacity).release());
-}
-
-void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache) {
- /* Pointer will be dereferenced by unref call. */
- reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Ref().release();
-}
-
-void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache) {
- reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Unref();
-}
-
-/* --- tsi_frame_protector methods implementation. ---*/
-
-static tsi_result ssl_protector_protect(tsi_frame_protector* self,
- const unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size) {
- tsi_ssl_frame_protector* impl =
- reinterpret_cast<tsi_ssl_frame_protector*>(self);
- int read_from_ssl;
- size_t available;
- tsi_result result = TSI_OK;
-
- /* First see if we have some pending data in the SSL BIO. */
- int pending_in_ssl = static_cast<int>(BIO_pending(impl->network_io));
- if (pending_in_ssl > 0) {
- *unprotected_bytes_size = 0;
- GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
- read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
- static_cast<int>(*protected_output_frames_size));
- if (read_from_ssl < 0) {
- gpr_log(GPR_ERROR,
- "Could not read from BIO even though some data is pending");
- return TSI_INTERNAL_ERROR;
- }
- *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
- return TSI_OK;
- }
-
- /* Now see if we can send a complete frame. */
- available = impl->buffer_size - impl->buffer_offset;
- if (available > *unprotected_bytes_size) {
- /* If we cannot, just copy the data in our internal buffer. */
- memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes,
- *unprotected_bytes_size);
- impl->buffer_offset += *unprotected_bytes_size;
- *protected_output_frames_size = 0;
- return TSI_OK;
- }
-
- /* If we can, prepare the buffer, send it to SSL_write and read. */
- memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes, available);
- result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_size);
- if (result != TSI_OK) return result;
-
- GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
- read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
- static_cast<int>(*protected_output_frames_size));
- if (read_from_ssl < 0) {
- gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
- return TSI_INTERNAL_ERROR;
- }
- *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
- *unprotected_bytes_size = available;
- impl->buffer_offset = 0;
- return TSI_OK;
-}
-
-static tsi_result ssl_protector_protect_flush(
- tsi_frame_protector* self, unsigned char* protected_output_frames,
- size_t* protected_output_frames_size, size_t* still_pending_size) {
- tsi_result result = TSI_OK;
- tsi_ssl_frame_protector* impl =
- reinterpret_cast<tsi_ssl_frame_protector*>(self);
- int read_from_ssl = 0;
- int pending;
-
- if (impl->buffer_offset != 0) {
- result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_offset);
- if (result != TSI_OK) return result;
- impl->buffer_offset = 0;
- }
-
- pending = static_cast<int>(BIO_pending(impl->network_io));
- GPR_ASSERT(pending >= 0);
- *still_pending_size = static_cast<size_t>(pending);
- if (*still_pending_size == 0) return TSI_OK;
-
- GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
- read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
- static_cast<int>(*protected_output_frames_size));
- if (read_from_ssl <= 0) {
- gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
- return TSI_INTERNAL_ERROR;
- }
- *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
- pending = static_cast<int>(BIO_pending(impl->network_io));
- GPR_ASSERT(pending >= 0);
- *still_pending_size = static_cast<size_t>(pending);
- return TSI_OK;
-}
-
-static tsi_result ssl_protector_unprotect(
- tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
- size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size) {
- tsi_result result = TSI_OK;
- int written_into_ssl = 0;
- size_t output_bytes_size = *unprotected_bytes_size;
- size_t output_bytes_offset = 0;
- tsi_ssl_frame_protector* impl =
- reinterpret_cast<tsi_ssl_frame_protector*>(self);
-
- /* First, try to read remaining data from ssl. */
- result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
- if (result != TSI_OK) return result;
- if (*unprotected_bytes_size == output_bytes_size) {
- /* We have read everything we could and cannot process any more input. */
- *protected_frames_bytes_size = 0;
- return TSI_OK;
- }
- output_bytes_offset = *unprotected_bytes_size;
- unprotected_bytes += output_bytes_offset;
- *unprotected_bytes_size = output_bytes_size - output_bytes_offset;
-
- /* Then, try to write some data to ssl. */
- GPR_ASSERT(*protected_frames_bytes_size <= INT_MAX);
- written_into_ssl = BIO_write(impl->network_io, protected_frames_bytes,
- static_cast<int>(*protected_frames_bytes_size));
- if (written_into_ssl < 0) {
- gpr_log(GPR_ERROR, "Sending protected frame to ssl failed with %d",
- written_into_ssl);
- return TSI_INTERNAL_ERROR;
- }
- *protected_frames_bytes_size = static_cast<size_t>(written_into_ssl);
-
- /* Now try to read some data again. */
- result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
- if (result == TSI_OK) {
- /* Don't forget to output the total number of bytes read. */
- *unprotected_bytes_size += output_bytes_offset;
- }
- return result;
-}
-
-static void ssl_protector_destroy(tsi_frame_protector* self) {
- tsi_ssl_frame_protector* impl =
- reinterpret_cast<tsi_ssl_frame_protector*>(self);
- if (impl->buffer != nullptr) gpr_free(impl->buffer);
- if (impl->ssl != nullptr) SSL_free(impl->ssl);
- if (impl->network_io != nullptr) BIO_free(impl->network_io);
- gpr_free(self);
-}
-
-static const tsi_frame_protector_vtable frame_protector_vtable = {
- ssl_protector_protect,
- ssl_protector_protect_flush,
- ssl_protector_unprotect,
- ssl_protector_destroy,
-};
-
-/* --- tsi_server_handshaker_factory methods implementation. --- */
-
-static void tsi_ssl_handshaker_factory_destroy(
- tsi_ssl_handshaker_factory* self) {
- if (self == nullptr) return;
-
- if (self->vtable != nullptr && self->vtable->destroy != nullptr) {
- self->vtable->destroy(self);
- }
- /* Note, we don't free(self) here because this object is always directly
- * embedded in another object. If tsi_ssl_handshaker_factory_init allocates
- * any memory, it should be free'd here. */
-}
-
-static tsi_ssl_handshaker_factory* tsi_ssl_handshaker_factory_ref(
- tsi_ssl_handshaker_factory* self) {
- if (self == nullptr) return nullptr;
- gpr_refn(&self->refcount, 1);
- return self;
-}
-
-static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory* self) {
- if (self == nullptr) return;
-
- if (gpr_unref(&self->refcount)) {
- tsi_ssl_handshaker_factory_destroy(self);
- }
-}
-
-static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr};
-
-/* Initializes a tsi_ssl_handshaker_factory object. Caller is responsible for
- * allocating memory for the factory. */
-static void tsi_ssl_handshaker_factory_init(
- tsi_ssl_handshaker_factory* factory) {
- GPR_ASSERT(factory != nullptr);
-
- factory->vtable = &handshaker_factory_vtable;
- gpr_ref_init(&factory->refcount, 1);
-}
-
+/* --- tsi_ssl_root_certs_store methods implementation. ---*/
+
+tsi_ssl_root_certs_store* tsi_ssl_root_certs_store_create(
+ const char* pem_roots) {
+ if (pem_roots == nullptr) {
+ gpr_log(GPR_ERROR, "The root certificates are empty.");
+ return nullptr;
+ }
+ tsi_ssl_root_certs_store* root_store = static_cast<tsi_ssl_root_certs_store*>(
+ gpr_zalloc(sizeof(tsi_ssl_root_certs_store)));
+ if (root_store == nullptr) {
+ gpr_log(GPR_ERROR, "Could not allocate buffer for ssl_root_certs_store.");
+ return nullptr;
+ }
+ root_store->store = X509_STORE_new();
+ if (root_store->store == nullptr) {
+ gpr_log(GPR_ERROR, "Could not allocate buffer for X509_STORE.");
+ gpr_free(root_store);
+ return nullptr;
+ }
+ tsi_result result = x509_store_load_certs(root_store->store, pem_roots,
+ strlen(pem_roots), nullptr);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Could not load root certificates.");
+ X509_STORE_free(root_store->store);
+ gpr_free(root_store);
+ return nullptr;
+ }
+ return root_store;
+}
+
+void tsi_ssl_root_certs_store_destroy(tsi_ssl_root_certs_store* self) {
+ if (self == nullptr) return;
+ X509_STORE_free(self->store);
+ gpr_free(self);
+}
+
+/* --- tsi_ssl_session_cache methods implementation. ---*/
+
+tsi_ssl_session_cache* tsi_ssl_session_cache_create_lru(size_t capacity) {
+ /* Pointer will be dereferenced by unref call. */
+ return reinterpret_cast<tsi_ssl_session_cache*>(
+ tsi::SslSessionLRUCache::Create(capacity).release());
+}
+
+void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache) {
+ /* Pointer will be dereferenced by unref call. */
+ reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Ref().release();
+}
+
+void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache) {
+ reinterpret_cast<tsi::SslSessionLRUCache*>(cache)->Unref();
+}
+
+/* --- tsi_frame_protector methods implementation. ---*/
+
+static tsi_result ssl_protector_protect(tsi_frame_protector* self,
+ const unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size) {
+ tsi_ssl_frame_protector* impl =
+ reinterpret_cast<tsi_ssl_frame_protector*>(self);
+ int read_from_ssl;
+ size_t available;
+ tsi_result result = TSI_OK;
+
+ /* First see if we have some pending data in the SSL BIO. */
+ int pending_in_ssl = static_cast<int>(BIO_pending(impl->network_io));
+ if (pending_in_ssl > 0) {
+ *unprotected_bytes_size = 0;
+ GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
+ read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
+ static_cast<int>(*protected_output_frames_size));
+ if (read_from_ssl < 0) {
+ gpr_log(GPR_ERROR,
+ "Could not read from BIO even though some data is pending");
+ return TSI_INTERNAL_ERROR;
+ }
+ *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
+ return TSI_OK;
+ }
+
+ /* Now see if we can send a complete frame. */
+ available = impl->buffer_size - impl->buffer_offset;
+ if (available > *unprotected_bytes_size) {
+ /* If we cannot, just copy the data in our internal buffer. */
+ memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes,
+ *unprotected_bytes_size);
+ impl->buffer_offset += *unprotected_bytes_size;
+ *protected_output_frames_size = 0;
+ return TSI_OK;
+ }
+
+ /* If we can, prepare the buffer, send it to SSL_write and read. */
+ memcpy(impl->buffer + impl->buffer_offset, unprotected_bytes, available);
+ result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_size);
+ if (result != TSI_OK) return result;
+
+ GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
+ read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
+ static_cast<int>(*protected_output_frames_size));
+ if (read_from_ssl < 0) {
+ gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
+ return TSI_INTERNAL_ERROR;
+ }
+ *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
+ *unprotected_bytes_size = available;
+ impl->buffer_offset = 0;
+ return TSI_OK;
+}
+
+static tsi_result ssl_protector_protect_flush(
+ tsi_frame_protector* self, unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size, size_t* still_pending_size) {
+ tsi_result result = TSI_OK;
+ tsi_ssl_frame_protector* impl =
+ reinterpret_cast<tsi_ssl_frame_protector*>(self);
+ int read_from_ssl = 0;
+ int pending;
+
+ if (impl->buffer_offset != 0) {
+ result = do_ssl_write(impl->ssl, impl->buffer, impl->buffer_offset);
+ if (result != TSI_OK) return result;
+ impl->buffer_offset = 0;
+ }
+
+ pending = static_cast<int>(BIO_pending(impl->network_io));
+ GPR_ASSERT(pending >= 0);
+ *still_pending_size = static_cast<size_t>(pending);
+ if (*still_pending_size == 0) return TSI_OK;
+
+ GPR_ASSERT(*protected_output_frames_size <= INT_MAX);
+ read_from_ssl = BIO_read(impl->network_io, protected_output_frames,
+ static_cast<int>(*protected_output_frames_size));
+ if (read_from_ssl <= 0) {
+ gpr_log(GPR_ERROR, "Could not read from BIO after SSL_write.");
+ return TSI_INTERNAL_ERROR;
+ }
+ *protected_output_frames_size = static_cast<size_t>(read_from_ssl);
+ pending = static_cast<int>(BIO_pending(impl->network_io));
+ GPR_ASSERT(pending >= 0);
+ *still_pending_size = static_cast<size_t>(pending);
+ return TSI_OK;
+}
+
+static tsi_result ssl_protector_unprotect(
+ tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
+ size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size) {
+ tsi_result result = TSI_OK;
+ int written_into_ssl = 0;
+ size_t output_bytes_size = *unprotected_bytes_size;
+ size_t output_bytes_offset = 0;
+ tsi_ssl_frame_protector* impl =
+ reinterpret_cast<tsi_ssl_frame_protector*>(self);
+
+ /* First, try to read remaining data from ssl. */
+ result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
+ if (result != TSI_OK) return result;
+ if (*unprotected_bytes_size == output_bytes_size) {
+ /* We have read everything we could and cannot process any more input. */
+ *protected_frames_bytes_size = 0;
+ return TSI_OK;
+ }
+ output_bytes_offset = *unprotected_bytes_size;
+ unprotected_bytes += output_bytes_offset;
+ *unprotected_bytes_size = output_bytes_size - output_bytes_offset;
+
+ /* Then, try to write some data to ssl. */
+ GPR_ASSERT(*protected_frames_bytes_size <= INT_MAX);
+ written_into_ssl = BIO_write(impl->network_io, protected_frames_bytes,
+ static_cast<int>(*protected_frames_bytes_size));
+ if (written_into_ssl < 0) {
+ gpr_log(GPR_ERROR, "Sending protected frame to ssl failed with %d",
+ written_into_ssl);
+ return TSI_INTERNAL_ERROR;
+ }
+ *protected_frames_bytes_size = static_cast<size_t>(written_into_ssl);
+
+ /* Now try to read some data again. */
+ result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size);
+ if (result == TSI_OK) {
+ /* Don't forget to output the total number of bytes read. */
+ *unprotected_bytes_size += output_bytes_offset;
+ }
+ return result;
+}
+
+static void ssl_protector_destroy(tsi_frame_protector* self) {
+ tsi_ssl_frame_protector* impl =
+ reinterpret_cast<tsi_ssl_frame_protector*>(self);
+ if (impl->buffer != nullptr) gpr_free(impl->buffer);
+ if (impl->ssl != nullptr) SSL_free(impl->ssl);
+ if (impl->network_io != nullptr) BIO_free(impl->network_io);
+ gpr_free(self);
+}
+
+static const tsi_frame_protector_vtable frame_protector_vtable = {
+ ssl_protector_protect,
+ ssl_protector_protect_flush,
+ ssl_protector_unprotect,
+ ssl_protector_destroy,
+};
+
+/* --- tsi_server_handshaker_factory methods implementation. --- */
+
+static void tsi_ssl_handshaker_factory_destroy(
+ tsi_ssl_handshaker_factory* self) {
+ if (self == nullptr) return;
+
+ if (self->vtable != nullptr && self->vtable->destroy != nullptr) {
+ self->vtable->destroy(self);
+ }
+ /* Note, we don't free(self) here because this object is always directly
+ * embedded in another object. If tsi_ssl_handshaker_factory_init allocates
+ * any memory, it should be free'd here. */
+}
+
+static tsi_ssl_handshaker_factory* tsi_ssl_handshaker_factory_ref(
+ tsi_ssl_handshaker_factory* self) {
+ if (self == nullptr) return nullptr;
+ gpr_refn(&self->refcount, 1);
+ return self;
+}
+
+static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory* self) {
+ if (self == nullptr) return;
+
+ if (gpr_unref(&self->refcount)) {
+ tsi_ssl_handshaker_factory_destroy(self);
+ }
+}
+
+static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr};
+
+/* Initializes a tsi_ssl_handshaker_factory object. Caller is responsible for
+ * allocating memory for the factory. */
+static void tsi_ssl_handshaker_factory_init(
+ tsi_ssl_handshaker_factory* factory) {
+ GPR_ASSERT(factory != nullptr);
+
+ factory->vtable = &handshaker_factory_vtable;
+ gpr_ref_init(&factory->refcount, 1);
+}
+
/* Gets the X509 cert chain in PEM format as a tsi_peer_property. */
tsi_result tsi_ssl_get_cert_chain_contents(STACK_OF(X509) * peer_chain,
tsi_peer_property* property) {
@@ -1218,54 +1218,54 @@ tsi_result tsi_ssl_get_cert_chain_contents(STACK_OF(X509) * peer_chain,
/* --- tsi_handshaker_result methods implementation. ---*/
static tsi_result ssl_handshaker_result_extract_peer(
const tsi_handshaker_result* self, tsi_peer* peer) {
- tsi_result result = TSI_OK;
- const unsigned char* alpn_selected = nullptr;
- unsigned int alpn_selected_len;
+ tsi_result result = TSI_OK;
+ const unsigned char* alpn_selected = nullptr;
+ unsigned int alpn_selected_len;
const tsi_ssl_handshaker_result* impl =
reinterpret_cast<const tsi_ssl_handshaker_result*>(self);
- X509* peer_cert = SSL_get_peer_certificate(impl->ssl);
- if (peer_cert != nullptr) {
- result = peer_from_x509(peer_cert, 1, peer);
- X509_free(peer_cert);
- if (result != TSI_OK) return result;
- }
-#if TSI_OPENSSL_ALPN_SUPPORT
- SSL_get0_alpn_selected(impl->ssl, &alpn_selected, &alpn_selected_len);
-#endif /* TSI_OPENSSL_ALPN_SUPPORT */
- if (alpn_selected == nullptr) {
- /* Try npn. */
- SSL_get0_next_proto_negotiated(impl->ssl, &alpn_selected,
- &alpn_selected_len);
- }
+ X509* peer_cert = SSL_get_peer_certificate(impl->ssl);
+ if (peer_cert != nullptr) {
+ result = peer_from_x509(peer_cert, 1, peer);
+ X509_free(peer_cert);
+ if (result != TSI_OK) return result;
+ }
+#if TSI_OPENSSL_ALPN_SUPPORT
+ SSL_get0_alpn_selected(impl->ssl, &alpn_selected, &alpn_selected_len);
+#endif /* TSI_OPENSSL_ALPN_SUPPORT */
+ if (alpn_selected == nullptr) {
+ /* Try npn. */
+ SSL_get0_next_proto_negotiated(impl->ssl, &alpn_selected,
+ &alpn_selected_len);
+ }
// When called on the client side, the stack also contains the
// peer's certificate; When called on the server side,
// the peer's certificate is not present in the stack
STACK_OF(X509)* peer_chain = SSL_get_peer_cert_chain(impl->ssl);
- // 1 is for session reused property.
+ // 1 is for session reused property.
size_t new_property_count = peer->property_count + 3;
- if (alpn_selected != nullptr) new_property_count++;
+ if (alpn_selected != nullptr) new_property_count++;
if (peer_chain != nullptr) new_property_count++;
- tsi_peer_property* new_properties = static_cast<tsi_peer_property*>(
- gpr_zalloc(sizeof(*new_properties) * new_property_count));
- for (size_t i = 0; i < peer->property_count; i++) {
- new_properties[i] = peer->properties[i];
- }
- if (peer->properties != nullptr) gpr_free(peer->properties);
- peer->properties = new_properties;
+ tsi_peer_property* new_properties = static_cast<tsi_peer_property*>(
+ gpr_zalloc(sizeof(*new_properties) * new_property_count));
+ for (size_t i = 0; i < peer->property_count; i++) {
+ new_properties[i] = peer->properties[i];
+ }
+ if (peer->properties != nullptr) gpr_free(peer->properties);
+ peer->properties = new_properties;
// Add peer chain if available
if (peer_chain != nullptr) {
result = tsi_ssl_get_cert_chain_contents(
peer_chain, &peer->properties[peer->property_count]);
if (result == TSI_OK) peer->property_count++;
}
- if (alpn_selected != nullptr) {
- result = tsi_construct_string_peer_property(
- TSI_SSL_ALPN_SELECTED_PROTOCOL,
- reinterpret_cast<const char*>(alpn_selected), alpn_selected_len,
- &peer->properties[peer->property_count]);
- if (result != TSI_OK) return result;
- peer->property_count++;
- }
+ if (alpn_selected != nullptr) {
+ result = tsi_construct_string_peer_property(
+ TSI_SSL_ALPN_SELECTED_PROTOCOL,
+ reinterpret_cast<const char*>(alpn_selected), alpn_selected_len,
+ &peer->properties[peer->property_count]);
+ if (result != TSI_OK) return result;
+ peer->property_count++;
+ }
// Add security_level peer property.
result = tsi_construct_string_peer_property_from_cstring(
TSI_SECURITY_LEVEL_PEER_PROPERTY,
@@ -1273,61 +1273,61 @@ static tsi_result ssl_handshaker_result_extract_peer(
&peer->properties[peer->property_count]);
if (result != TSI_OK) return result;
peer->property_count++;
-
- const char* session_reused = SSL_session_reused(impl->ssl) ? "true" : "false";
+
+ const char* session_reused = SSL_session_reused(impl->ssl) ? "true" : "false";
result = tsi_construct_string_peer_property_from_cstring(
- TSI_SSL_SESSION_REUSED_PEER_PROPERTY, session_reused,
+ TSI_SSL_SESSION_REUSED_PEER_PROPERTY, session_reused,
&peer->properties[peer->property_count]);
- if (result != TSI_OK) return result;
- peer->property_count++;
- return result;
-}
-
+ if (result != TSI_OK) return result;
+ peer->property_count++;
+ return result;
+}
+
static tsi_result ssl_handshaker_result_create_frame_protector(
const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
- tsi_frame_protector** protector) {
- size_t actual_max_output_protected_frame_size =
- TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
+ tsi_frame_protector** protector) {
+ size_t actual_max_output_protected_frame_size =
+ TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
tsi_ssl_handshaker_result* impl =
reinterpret_cast<tsi_ssl_handshaker_result*>(
const_cast<tsi_handshaker_result*>(self));
- tsi_ssl_frame_protector* protector_impl =
- static_cast<tsi_ssl_frame_protector*>(
- gpr_zalloc(sizeof(*protector_impl)));
-
- if (max_output_protected_frame_size != nullptr) {
- if (*max_output_protected_frame_size >
- TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND) {
- *max_output_protected_frame_size =
- TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
- } else if (*max_output_protected_frame_size <
- TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND) {
- *max_output_protected_frame_size =
- TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND;
- }
- actual_max_output_protected_frame_size = *max_output_protected_frame_size;
- }
- protector_impl->buffer_size =
- actual_max_output_protected_frame_size - TSI_SSL_MAX_PROTECTION_OVERHEAD;
- protector_impl->buffer =
- static_cast<unsigned char*>(gpr_malloc(protector_impl->buffer_size));
- if (protector_impl->buffer == nullptr) {
- gpr_log(GPR_ERROR,
- "Could not allocated buffer for tsi_ssl_frame_protector.");
- gpr_free(protector_impl);
- return TSI_INTERNAL_ERROR;
- }
-
+ tsi_ssl_frame_protector* protector_impl =
+ static_cast<tsi_ssl_frame_protector*>(
+ gpr_zalloc(sizeof(*protector_impl)));
+
+ if (max_output_protected_frame_size != nullptr) {
+ if (*max_output_protected_frame_size >
+ TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND) {
+ *max_output_protected_frame_size =
+ TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
+ } else if (*max_output_protected_frame_size <
+ TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND) {
+ *max_output_protected_frame_size =
+ TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND;
+ }
+ actual_max_output_protected_frame_size = *max_output_protected_frame_size;
+ }
+ protector_impl->buffer_size =
+ actual_max_output_protected_frame_size - TSI_SSL_MAX_PROTECTION_OVERHEAD;
+ protector_impl->buffer =
+ static_cast<unsigned char*>(gpr_malloc(protector_impl->buffer_size));
+ if (protector_impl->buffer == nullptr) {
+ gpr_log(GPR_ERROR,
+ "Could not allocated buffer for tsi_ssl_frame_protector.");
+ gpr_free(protector_impl);
+ return TSI_INTERNAL_ERROR;
+ }
+
/* Transfer ownership of ssl and network_io to the frame protector. */
- protector_impl->ssl = impl->ssl;
- impl->ssl = nullptr;
- protector_impl->network_io = impl->network_io;
- impl->network_io = nullptr;
- protector_impl->base.vtable = &frame_protector_vtable;
- *protector = &protector_impl->base;
- return TSI_OK;
-}
-
+ protector_impl->ssl = impl->ssl;
+ impl->ssl = nullptr;
+ protector_impl->network_io = impl->network_io;
+ impl->network_io = nullptr;
+ protector_impl->base.vtable = &frame_protector_vtable;
+ *protector = &protector_impl->base;
+ return TSI_OK;
+}
+
static tsi_result ssl_handshaker_result_get_unused_bytes(
const tsi_handshaker_result* self, const unsigned char** bytes,
size_t* bytes_size) {
@@ -1455,15 +1455,15 @@ static tsi_result ssl_handshaker_process_bytes_from_peer(
}
}
-static void ssl_handshaker_destroy(tsi_handshaker* self) {
- tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
- SSL_free(impl->ssl);
- BIO_free(impl->network_io);
+static void ssl_handshaker_destroy(tsi_handshaker* self) {
+ tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self);
+ SSL_free(impl->ssl);
+ BIO_free(impl->network_io);
gpr_free(impl->outgoing_bytes_buffer);
- tsi_ssl_handshaker_factory_unref(impl->factory_ref);
- gpr_free(impl);
-}
-
+ tsi_ssl_handshaker_factory_unref(impl->factory_ref);
+ gpr_free(impl);
+}
+
// Removes the bytes remaining in |impl->SSL|'s read BIO and writes them to
// |bytes_remaining|.
static tsi_result ssl_bytes_remaining(tsi_ssl_handshaker* impl,
@@ -1558,226 +1558,226 @@ static tsi_result ssl_handshaker_next(
return status;
}
-static const tsi_handshaker_vtable handshaker_vtable = {
+static const tsi_handshaker_vtable handshaker_vtable = {
nullptr, /* get_bytes_to_send_to_peer -- deprecated */
nullptr, /* process_bytes_from_peer -- deprecated */
nullptr, /* get_result -- deprecated */
nullptr, /* extract_peer -- deprecated */
nullptr, /* create_frame_protector -- deprecated */
- ssl_handshaker_destroy,
+ ssl_handshaker_destroy,
ssl_handshaker_next,
nullptr, /* shutdown */
-};
-
-/* --- tsi_ssl_handshaker_factory common methods. --- */
-
-static void tsi_ssl_handshaker_resume_session(
- SSL* ssl, tsi::SslSessionLRUCache* session_cache) {
- const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
- if (server_name == nullptr) {
- return;
- }
- tsi::SslSessionPtr session = session_cache->Get(server_name);
- if (session != nullptr) {
- // SSL_set_session internally increments reference counter.
- SSL_set_session(ssl, session.get());
- }
-}
-
-static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client,
- const char* server_name_indication,
- tsi_ssl_handshaker_factory* factory,
- tsi_handshaker** handshaker) {
- SSL* ssl = SSL_new(ctx);
- BIO* network_io = nullptr;
- BIO* ssl_io = nullptr;
- tsi_ssl_handshaker* impl = nullptr;
- *handshaker = nullptr;
- if (ctx == nullptr) {
- gpr_log(GPR_ERROR, "SSL Context is null. Should never happen.");
- return TSI_INTERNAL_ERROR;
- }
- if (ssl == nullptr) {
- return TSI_OUT_OF_RESOURCES;
- }
- SSL_set_info_callback(ssl, ssl_info_callback);
-
- if (!BIO_new_bio_pair(&network_io, 0, &ssl_io, 0)) {
- gpr_log(GPR_ERROR, "BIO_new_bio_pair failed.");
- SSL_free(ssl);
- return TSI_OUT_OF_RESOURCES;
- }
- SSL_set_bio(ssl, ssl_io, ssl_io);
- if (is_client) {
- int ssl_result;
- SSL_set_connect_state(ssl);
- if (server_name_indication != nullptr) {
- if (!SSL_set_tlsext_host_name(ssl, server_name_indication)) {
- gpr_log(GPR_ERROR, "Invalid server name indication %s.",
- server_name_indication);
- SSL_free(ssl);
- BIO_free(network_io);
- return TSI_INTERNAL_ERROR;
- }
- }
- tsi_ssl_client_handshaker_factory* client_factory =
- reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
- if (client_factory->session_cache != nullptr) {
- tsi_ssl_handshaker_resume_session(ssl,
- client_factory->session_cache.get());
- }
- ssl_result = SSL_do_handshake(ssl);
- ssl_result = SSL_get_error(ssl, ssl_result);
- if (ssl_result != SSL_ERROR_WANT_READ) {
- gpr_log(GPR_ERROR,
- "Unexpected error received from first SSL_do_handshake call: %s",
- ssl_error_string(ssl_result));
- SSL_free(ssl);
- BIO_free(network_io);
- return TSI_INTERNAL_ERROR;
- }
- } else {
- SSL_set_accept_state(ssl);
- }
-
- impl = static_cast<tsi_ssl_handshaker*>(gpr_zalloc(sizeof(*impl)));
- impl->ssl = ssl;
- impl->network_io = network_io;
- impl->result = TSI_HANDSHAKE_IN_PROGRESS;
+};
+
+/* --- tsi_ssl_handshaker_factory common methods. --- */
+
+static void tsi_ssl_handshaker_resume_session(
+ SSL* ssl, tsi::SslSessionLRUCache* session_cache) {
+ const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
+ if (server_name == nullptr) {
+ return;
+ }
+ tsi::SslSessionPtr session = session_cache->Get(server_name);
+ if (session != nullptr) {
+ // SSL_set_session internally increments reference counter.
+ SSL_set_session(ssl, session.get());
+ }
+}
+
+static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client,
+ const char* server_name_indication,
+ tsi_ssl_handshaker_factory* factory,
+ tsi_handshaker** handshaker) {
+ SSL* ssl = SSL_new(ctx);
+ BIO* network_io = nullptr;
+ BIO* ssl_io = nullptr;
+ tsi_ssl_handshaker* impl = nullptr;
+ *handshaker = nullptr;
+ if (ctx == nullptr) {
+ gpr_log(GPR_ERROR, "SSL Context is null. Should never happen.");
+ return TSI_INTERNAL_ERROR;
+ }
+ if (ssl == nullptr) {
+ return TSI_OUT_OF_RESOURCES;
+ }
+ SSL_set_info_callback(ssl, ssl_info_callback);
+
+ if (!BIO_new_bio_pair(&network_io, 0, &ssl_io, 0)) {
+ gpr_log(GPR_ERROR, "BIO_new_bio_pair failed.");
+ SSL_free(ssl);
+ return TSI_OUT_OF_RESOURCES;
+ }
+ SSL_set_bio(ssl, ssl_io, ssl_io);
+ if (is_client) {
+ int ssl_result;
+ SSL_set_connect_state(ssl);
+ if (server_name_indication != nullptr) {
+ if (!SSL_set_tlsext_host_name(ssl, server_name_indication)) {
+ gpr_log(GPR_ERROR, "Invalid server name indication %s.",
+ server_name_indication);
+ SSL_free(ssl);
+ BIO_free(network_io);
+ return TSI_INTERNAL_ERROR;
+ }
+ }
+ tsi_ssl_client_handshaker_factory* client_factory =
+ reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
+ if (client_factory->session_cache != nullptr) {
+ tsi_ssl_handshaker_resume_session(ssl,
+ client_factory->session_cache.get());
+ }
+ ssl_result = SSL_do_handshake(ssl);
+ ssl_result = SSL_get_error(ssl, ssl_result);
+ if (ssl_result != SSL_ERROR_WANT_READ) {
+ gpr_log(GPR_ERROR,
+ "Unexpected error received from first SSL_do_handshake call: %s",
+ ssl_error_string(ssl_result));
+ SSL_free(ssl);
+ BIO_free(network_io);
+ return TSI_INTERNAL_ERROR;
+ }
+ } else {
+ SSL_set_accept_state(ssl);
+ }
+
+ impl = static_cast<tsi_ssl_handshaker*>(gpr_zalloc(sizeof(*impl)));
+ impl->ssl = ssl;
+ impl->network_io = network_io;
+ impl->result = TSI_HANDSHAKE_IN_PROGRESS;
impl->outgoing_bytes_buffer_size =
TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE;
impl->outgoing_bytes_buffer =
static_cast<unsigned char*>(gpr_zalloc(impl->outgoing_bytes_buffer_size));
- impl->base.vtable = &handshaker_vtable;
- impl->factory_ref = tsi_ssl_handshaker_factory_ref(factory);
- *handshaker = &impl->base;
- return TSI_OK;
-}
-
-static int select_protocol_list(const unsigned char** out,
- unsigned char* outlen,
- const unsigned char* client_list,
- size_t client_list_len,
- const unsigned char* server_list,
- size_t server_list_len) {
- const unsigned char* client_current = client_list;
- while (static_cast<unsigned int>(client_current - client_list) <
- client_list_len) {
- unsigned char client_current_len = *(client_current++);
- const unsigned char* server_current = server_list;
- while ((server_current >= server_list) &&
- static_cast<uintptr_t>(server_current - server_list) <
- server_list_len) {
- unsigned char server_current_len = *(server_current++);
- if ((client_current_len == server_current_len) &&
- !memcmp(client_current, server_current, server_current_len)) {
- *out = server_current;
- *outlen = server_current_len;
- return SSL_TLSEXT_ERR_OK;
- }
- server_current += server_current_len;
- }
- client_current += client_current_len;
- }
- return SSL_TLSEXT_ERR_NOACK;
-}
-
-/* --- tsi_ssl_client_handshaker_factory methods implementation. --- */
-
-tsi_result tsi_ssl_client_handshaker_factory_create_handshaker(
- tsi_ssl_client_handshaker_factory* self, const char* server_name_indication,
- tsi_handshaker** handshaker) {
- return create_tsi_ssl_handshaker(self->ssl_context, 1, server_name_indication,
- &self->base, handshaker);
-}
-
-void tsi_ssl_client_handshaker_factory_unref(
- tsi_ssl_client_handshaker_factory* self) {
- if (self == nullptr) return;
- tsi_ssl_handshaker_factory_unref(&self->base);
-}
-
-static void tsi_ssl_client_handshaker_factory_destroy(
- tsi_ssl_handshaker_factory* factory) {
- if (factory == nullptr) return;
- tsi_ssl_client_handshaker_factory* self =
- reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
- if (self->ssl_context != nullptr) SSL_CTX_free(self->ssl_context);
- if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
- self->session_cache.reset();
- gpr_free(self);
-}
-
+ impl->base.vtable = &handshaker_vtable;
+ impl->factory_ref = tsi_ssl_handshaker_factory_ref(factory);
+ *handshaker = &impl->base;
+ return TSI_OK;
+}
+
+static int select_protocol_list(const unsigned char** out,
+ unsigned char* outlen,
+ const unsigned char* client_list,
+ size_t client_list_len,
+ const unsigned char* server_list,
+ size_t server_list_len) {
+ const unsigned char* client_current = client_list;
+ while (static_cast<unsigned int>(client_current - client_list) <
+ client_list_len) {
+ unsigned char client_current_len = *(client_current++);
+ const unsigned char* server_current = server_list;
+ while ((server_current >= server_list) &&
+ static_cast<uintptr_t>(server_current - server_list) <
+ server_list_len) {
+ unsigned char server_current_len = *(server_current++);
+ if ((client_current_len == server_current_len) &&
+ !memcmp(client_current, server_current, server_current_len)) {
+ *out = server_current;
+ *outlen = server_current_len;
+ return SSL_TLSEXT_ERR_OK;
+ }
+ server_current += server_current_len;
+ }
+ client_current += client_current_len;
+ }
+ return SSL_TLSEXT_ERR_NOACK;
+}
+
+/* --- tsi_ssl_client_handshaker_factory methods implementation. --- */
+
+tsi_result tsi_ssl_client_handshaker_factory_create_handshaker(
+ tsi_ssl_client_handshaker_factory* self, const char* server_name_indication,
+ tsi_handshaker** handshaker) {
+ return create_tsi_ssl_handshaker(self->ssl_context, 1, server_name_indication,
+ &self->base, handshaker);
+}
+
+void tsi_ssl_client_handshaker_factory_unref(
+ tsi_ssl_client_handshaker_factory* self) {
+ if (self == nullptr) return;
+ tsi_ssl_handshaker_factory_unref(&self->base);
+}
+
+static void tsi_ssl_client_handshaker_factory_destroy(
+ tsi_ssl_handshaker_factory* factory) {
+ if (factory == nullptr) return;
+ tsi_ssl_client_handshaker_factory* self =
+ reinterpret_cast<tsi_ssl_client_handshaker_factory*>(factory);
+ if (self->ssl_context != nullptr) SSL_CTX_free(self->ssl_context);
+ if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
+ self->session_cache.reset();
+ 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) {
- tsi_ssl_client_handshaker_factory* factory =
- static_cast<tsi_ssl_client_handshaker_factory*>(arg);
- return select_protocol_list((const unsigned char**)out, outlen,
- factory->alpn_protocol_list,
- factory->alpn_protocol_list_length, in, inlen);
-}
-
-/* --- tsi_ssl_server_handshaker_factory methods implementation. --- */
-
-tsi_result tsi_ssl_server_handshaker_factory_create_handshaker(
- tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker) {
- if (self->ssl_context_count == 0) return TSI_INVALID_ARGUMENT;
- /* Create the handshaker with the first context. We will switch if needed
- because of SNI in ssl_server_handshaker_factory_servername_callback. */
- return create_tsi_ssl_handshaker(self->ssl_contexts[0], 0, nullptr,
- &self->base, handshaker);
-}
-
-void tsi_ssl_server_handshaker_factory_unref(
- tsi_ssl_server_handshaker_factory* self) {
- if (self == nullptr) return;
- tsi_ssl_handshaker_factory_unref(&self->base);
-}
-
-static void tsi_ssl_server_handshaker_factory_destroy(
- tsi_ssl_handshaker_factory* factory) {
- if (factory == nullptr) return;
- tsi_ssl_server_handshaker_factory* self =
- reinterpret_cast<tsi_ssl_server_handshaker_factory*>(factory);
- size_t i;
- for (i = 0; i < self->ssl_context_count; i++) {
- if (self->ssl_contexts[i] != nullptr) {
- SSL_CTX_free(self->ssl_contexts[i]);
- tsi_peer_destruct(&self->ssl_context_x509_subject_names[i]);
- }
- }
- if (self->ssl_contexts != nullptr) gpr_free(self->ssl_contexts);
- if (self->ssl_context_x509_subject_names != nullptr) {
- gpr_free(self->ssl_context_x509_subject_names);
- }
- if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
- gpr_free(self);
-}
-
+ tsi_ssl_client_handshaker_factory* factory =
+ static_cast<tsi_ssl_client_handshaker_factory*>(arg);
+ return select_protocol_list((const unsigned char**)out, outlen,
+ factory->alpn_protocol_list,
+ factory->alpn_protocol_list_length, in, inlen);
+}
+
+/* --- tsi_ssl_server_handshaker_factory methods implementation. --- */
+
+tsi_result tsi_ssl_server_handshaker_factory_create_handshaker(
+ tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker) {
+ if (self->ssl_context_count == 0) return TSI_INVALID_ARGUMENT;
+ /* Create the handshaker with the first context. We will switch if needed
+ because of SNI in ssl_server_handshaker_factory_servername_callback. */
+ return create_tsi_ssl_handshaker(self->ssl_contexts[0], 0, nullptr,
+ &self->base, handshaker);
+}
+
+void tsi_ssl_server_handshaker_factory_unref(
+ tsi_ssl_server_handshaker_factory* self) {
+ if (self == nullptr) return;
+ tsi_ssl_handshaker_factory_unref(&self->base);
+}
+
+static void tsi_ssl_server_handshaker_factory_destroy(
+ tsi_ssl_handshaker_factory* factory) {
+ if (factory == nullptr) return;
+ tsi_ssl_server_handshaker_factory* self =
+ reinterpret_cast<tsi_ssl_server_handshaker_factory*>(factory);
+ size_t i;
+ for (i = 0; i < self->ssl_context_count; i++) {
+ if (self->ssl_contexts[i] != nullptr) {
+ SSL_CTX_free(self->ssl_contexts[i]);
+ tsi_peer_destruct(&self->ssl_context_x509_subject_names[i]);
+ }
+ }
+ if (self->ssl_contexts != nullptr) gpr_free(self->ssl_contexts);
+ if (self->ssl_context_x509_subject_names != nullptr) {
+ gpr_free(self->ssl_context_x509_subject_names);
+ }
+ if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list);
+ gpr_free(self);
+}
+
static int does_entry_match_name(y_absl::string_view entry,
y_absl::string_view name) {
if (entry.empty()) return 0;
-
- /* Take care of '.' terminations. */
+
+ /* Take care of '.' terminations. */
if (name.back() == '.') {
name.remove_suffix(1);
- }
+ }
if (entry.back() == '.') {
entry.remove_suffix(1);
if (entry.empty()) return 0;
- }
-
+ }
+
if (y_absl::EqualsIgnoreCase(name, entry)) {
- return 1; /* Perfect match. */
- }
+ return 1; /* Perfect match. */
+ }
if (entry.front() != '*') return 0;
-
- /* Wildchar subdomain matching. */
+
+ /* Wildchar subdomain matching. */
if (entry.size() < 3 || entry[1] != '.') { /* At least *.x */
- gpr_log(GPR_ERROR, "Invalid wildchar entry.");
- return 0;
- }
+ gpr_log(GPR_ERROR, "Invalid wildchar entry.");
+ return 0;
+ }
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;
@@ -1788,337 +1788,337 @@ static int does_entry_match_name(y_absl::string_view entry,
if (dot == y_absl::string_view::npos || dot == name_subdomain.size() - 1) {
gpr_log(GPR_ERROR, "Invalid toplevel subdomain: %s",
TString(name_subdomain).c_str());
- return 0;
- }
+ return 0;
+ }
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*/,
- void* arg) {
- tsi_ssl_server_handshaker_factory* impl =
- static_cast<tsi_ssl_server_handshaker_factory*>(arg);
- size_t i = 0;
- const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
- if (servername == nullptr || strlen(servername) == 0) {
- return SSL_TLSEXT_ERR_NOACK;
- }
-
- for (i = 0; i < impl->ssl_context_count; i++) {
- if (tsi_ssl_peer_matches_name(&impl->ssl_context_x509_subject_names[i],
- servername)) {
- SSL_set_SSL_CTX(ssl, impl->ssl_contexts[i]);
- return SSL_TLSEXT_ERR_OK;
- }
- }
- gpr_log(GPR_ERROR, "No match found for server name: %s.", servername);
+ void* arg) {
+ tsi_ssl_server_handshaker_factory* impl =
+ static_cast<tsi_ssl_server_handshaker_factory*>(arg);
+ size_t i = 0;
+ const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
+ if (servername == nullptr || strlen(servername) == 0) {
+ return SSL_TLSEXT_ERR_NOACK;
+ }
+
+ for (i = 0; i < impl->ssl_context_count; i++) {
+ if (tsi_ssl_peer_matches_name(&impl->ssl_context_x509_subject_names[i],
+ servername)) {
+ SSL_set_SSL_CTX(ssl, impl->ssl_contexts[i]);
+ return SSL_TLSEXT_ERR_OK;
+ }
+ }
+ gpr_log(GPR_ERROR, "No match found for server name: %s.", servername);
return SSL_TLSEXT_ERR_NOACK;
-}
-
-#if TSI_OPENSSL_ALPN_SUPPORT
-static int server_handshaker_factory_alpn_callback(
+}
+
+#if TSI_OPENSSL_ALPN_SUPPORT
+static int server_handshaker_factory_alpn_callback(
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);
- return select_protocol_list(out, outlen, in, inlen,
- factory->alpn_protocol_list,
- factory->alpn_protocol_list_length);
-}
-#endif /* TSI_OPENSSL_ALPN_SUPPORT */
-
-static int server_handshaker_factory_npn_advertised_callback(
+ const unsigned char* in, unsigned int inlen, void* arg) {
+ tsi_ssl_server_handshaker_factory* factory =
+ static_cast<tsi_ssl_server_handshaker_factory*>(arg);
+ return select_protocol_list(out, outlen, in, inlen,
+ factory->alpn_protocol_list,
+ factory->alpn_protocol_list_length);
+}
+#endif /* TSI_OPENSSL_ALPN_SUPPORT */
+
+static int server_handshaker_factory_npn_advertised_callback(
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;
- GPR_ASSERT(factory->alpn_protocol_list_length <= UINT_MAX);
- *outlen = static_cast<unsigned int>(factory->alpn_protocol_list_length);
- return SSL_TLSEXT_ERR_OK;
-}
-
-/// This callback is called when new \a session is established and ready to
-/// be cached. This session can be reused for new connections to similar
-/// servers at later point of time.
-/// It's intended to be used with SSL_CTX_sess_set_new_cb function.
-///
-/// It returns 1 if callback takes ownership over \a session and 0 otherwise.
-static int server_handshaker_factory_new_session_callback(
- SSL* ssl, SSL_SESSION* session) {
- SSL_CTX* ssl_context = SSL_get_SSL_CTX(ssl);
- if (ssl_context == nullptr) {
- return 0;
- }
- void* arg = SSL_CTX_get_ex_data(ssl_context, g_ssl_ctx_ex_factory_index);
- tsi_ssl_client_handshaker_factory* factory =
- static_cast<tsi_ssl_client_handshaker_factory*>(arg);
- const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
- if (server_name == nullptr) {
- return 0;
- }
- factory->session_cache->Put(server_name, tsi::SslSessionPtr(session));
+ tsi_ssl_server_handshaker_factory* factory =
+ static_cast<tsi_ssl_server_handshaker_factory*>(arg);
+ *out = factory->alpn_protocol_list;
+ GPR_ASSERT(factory->alpn_protocol_list_length <= UINT_MAX);
+ *outlen = static_cast<unsigned int>(factory->alpn_protocol_list_length);
+ return SSL_TLSEXT_ERR_OK;
+}
+
+/// This callback is called when new \a session is established and ready to
+/// be cached. This session can be reused for new connections to similar
+/// servers at later point of time.
+/// It's intended to be used with SSL_CTX_sess_set_new_cb function.
+///
+/// It returns 1 if callback takes ownership over \a session and 0 otherwise.
+static int server_handshaker_factory_new_session_callback(
+ SSL* ssl, SSL_SESSION* session) {
+ SSL_CTX* ssl_context = SSL_get_SSL_CTX(ssl);
+ if (ssl_context == nullptr) {
+ return 0;
+ }
+ void* arg = SSL_CTX_get_ex_data(ssl_context, g_ssl_ctx_ex_factory_index);
+ tsi_ssl_client_handshaker_factory* factory =
+ static_cast<tsi_ssl_client_handshaker_factory*>(arg);
+ const char* server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
+ if (server_name == nullptr) {
+ return 0;
+ }
+ factory->session_cache->Put(server_name, tsi::SslSessionPtr(session));
// Return 1 to indicate transferred ownership over the given session.
- return 1;
-}
-
-/* --- tsi_ssl_handshaker_factory constructors. --- */
-
-static tsi_ssl_handshaker_factory_vtable client_handshaker_factory_vtable = {
- tsi_ssl_client_handshaker_factory_destroy};
-
-tsi_result tsi_create_ssl_client_handshaker_factory(
- const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const char* pem_root_certs, const char* cipher_suites,
- const char** alpn_protocols, uint16_t num_alpn_protocols,
- tsi_ssl_client_handshaker_factory** factory) {
- tsi_ssl_client_handshaker_options options;
- options.pem_key_cert_pair = pem_key_cert_pair;
- options.pem_root_certs = pem_root_certs;
- options.cipher_suites = cipher_suites;
- options.alpn_protocols = alpn_protocols;
- options.num_alpn_protocols = num_alpn_protocols;
- return tsi_create_ssl_client_handshaker_factory_with_options(&options,
- factory);
-}
-
-tsi_result tsi_create_ssl_client_handshaker_factory_with_options(
- const tsi_ssl_client_handshaker_options* options,
- tsi_ssl_client_handshaker_factory** factory) {
- SSL_CTX* ssl_context = nullptr;
- tsi_ssl_client_handshaker_factory* impl = nullptr;
- tsi_result result = TSI_OK;
-
- gpr_once_init(&g_init_openssl_once, init_openssl);
-
- if (factory == nullptr) return TSI_INVALID_ARGUMENT;
- *factory = nullptr;
- if (options->pem_root_certs == nullptr && options->root_store == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
-
+ return 1;
+}
+
+/* --- tsi_ssl_handshaker_factory constructors. --- */
+
+static tsi_ssl_handshaker_factory_vtable client_handshaker_factory_vtable = {
+ tsi_ssl_client_handshaker_factory_destroy};
+
+tsi_result tsi_create_ssl_client_handshaker_factory(
+ const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair,
+ const char* pem_root_certs, const char* cipher_suites,
+ const char** alpn_protocols, uint16_t num_alpn_protocols,
+ tsi_ssl_client_handshaker_factory** factory) {
+ tsi_ssl_client_handshaker_options options;
+ options.pem_key_cert_pair = pem_key_cert_pair;
+ options.pem_root_certs = pem_root_certs;
+ options.cipher_suites = cipher_suites;
+ options.alpn_protocols = alpn_protocols;
+ options.num_alpn_protocols = num_alpn_protocols;
+ return tsi_create_ssl_client_handshaker_factory_with_options(&options,
+ factory);
+}
+
+tsi_result tsi_create_ssl_client_handshaker_factory_with_options(
+ const tsi_ssl_client_handshaker_options* options,
+ tsi_ssl_client_handshaker_factory** factory) {
+ SSL_CTX* ssl_context = nullptr;
+ tsi_ssl_client_handshaker_factory* impl = nullptr;
+ tsi_result result = TSI_OK;
+
+ gpr_once_init(&g_init_openssl_once, init_openssl);
+
+ if (factory == nullptr) return TSI_INVALID_ARGUMENT;
+ *factory = nullptr;
+ if (options->pem_root_certs == nullptr && options->root_store == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+
#if OPENSSL_VERSION_NUMBER >= 0x10100000
ssl_context = SSL_CTX_new(TLS_method());
#else
- ssl_context = SSL_CTX_new(TLSv1_2_method());
+ ssl_context = SSL_CTX_new(TLSv1_2_method());
#endif
result = tsi_set_min_and_max_tls_versions(
ssl_context, options->min_tls_version, options->max_tls_version);
if (result != TSI_OK) return result;
- if (ssl_context == nullptr) {
- gpr_log(GPR_ERROR, "Could not create ssl context.");
- return TSI_INVALID_ARGUMENT;
- }
-
- impl = static_cast<tsi_ssl_client_handshaker_factory*>(
- gpr_zalloc(sizeof(*impl)));
- tsi_ssl_handshaker_factory_init(&impl->base);
- impl->base.vtable = &client_handshaker_factory_vtable;
- impl->ssl_context = ssl_context;
- if (options->session_cache != nullptr) {
- // Unref is called manually on factory destruction.
- impl->session_cache =
- reinterpret_cast<tsi::SslSessionLRUCache*>(options->session_cache)
- ->Ref();
- SSL_CTX_set_ex_data(ssl_context, g_ssl_ctx_ex_factory_index, impl);
- SSL_CTX_sess_set_new_cb(ssl_context,
- server_handshaker_factory_new_session_callback);
- SSL_CTX_set_session_cache_mode(ssl_context, SSL_SESS_CACHE_CLIENT);
- }
-
- do {
- result = populate_ssl_context(ssl_context, options->pem_key_cert_pair,
- options->cipher_suites);
- if (result != TSI_OK) break;
-
-#if OPENSSL_VERSION_NUMBER >= 0x10100000
- // X509_STORE_up_ref is only available since OpenSSL 1.1.
- if (options->root_store != nullptr) {
- X509_STORE_up_ref(options->root_store->store);
- SSL_CTX_set_cert_store(ssl_context, options->root_store->store);
- }
-#endif
- if (OPENSSL_VERSION_NUMBER < 0x10100000 || options->root_store == nullptr) {
- result = ssl_ctx_load_verification_certs(
- ssl_context, options->pem_root_certs, strlen(options->pem_root_certs),
- nullptr);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Cannot load server root certificates.");
- break;
- }
- }
-
- if (options->num_alpn_protocols != 0) {
- result = build_alpn_protocol_name_list(
- options->alpn_protocols, options->num_alpn_protocols,
- &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Building alpn list failed with error %s.",
- tsi_result_to_string(result));
- break;
- }
-#if TSI_OPENSSL_ALPN_SUPPORT
- GPR_ASSERT(impl->alpn_protocol_list_length < UINT_MAX);
- if (SSL_CTX_set_alpn_protos(
- ssl_context, impl->alpn_protocol_list,
- static_cast<unsigned int>(impl->alpn_protocol_list_length))) {
- gpr_log(GPR_ERROR, "Could not set alpn protocol list to context.");
- result = TSI_INVALID_ARGUMENT;
- break;
- }
-#endif /* TSI_OPENSSL_ALPN_SUPPORT */
- SSL_CTX_set_next_proto_select_cb(
- ssl_context, client_handshaker_factory_npn_callback, impl);
- }
- } while (0);
- if (result != TSI_OK) {
- tsi_ssl_handshaker_factory_unref(&impl->base);
- return result;
- }
+ if (ssl_context == nullptr) {
+ gpr_log(GPR_ERROR, "Could not create ssl context.");
+ return TSI_INVALID_ARGUMENT;
+ }
+
+ impl = static_cast<tsi_ssl_client_handshaker_factory*>(
+ gpr_zalloc(sizeof(*impl)));
+ tsi_ssl_handshaker_factory_init(&impl->base);
+ impl->base.vtable = &client_handshaker_factory_vtable;
+ impl->ssl_context = ssl_context;
+ if (options->session_cache != nullptr) {
+ // Unref is called manually on factory destruction.
+ impl->session_cache =
+ reinterpret_cast<tsi::SslSessionLRUCache*>(options->session_cache)
+ ->Ref();
+ SSL_CTX_set_ex_data(ssl_context, g_ssl_ctx_ex_factory_index, impl);
+ SSL_CTX_sess_set_new_cb(ssl_context,
+ server_handshaker_factory_new_session_callback);
+ SSL_CTX_set_session_cache_mode(ssl_context, SSL_SESS_CACHE_CLIENT);
+ }
+
+ do {
+ result = populate_ssl_context(ssl_context, options->pem_key_cert_pair,
+ options->cipher_suites);
+ if (result != TSI_OK) break;
+
+#if OPENSSL_VERSION_NUMBER >= 0x10100000
+ // X509_STORE_up_ref is only available since OpenSSL 1.1.
+ if (options->root_store != nullptr) {
+ X509_STORE_up_ref(options->root_store->store);
+ SSL_CTX_set_cert_store(ssl_context, options->root_store->store);
+ }
+#endif
+ if (OPENSSL_VERSION_NUMBER < 0x10100000 || options->root_store == nullptr) {
+ result = ssl_ctx_load_verification_certs(
+ ssl_context, options->pem_root_certs, strlen(options->pem_root_certs),
+ nullptr);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Cannot load server root certificates.");
+ break;
+ }
+ }
+
+ if (options->num_alpn_protocols != 0) {
+ result = build_alpn_protocol_name_list(
+ options->alpn_protocols, options->num_alpn_protocols,
+ &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Building alpn list failed with error %s.",
+ tsi_result_to_string(result));
+ break;
+ }
+#if TSI_OPENSSL_ALPN_SUPPORT
+ GPR_ASSERT(impl->alpn_protocol_list_length < UINT_MAX);
+ if (SSL_CTX_set_alpn_protos(
+ ssl_context, impl->alpn_protocol_list,
+ static_cast<unsigned int>(impl->alpn_protocol_list_length))) {
+ gpr_log(GPR_ERROR, "Could not set alpn protocol list to context.");
+ result = TSI_INVALID_ARGUMENT;
+ break;
+ }
+#endif /* TSI_OPENSSL_ALPN_SUPPORT */
+ SSL_CTX_set_next_proto_select_cb(
+ ssl_context, client_handshaker_factory_npn_callback, impl);
+ }
+ } while (0);
+ if (result != TSI_OK) {
+ tsi_ssl_handshaker_factory_unref(&impl->base);
+ return result;
+ }
if (options->skip_server_certificate_verification) {
SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, NullVerifyCallback);
} else {
SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, nullptr);
}
- /* TODO(jboeuf): Add revocation verification. */
-
- *factory = impl;
- return TSI_OK;
-}
-
-static tsi_ssl_handshaker_factory_vtable server_handshaker_factory_vtable = {
- tsi_ssl_server_handshaker_factory_destroy};
-
-tsi_result tsi_create_ssl_server_handshaker_factory(
- const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs, const char* pem_client_root_certs,
- int force_client_auth, const char* cipher_suites,
- const char** alpn_protocols, uint16_t num_alpn_protocols,
- tsi_ssl_server_handshaker_factory** factory) {
- return tsi_create_ssl_server_handshaker_factory_ex(
- pem_key_cert_pairs, num_key_cert_pairs, pem_client_root_certs,
- force_client_auth ? TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
- : TSI_DONT_REQUEST_CLIENT_CERTIFICATE,
- cipher_suites, alpn_protocols, num_alpn_protocols, factory);
-}
-
-tsi_result tsi_create_ssl_server_handshaker_factory_ex(
- const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs, const char* pem_client_root_certs,
- tsi_client_certificate_request_type client_certificate_request,
- const char* cipher_suites, const char** alpn_protocols,
- uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory) {
- 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_client_root_certs;
- options.client_certificate_request = client_certificate_request;
- options.cipher_suites = cipher_suites;
- options.alpn_protocols = alpn_protocols;
- options.num_alpn_protocols = num_alpn_protocols;
- return tsi_create_ssl_server_handshaker_factory_with_options(&options,
- factory);
-}
-
-tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
- const tsi_ssl_server_handshaker_options* options,
- tsi_ssl_server_handshaker_factory** factory) {
- tsi_ssl_server_handshaker_factory* impl = nullptr;
- tsi_result result = TSI_OK;
- size_t i = 0;
-
- gpr_once_init(&g_init_openssl_once, init_openssl);
-
- if (factory == nullptr) return TSI_INVALID_ARGUMENT;
- *factory = nullptr;
- if (options->num_key_cert_pairs == 0 ||
- options->pem_key_cert_pairs == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
-
- impl = static_cast<tsi_ssl_server_handshaker_factory*>(
- gpr_zalloc(sizeof(*impl)));
- tsi_ssl_handshaker_factory_init(&impl->base);
- impl->base.vtable = &server_handshaker_factory_vtable;
-
- impl->ssl_contexts = static_cast<SSL_CTX**>(
- gpr_zalloc(options->num_key_cert_pairs * sizeof(SSL_CTX*)));
- impl->ssl_context_x509_subject_names = static_cast<tsi_peer*>(
- gpr_zalloc(options->num_key_cert_pairs * sizeof(tsi_peer)));
- if (impl->ssl_contexts == nullptr ||
- impl->ssl_context_x509_subject_names == nullptr) {
- tsi_ssl_handshaker_factory_unref(&impl->base);
- return TSI_OUT_OF_RESOURCES;
- }
- impl->ssl_context_count = options->num_key_cert_pairs;
-
- if (options->num_alpn_protocols > 0) {
- result = build_alpn_protocol_name_list(
- options->alpn_protocols, options->num_alpn_protocols,
- &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
- if (result != TSI_OK) {
- tsi_ssl_handshaker_factory_unref(&impl->base);
- return result;
- }
- }
-
- for (i = 0; i < options->num_key_cert_pairs; i++) {
- do {
+ /* TODO(jboeuf): Add revocation verification. */
+
+ *factory = impl;
+ return TSI_OK;
+}
+
+static tsi_ssl_handshaker_factory_vtable server_handshaker_factory_vtable = {
+ tsi_ssl_server_handshaker_factory_destroy};
+
+tsi_result tsi_create_ssl_server_handshaker_factory(
+ const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs, const char* pem_client_root_certs,
+ int force_client_auth, const char* cipher_suites,
+ const char** alpn_protocols, uint16_t num_alpn_protocols,
+ tsi_ssl_server_handshaker_factory** factory) {
+ return tsi_create_ssl_server_handshaker_factory_ex(
+ pem_key_cert_pairs, num_key_cert_pairs, pem_client_root_certs,
+ force_client_auth ? TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
+ : TSI_DONT_REQUEST_CLIENT_CERTIFICATE,
+ cipher_suites, alpn_protocols, num_alpn_protocols, factory);
+}
+
+tsi_result tsi_create_ssl_server_handshaker_factory_ex(
+ const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs, const char* pem_client_root_certs,
+ tsi_client_certificate_request_type client_certificate_request,
+ const char* cipher_suites, const char** alpn_protocols,
+ uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory) {
+ 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_client_root_certs;
+ options.client_certificate_request = client_certificate_request;
+ options.cipher_suites = cipher_suites;
+ options.alpn_protocols = alpn_protocols;
+ options.num_alpn_protocols = num_alpn_protocols;
+ return tsi_create_ssl_server_handshaker_factory_with_options(&options,
+ factory);
+}
+
+tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
+ const tsi_ssl_server_handshaker_options* options,
+ tsi_ssl_server_handshaker_factory** factory) {
+ tsi_ssl_server_handshaker_factory* impl = nullptr;
+ tsi_result result = TSI_OK;
+ size_t i = 0;
+
+ gpr_once_init(&g_init_openssl_once, init_openssl);
+
+ if (factory == nullptr) return TSI_INVALID_ARGUMENT;
+ *factory = nullptr;
+ if (options->num_key_cert_pairs == 0 ||
+ options->pem_key_cert_pairs == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+
+ impl = static_cast<tsi_ssl_server_handshaker_factory*>(
+ gpr_zalloc(sizeof(*impl)));
+ tsi_ssl_handshaker_factory_init(&impl->base);
+ impl->base.vtable = &server_handshaker_factory_vtable;
+
+ impl->ssl_contexts = static_cast<SSL_CTX**>(
+ gpr_zalloc(options->num_key_cert_pairs * sizeof(SSL_CTX*)));
+ impl->ssl_context_x509_subject_names = static_cast<tsi_peer*>(
+ gpr_zalloc(options->num_key_cert_pairs * sizeof(tsi_peer)));
+ if (impl->ssl_contexts == nullptr ||
+ impl->ssl_context_x509_subject_names == nullptr) {
+ tsi_ssl_handshaker_factory_unref(&impl->base);
+ return TSI_OUT_OF_RESOURCES;
+ }
+ impl->ssl_context_count = options->num_key_cert_pairs;
+
+ if (options->num_alpn_protocols > 0) {
+ result = build_alpn_protocol_name_list(
+ options->alpn_protocols, options->num_alpn_protocols,
+ &impl->alpn_protocol_list, &impl->alpn_protocol_list_length);
+ if (result != TSI_OK) {
+ tsi_ssl_handshaker_factory_unref(&impl->base);
+ return result;
+ }
+ }
+
+ for (i = 0; i < options->num_key_cert_pairs; i++) {
+ do {
#if OPENSSL_VERSION_NUMBER >= 0x10100000
impl->ssl_contexts[i] = SSL_CTX_new(TLS_method());
#else
- impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method());
+ impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method());
#endif
result = tsi_set_min_and_max_tls_versions(impl->ssl_contexts[i],
options->min_tls_version,
options->max_tls_version);
if (result != TSI_OK) return result;
- if (impl->ssl_contexts[i] == nullptr) {
- gpr_log(GPR_ERROR, "Could not create ssl context.");
- result = TSI_OUT_OF_RESOURCES;
- break;
- }
- result = populate_ssl_context(impl->ssl_contexts[i],
- &options->pem_key_cert_pairs[i],
- options->cipher_suites);
- if (result != TSI_OK) break;
-
- // TODO(elessar): Provide ability to disable session ticket keys.
-
- // Allow client cache sessions (it's needed for OpenSSL only).
- int set_sid_ctx_result = SSL_CTX_set_session_id_context(
- impl->ssl_contexts[i], kSslSessionIdContext,
- GPR_ARRAY_SIZE(kSslSessionIdContext));
- if (set_sid_ctx_result == 0) {
- gpr_log(GPR_ERROR, "Failed to set session id context.");
- result = TSI_INTERNAL_ERROR;
- break;
- }
-
- if (options->session_ticket_key != nullptr) {
- if (SSL_CTX_set_tlsext_ticket_keys(
- impl->ssl_contexts[i],
- const_cast<char*>(options->session_ticket_key),
- options->session_ticket_key_size) == 0) {
- gpr_log(GPR_ERROR, "Invalid STEK size.");
- result = TSI_INVALID_ARGUMENT;
- break;
- }
- }
-
- if (options->pem_client_root_certs != nullptr) {
- STACK_OF(X509_NAME)* root_names = nullptr;
- result = ssl_ctx_load_verification_certs(
- impl->ssl_contexts[i], options->pem_client_root_certs,
- strlen(options->pem_client_root_certs), &root_names);
- if (result != TSI_OK) {
- gpr_log(GPR_ERROR, "Invalid verification certs.");
- break;
- }
- SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names);
- }
+ if (impl->ssl_contexts[i] == nullptr) {
+ gpr_log(GPR_ERROR, "Could not create ssl context.");
+ result = TSI_OUT_OF_RESOURCES;
+ break;
+ }
+ result = populate_ssl_context(impl->ssl_contexts[i],
+ &options->pem_key_cert_pairs[i],
+ options->cipher_suites);
+ if (result != TSI_OK) break;
+
+ // TODO(elessar): Provide ability to disable session ticket keys.
+
+ // Allow client cache sessions (it's needed for OpenSSL only).
+ int set_sid_ctx_result = SSL_CTX_set_session_id_context(
+ impl->ssl_contexts[i], kSslSessionIdContext,
+ GPR_ARRAY_SIZE(kSslSessionIdContext));
+ if (set_sid_ctx_result == 0) {
+ gpr_log(GPR_ERROR, "Failed to set session id context.");
+ result = TSI_INTERNAL_ERROR;
+ break;
+ }
+
+ if (options->session_ticket_key != nullptr) {
+ if (SSL_CTX_set_tlsext_ticket_keys(
+ impl->ssl_contexts[i],
+ const_cast<char*>(options->session_ticket_key),
+ options->session_ticket_key_size) == 0) {
+ gpr_log(GPR_ERROR, "Invalid STEK size.");
+ result = TSI_INVALID_ARGUMENT;
+ break;
+ }
+ }
+
+ if (options->pem_client_root_certs != nullptr) {
+ STACK_OF(X509_NAME)* root_names = nullptr;
+ result = ssl_ctx_load_verification_certs(
+ impl->ssl_contexts[i], options->pem_client_root_certs,
+ strlen(options->pem_client_root_certs), &root_names);
+ if (result != TSI_OK) {
+ gpr_log(GPR_ERROR, "Invalid verification certs.");
+ break;
+ }
+ SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names);
+ }
switch (options->client_certificate_request) {
case TSI_DONT_REQUEST_CLIENT_CERTIFICATE:
SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, nullptr);
@@ -2142,84 +2142,84 @@ tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
break;
}
/* TODO(jboeuf): Add revocation verification. */
-
+
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;
-
- SSL_CTX_set_tlsext_servername_callback(
- impl->ssl_contexts[i],
- ssl_server_handshaker_factory_servername_callback);
- SSL_CTX_set_tlsext_servername_arg(impl->ssl_contexts[i], impl);
-#if TSI_OPENSSL_ALPN_SUPPORT
- SSL_CTX_set_alpn_select_cb(impl->ssl_contexts[i],
- server_handshaker_factory_alpn_callback, impl);
-#endif /* TSI_OPENSSL_ALPN_SUPPORT */
- SSL_CTX_set_next_protos_advertised_cb(
- impl->ssl_contexts[i],
- server_handshaker_factory_npn_advertised_callback, impl);
- } while (0);
-
- if (result != TSI_OK) {
- tsi_ssl_handshaker_factory_unref(&impl->base);
- return result;
- }
- }
-
- *factory = impl;
- return TSI_OK;
-}
-
-/* --- tsi_ssl utils. --- */
-
+ options->pem_key_cert_pairs[i].cert_chain,
+ &impl->ssl_context_x509_subject_names[i]);
+ if (result != TSI_OK) break;
+
+ SSL_CTX_set_tlsext_servername_callback(
+ impl->ssl_contexts[i],
+ ssl_server_handshaker_factory_servername_callback);
+ SSL_CTX_set_tlsext_servername_arg(impl->ssl_contexts[i], impl);
+#if TSI_OPENSSL_ALPN_SUPPORT
+ SSL_CTX_set_alpn_select_cb(impl->ssl_contexts[i],
+ server_handshaker_factory_alpn_callback, impl);
+#endif /* TSI_OPENSSL_ALPN_SUPPORT */
+ SSL_CTX_set_next_protos_advertised_cb(
+ impl->ssl_contexts[i],
+ server_handshaker_factory_npn_advertised_callback, impl);
+ } while (0);
+
+ if (result != TSI_OK) {
+ tsi_ssl_handshaker_factory_unref(&impl->base);
+ return result;
+ }
+ }
+
+ *factory = impl;
+ return TSI_OK;
+}
+
+/* --- tsi_ssl utils. --- */
+
int tsi_ssl_peer_matches_name(const tsi_peer* peer, y_absl::string_view name) {
- size_t i = 0;
- size_t san_count = 0;
- const tsi_peer_property* cn_property = nullptr;
- int like_ip = looks_like_ip_address(name);
-
- /* Check the SAN first. */
- for (i = 0; i < peer->property_count; i++) {
- const tsi_peer_property* property = &peer->properties[i];
- if (property->name == nullptr) continue;
- if (strcmp(property->name,
- TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) {
- san_count++;
-
+ size_t i = 0;
+ size_t san_count = 0;
+ const tsi_peer_property* cn_property = nullptr;
+ int like_ip = looks_like_ip_address(name);
+
+ /* Check the SAN first. */
+ for (i = 0; i < peer->property_count; i++) {
+ const tsi_peer_property* property = &peer->properties[i];
+ if (property->name == nullptr) continue;
+ if (strcmp(property->name,
+ TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) {
+ san_count++;
+
y_absl::string_view entry(property->value.data, property->value.length);
if (!like_ip && does_entry_match_name(entry, name)) {
- return 1;
+ return 1;
} else if (like_ip && name == entry) {
- /* IP Addresses are exact matches only. */
- return 1;
- }
- } else if (strcmp(property->name,
- TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) {
- cn_property = property;
- }
- }
-
- /* If there's no SAN, try the CN, but only if its not like an IP Address */
- if (san_count == 0 && cn_property != nullptr && !like_ip) {
+ /* IP Addresses are exact matches only. */
+ return 1;
+ }
+ } else if (strcmp(property->name,
+ TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) {
+ cn_property = property;
+ }
+ }
+
+ /* If there's no SAN, try the CN, but only if its not like an IP Address */
+ 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)) {
- return 1;
- }
- }
-
- return 0; /* Not found. */
-}
-
-/* --- Testing support. --- */
-const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable(
- tsi_ssl_handshaker_factory* factory,
- tsi_ssl_handshaker_factory_vtable* new_vtable) {
- GPR_ASSERT(factory != nullptr);
- GPR_ASSERT(factory->vtable != nullptr);
-
- const tsi_ssl_handshaker_factory_vtable* orig_vtable = factory->vtable;
- factory->vtable = new_vtable;
- return orig_vtable;
-}
+ return 1;
+ }
+ }
+
+ return 0; /* Not found. */
+}
+
+/* --- Testing support. --- */
+const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable(
+ tsi_ssl_handshaker_factory* factory,
+ tsi_ssl_handshaker_factory_vtable* new_vtable) {
+ GPR_ASSERT(factory != nullptr);
+ GPR_ASSERT(factory->vtable != nullptr);
+
+ const tsi_ssl_handshaker_factory_vtable* orig_vtable = factory->vtable;
+ factory->vtable = new_vtable;
+ return orig_vtable;
+}
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 2f2dc08c053..bf9e8a38be1 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.h
+++ b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.h
@@ -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.
- *
- */
-
-#ifndef GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_H
-#define GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_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_TSI_SSL_TRANSPORT_SECURITY_H
+#define GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_H
+
+#include <grpc/support/port_platform.h>
+
#include <grpc/grpc_security_constants.h>
#include "y_absl/strings/string_view.h"
-#include "src/core/tsi/transport_security_interface.h"
-
+#include "src/core/tsi/transport_security_interface.h"
+
extern "C" {
#include <openssl/x509.h>
}
-/* Value for the TSI_CERTIFICATE_TYPE_PEER_PROPERTY property for X509 certs. */
-#define TSI_X509_CERTIFICATE_TYPE "X509"
-
-/* This property is of type TSI_PEER_PROPERTY_STRING. */
-#define TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY "x509_subject_common_name"
-#define TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY \
- "x509_subject_alternative_name"
-#define TSI_SSL_SESSION_REUSED_PEER_PROPERTY "ssl_session_reused"
-
-#define TSI_X509_PEM_CERT_PROPERTY "x509_pem_cert"
-
+/* Value for the TSI_CERTIFICATE_TYPE_PEER_PROPERTY property for X509 certs. */
+#define TSI_X509_CERTIFICATE_TYPE "X509"
+
+/* This property is of type TSI_PEER_PROPERTY_STRING. */
+#define TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY "x509_subject_common_name"
+#define TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY \
+ "x509_subject_alternative_name"
+#define TSI_SSL_SESSION_REUSED_PEER_PROPERTY "ssl_session_reused"
+
+#define TSI_X509_PEM_CERT_PROPERTY "x509_pem_cert"
+
#define TSI_X509_PEM_CERT_CHAIN_PROPERTY "x509_pem_cert_chain"
-#define TSI_SSL_ALPN_SELECTED_PROTOCOL "ssl_alpn_selected_protocol"
-
+#define TSI_SSL_ALPN_SELECTED_PROTOCOL "ssl_alpn_selected_protocol"
+
#define TSI_X509_URI_PEER_PROPERTY "x509_uri"
-/* --- tsi_ssl_root_certs_store object ---
-
- This object stores SSL root certificates. It can be shared by multiple SSL
- context. */
-typedef struct tsi_ssl_root_certs_store tsi_ssl_root_certs_store;
-
-/* Given a NULL-terminated string containing the PEM encoding of the root
- certificates, creates a tsi_ssl_root_certs_store object. */
-tsi_ssl_root_certs_store* tsi_ssl_root_certs_store_create(
- const char* pem_roots);
-
-/* Destroys the tsi_ssl_root_certs_store object. */
-void tsi_ssl_root_certs_store_destroy(tsi_ssl_root_certs_store* self);
-
-/* --- tsi_ssl_session_cache object ---
-
- Cache for SSL sessions for sessions resumption. */
-
-typedef struct tsi_ssl_session_cache tsi_ssl_session_cache;
-
-/* Create LRU cache for SSL sessions with \a capacity. */
-tsi_ssl_session_cache* tsi_ssl_session_cache_create_lru(size_t capacity);
-
-/* Increment reference counter of \a cache. */
-void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache);
-
-/* Decrement reference counter of \a cache. */
-void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache);
-
-/* --- tsi_ssl_client_handshaker_factory object ---
-
- This object creates a client tsi_handshaker objects implemented in terms of
- the TLS 1.2 specificiation. */
-
-typedef struct tsi_ssl_client_handshaker_factory
- tsi_ssl_client_handshaker_factory;
-
-/* Object that holds a private key / certificate chain pair in PEM format. */
+/* --- tsi_ssl_root_certs_store object ---
+
+ This object stores SSL root certificates. It can be shared by multiple SSL
+ context. */
+typedef struct tsi_ssl_root_certs_store tsi_ssl_root_certs_store;
+
+/* Given a NULL-terminated string containing the PEM encoding of the root
+ certificates, creates a tsi_ssl_root_certs_store object. */
+tsi_ssl_root_certs_store* tsi_ssl_root_certs_store_create(
+ const char* pem_roots);
+
+/* Destroys the tsi_ssl_root_certs_store object. */
+void tsi_ssl_root_certs_store_destroy(tsi_ssl_root_certs_store* self);
+
+/* --- tsi_ssl_session_cache object ---
+
+ Cache for SSL sessions for sessions resumption. */
+
+typedef struct tsi_ssl_session_cache tsi_ssl_session_cache;
+
+/* Create LRU cache for SSL sessions with \a capacity. */
+tsi_ssl_session_cache* tsi_ssl_session_cache_create_lru(size_t capacity);
+
+/* Increment reference counter of \a cache. */
+void tsi_ssl_session_cache_ref(tsi_ssl_session_cache* cache);
+
+/* Decrement reference counter of \a cache. */
+void tsi_ssl_session_cache_unref(tsi_ssl_session_cache* cache);
+
+/* --- tsi_ssl_client_handshaker_factory object ---
+
+ This object creates a client tsi_handshaker objects implemented in terms of
+ the TLS 1.2 specificiation. */
+
+typedef struct tsi_ssl_client_handshaker_factory
+ tsi_ssl_client_handshaker_factory;
+
+/* Object that holds a private key / certificate chain pair in PEM format. */
struct tsi_ssl_pem_key_cert_pair {
- /* private_key is the NULL-terminated string containing the PEM encoding of
- the client's private key. */
- const char* private_key;
-
- /* cert_chain is the NULL-terminated string containing the PEM encoding of
- the client's certificate chain. */
- const char* cert_chain;
+ /* private_key is the NULL-terminated string containing the PEM encoding of
+ the client's private key. */
+ const char* private_key;
+
+ /* cert_chain is the NULL-terminated string containing the PEM encoding of
+ the client's certificate chain. */
+ const char* cert_chain;
};
-/* TO BE DEPRECATED.
- Creates a client handshaker factory.
- - 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.
- - pem_roots_cert is the NULL-terminated string containing the PEM encoding of
- the server root certificates.
- - cipher_suites contains an optional list of the ciphers that the client
- supports. The format of this string is described in:
- https://www.openssl.org/docs/apps/ciphers.html.
- This parameter can be set to NULL to use the default set of ciphers.
- TODO(jboeuf): Revisit the format of this parameter.
- - alpn_protocols is an array containing the NULL terminated protocol names
- that the handshakers created with this factory support. This parameter can
- be NULL.
- - num_alpn_protocols is the number of alpn protocols and associated lengths
- specified. If this parameter is 0, the other alpn parameters must be NULL.
- - factory is the address of the factory pointer to be created.
-
- - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
- where a parameter is invalid. */
-tsi_result tsi_create_ssl_client_handshaker_factory(
- const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair,
- const char* pem_root_certs, const char* cipher_suites,
- const char** alpn_protocols, uint16_t num_alpn_protocols,
- tsi_ssl_client_handshaker_factory** factory);
-
+/* TO BE DEPRECATED.
+ Creates a client handshaker factory.
+ - 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.
+ - pem_roots_cert is the NULL-terminated string containing the PEM encoding of
+ the server root certificates.
+ - cipher_suites contains an optional list of the ciphers that the client
+ supports. The format of this string is described in:
+ https://www.openssl.org/docs/apps/ciphers.html.
+ This parameter can be set to NULL to use the default set of ciphers.
+ TODO(jboeuf): Revisit the format of this parameter.
+ - alpn_protocols is an array containing the NULL terminated protocol names
+ that the handshakers created with this factory support. This parameter can
+ be NULL.
+ - num_alpn_protocols is the number of alpn protocols and associated lengths
+ specified. If this parameter is 0, the other alpn parameters must be NULL.
+ - factory is the address of the factory pointer to be created.
+
+ - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
+ where a parameter is invalid. */
+tsi_result tsi_create_ssl_client_handshaker_factory(
+ const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair,
+ const char* pem_root_certs, const char* cipher_suites,
+ const char** alpn_protocols, uint16_t num_alpn_protocols,
+ tsi_ssl_client_handshaker_factory** factory);
+
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. */
- const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair;
- /* pem_roots_cert is the NULL-terminated string containing the PEM encoding of
- the client root certificates. */
- const char* pem_root_certs;
- /* root_store is a pointer to the ssl_root_certs_store object. If root_store
- is not nullptr and SSL implementation permits, root_store will be used as
- root certificates. Otherwise, pem_roots_cert will be used to load server
- root certificates. */
- const tsi_ssl_root_certs_store* root_store;
- /* cipher_suites contains an optional list of the ciphers that the client
- supports. The format of this string is described in:
- https://www.openssl.org/docs/apps/ciphers.html.
- This parameter can be set to NULL to use the default set of ciphers.
- TODO(jboeuf): Revisit the format of this parameter. */
- const char* cipher_suites;
- /* alpn_protocols is an array containing the NULL terminated protocol names
- that the handshakers created with this factory support. This parameter can
- be NULL. */
- const char** alpn_protocols;
- /* num_alpn_protocols is the number of alpn protocols and associated lengths
- specified. If this parameter is 0, the other alpn parameters must be
- NULL. */
- size_t num_alpn_protocols;
- /* ssl_session_cache is a cache for reusable client-side sessions. */
- tsi_ssl_session_cache* session_cache;
-
+ /* 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. */
+ const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair;
+ /* pem_roots_cert is the NULL-terminated string containing the PEM encoding of
+ the client root certificates. */
+ const char* pem_root_certs;
+ /* root_store is a pointer to the ssl_root_certs_store object. If root_store
+ is not nullptr and SSL implementation permits, root_store will be used as
+ root certificates. Otherwise, pem_roots_cert will be used to load server
+ root certificates. */
+ const tsi_ssl_root_certs_store* root_store;
+ /* cipher_suites contains an optional list of the ciphers that the client
+ supports. The format of this string is described in:
+ https://www.openssl.org/docs/apps/ciphers.html.
+ This parameter can be set to NULL to use the default set of ciphers.
+ TODO(jboeuf): Revisit the format of this parameter. */
+ const char* cipher_suites;
+ /* alpn_protocols is an array containing the NULL terminated protocol names
+ that the handshakers created with this factory support. This parameter can
+ be NULL. */
+ const char** alpn_protocols;
+ /* num_alpn_protocols is the number of alpn protocols and associated lengths
+ specified. If this parameter is 0, the other alpn parameters must be
+ NULL. */
+ size_t num_alpn_protocols;
+ /* ssl_session_cache is a cache for reusable client-side sessions. */
+ tsi_ssl_session_cache* session_cache;
+
/* skip server certificate verification. */
bool skip_server_certificate_verification;
@@ -170,123 +170,123 @@ struct tsi_ssl_client_handshaker_options {
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.
-
- - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
- where a parameter is invalid. */
-tsi_result tsi_create_ssl_client_handshaker_factory_with_options(
- const tsi_ssl_client_handshaker_options* options,
- tsi_ssl_client_handshaker_factory** factory);
-
-/* Creates a client handshaker.
- - self is the factory from which the handshaker will be created.
- - server_name_indication indicates the name of the server the client is
- trying to connect to which will be relayed to the server using the SNI
- extension.
- - handshaker is the address of the handshaker pointer to be created.
-
- - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
- where a parameter is invalid. */
-tsi_result tsi_ssl_client_handshaker_factory_create_handshaker(
- tsi_ssl_client_handshaker_factory* self, const char* server_name_indication,
- tsi_handshaker** handshaker);
-
-/* Decrements reference count of the handshaker factory. Handshaker factory will
- * be destroyed once no references exist. */
-void tsi_ssl_client_handshaker_factory_unref(
- tsi_ssl_client_handshaker_factory* factory);
-
-/* --- tsi_ssl_server_handshaker_factory object ---
-
- This object creates a client tsi_handshaker objects implemented in terms of
- the TLS 1.2 specificiation. */
-
-typedef struct tsi_ssl_server_handshaker_factory
- tsi_ssl_server_handshaker_factory;
-
-/* TO BE DEPRECATED.
- Creates a server handshaker factory.
- - pem_key_cert_pairs is an array private key / certificate chains of the
- server.
- - num_key_cert_pairs is the number of items in the pem_key_cert_pairs array.
- - pem_root_certs is the NULL-terminated string containing the PEM encoding
- of the client root certificates. This parameter may be NULL if the server
- does not want the client to be authenticated with SSL.
- - cipher_suites contains an optional list of the ciphers that the server
- supports. The format of this string is described in:
- https://www.openssl.org/docs/apps/ciphers.html.
- This parameter can be set to NULL to use the default set of ciphers.
- TODO(jboeuf): Revisit the format of this parameter.
- - alpn_protocols is an array containing the NULL terminated protocol names
- that the handshakers created with this factory support. This parameter can
- be NULL.
- - num_alpn_protocols is the number of alpn protocols and associated lengths
- specified. If this parameter is 0, the other alpn parameters must be NULL.
- - factory is the address of the factory pointer to be created.
-
- - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
- where a parameter is invalid. */
-tsi_result tsi_create_ssl_server_handshaker_factory(
- const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs, const char* pem_client_root_certs,
- int force_client_auth, const char* cipher_suites,
- const char** alpn_protocols, uint16_t num_alpn_protocols,
- tsi_ssl_server_handshaker_factory** factory);
-
-/* TO BE DEPRECATED.
- Same as tsi_create_ssl_server_handshaker_factory method except uses
- tsi_client_certificate_request_type to support more ways to handle client
- certificate authentication.
- - client_certificate_request, if set to non-zero will force the client to
- authenticate with an SSL cert. Note that this option is ignored if
- pem_client_root_certs is NULL or pem_client_roots_certs_size is 0 */
-tsi_result tsi_create_ssl_server_handshaker_factory_ex(
- const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
- size_t num_key_cert_pairs, const char* pem_client_root_certs,
- tsi_client_certificate_request_type client_certificate_request,
- const char* cipher_suites, const char** alpn_protocols,
- uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory);
-
+/* 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.
+
+ - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
+ where a parameter is invalid. */
+tsi_result tsi_create_ssl_client_handshaker_factory_with_options(
+ const tsi_ssl_client_handshaker_options* options,
+ tsi_ssl_client_handshaker_factory** factory);
+
+/* Creates a client handshaker.
+ - self is the factory from which the handshaker will be created.
+ - server_name_indication indicates the name of the server the client is
+ trying to connect to which will be relayed to the server using the SNI
+ extension.
+ - handshaker is the address of the handshaker pointer to be created.
+
+ - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
+ where a parameter is invalid. */
+tsi_result tsi_ssl_client_handshaker_factory_create_handshaker(
+ tsi_ssl_client_handshaker_factory* self, const char* server_name_indication,
+ tsi_handshaker** handshaker);
+
+/* Decrements reference count of the handshaker factory. Handshaker factory will
+ * be destroyed once no references exist. */
+void tsi_ssl_client_handshaker_factory_unref(
+ tsi_ssl_client_handshaker_factory* factory);
+
+/* --- tsi_ssl_server_handshaker_factory object ---
+
+ This object creates a client tsi_handshaker objects implemented in terms of
+ the TLS 1.2 specificiation. */
+
+typedef struct tsi_ssl_server_handshaker_factory
+ tsi_ssl_server_handshaker_factory;
+
+/* TO BE DEPRECATED.
+ Creates a server handshaker factory.
+ - pem_key_cert_pairs is an array private key / certificate chains of the
+ server.
+ - num_key_cert_pairs is the number of items in the pem_key_cert_pairs array.
+ - pem_root_certs is the NULL-terminated string containing the PEM encoding
+ of the client root certificates. This parameter may be NULL if the server
+ does not want the client to be authenticated with SSL.
+ - cipher_suites contains an optional list of the ciphers that the server
+ supports. The format of this string is described in:
+ https://www.openssl.org/docs/apps/ciphers.html.
+ This parameter can be set to NULL to use the default set of ciphers.
+ TODO(jboeuf): Revisit the format of this parameter.
+ - alpn_protocols is an array containing the NULL terminated protocol names
+ that the handshakers created with this factory support. This parameter can
+ be NULL.
+ - num_alpn_protocols is the number of alpn protocols and associated lengths
+ specified. If this parameter is 0, the other alpn parameters must be NULL.
+ - factory is the address of the factory pointer to be created.
+
+ - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
+ where a parameter is invalid. */
+tsi_result tsi_create_ssl_server_handshaker_factory(
+ const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs, const char* pem_client_root_certs,
+ int force_client_auth, const char* cipher_suites,
+ const char** alpn_protocols, uint16_t num_alpn_protocols,
+ tsi_ssl_server_handshaker_factory** factory);
+
+/* TO BE DEPRECATED.
+ Same as tsi_create_ssl_server_handshaker_factory method except uses
+ tsi_client_certificate_request_type to support more ways to handle client
+ certificate authentication.
+ - client_certificate_request, if set to non-zero will force the client to
+ authenticate with an SSL cert. Note that this option is ignored if
+ pem_client_root_certs is NULL or pem_client_roots_certs_size is 0 */
+tsi_result tsi_create_ssl_server_handshaker_factory_ex(
+ const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs,
+ size_t num_key_cert_pairs, const char* pem_client_root_certs,
+ tsi_client_certificate_request_type client_certificate_request,
+ 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 {
- /* 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;
- /* num_key_cert_pairs is the number of items in the pem_key_cert_pairs
- array. */
- size_t num_key_cert_pairs;
- /* pem_root_certs is the NULL-terminated string containing the PEM encoding
- of the server root certificates. This parameter may be NULL if the server
- does not want the client to be authenticated with SSL. */
- const char* pem_client_root_certs;
- /* client_certificate_request, if set to non-zero will force the client to
- authenticate with an SSL cert. Note that this option is ignored if
- pem_client_root_certs is NULL or pem_client_roots_certs_size is 0. */
- tsi_client_certificate_request_type client_certificate_request;
- /* cipher_suites contains an optional list of the ciphers that the server
- supports. The format of this string is described in:
- https://www.openssl.org/docs/apps/ciphers.html.
- This parameter can be set to NULL to use the default set of ciphers.
- TODO(jboeuf): Revisit the format of this parameter. */
- const char* cipher_suites;
- /* alpn_protocols is an array containing the NULL terminated protocol names
- that the handshakers created with this factory support. This parameter can
- be NULL. */
- const char** alpn_protocols;
- /* num_alpn_protocols is the number of alpn protocols and associated lengths
- specified. If this parameter is 0, the other alpn parameters must be
- NULL. */
- uint16_t num_alpn_protocols;
+ /* 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;
+ /* num_key_cert_pairs is the number of items in the pem_key_cert_pairs
+ array. */
+ size_t num_key_cert_pairs;
+ /* pem_root_certs is the NULL-terminated string containing the PEM encoding
+ of the server root certificates. This parameter may be NULL if the server
+ does not want the client to be authenticated with SSL. */
+ const char* pem_client_root_certs;
+ /* client_certificate_request, if set to non-zero will force the client to
+ authenticate with an SSL cert. Note that this option is ignored if
+ pem_client_root_certs is NULL or pem_client_roots_certs_size is 0. */
+ tsi_client_certificate_request_type client_certificate_request;
+ /* cipher_suites contains an optional list of the ciphers that the server
+ supports. The format of this string is described in:
+ https://www.openssl.org/docs/apps/ciphers.html.
+ This parameter can be set to NULL to use the default set of ciphers.
+ TODO(jboeuf): Revisit the format of this parameter. */
+ const char* cipher_suites;
+ /* alpn_protocols is an array containing the NULL terminated protocol names
+ that the handshakers created with this factory support. This parameter can
+ be NULL. */
+ const char** alpn_protocols;
+ /* num_alpn_protocols is the number of alpn protocols and associated lengths
+ 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. */
- const char* session_ticket_key;
- /* session_ticket_key_size is a size of session ticket encryption key. */
- size_t session_ticket_key_size;
+ const char* session_ticket_key;
+ /* session_ticket_key_size is a size of session ticket encryption key. */
+ size_t session_ticket_key_size;
/* The min and max TLS versions that will be negotiated by the handshaker. */
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),
@@ -301,59 +301,59 @@ struct tsi_ssl_server_handshaker_options {
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.
-
- - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
- where a parameter is invalid. */
-tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
- const tsi_ssl_server_handshaker_options* options,
- tsi_ssl_server_handshaker_factory** factory);
-
-/* Creates a server handshaker.
- - self is the factory from which the handshaker will be created.
- - handshaker is the address of the handshaker pointer to be created.
-
- - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
- where a parameter is invalid. */
-tsi_result tsi_ssl_server_handshaker_factory_create_handshaker(
- tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker);
-
-/* Decrements reference count of the handshaker factory. Handshaker factory will
- * be destroyed once no references exist. */
-void tsi_ssl_server_handshaker_factory_unref(
- tsi_ssl_server_handshaker_factory* self);
-
-/* Util that checks that an ssl peer matches a specific name.
- Still TODO(jboeuf):
- - handle mixed case.
- - handle %encoded chars.
- - handle public suffix wildchar more strictly (e.g. *.co.uk) */
+/* 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.
+
+ - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
+ where a parameter is invalid. */
+tsi_result tsi_create_ssl_server_handshaker_factory_with_options(
+ const tsi_ssl_server_handshaker_options* options,
+ tsi_ssl_server_handshaker_factory** factory);
+
+/* Creates a server handshaker.
+ - self is the factory from which the handshaker will be created.
+ - handshaker is the address of the handshaker pointer to be created.
+
+ - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
+ where a parameter is invalid. */
+tsi_result tsi_ssl_server_handshaker_factory_create_handshaker(
+ tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker);
+
+/* Decrements reference count of the handshaker factory. Handshaker factory will
+ * be destroyed once no references exist. */
+void tsi_ssl_server_handshaker_factory_unref(
+ tsi_ssl_server_handshaker_factory* self);
+
+/* Util that checks that an ssl peer matches a specific name.
+ Still TODO(jboeuf):
+ - handle mixed case.
+ - handle %encoded chars.
+ - handle public suffix wildchar more strictly (e.g. *.co.uk) */
int tsi_ssl_peer_matches_name(const tsi_peer* peer, y_absl::string_view name);
-
-/* --- Testing support. ---
-
- These functions and typedefs are not intended to be used outside of testing.
- */
-
-/* Base type of client and server handshaker factories. */
-typedef struct tsi_ssl_handshaker_factory tsi_ssl_handshaker_factory;
-
-/* Function pointer to handshaker_factory destructor. */
-typedef void (*tsi_ssl_handshaker_factory_destructor)(
- tsi_ssl_handshaker_factory* factory);
-
-/* Virtual table for tsi_ssl_handshaker_factory. */
+
+/* --- Testing support. ---
+
+ These functions and typedefs are not intended to be used outside of testing.
+ */
+
+/* Base type of client and server handshaker factories. */
+typedef struct tsi_ssl_handshaker_factory tsi_ssl_handshaker_factory;
+
+/* Function pointer to handshaker_factory destructor. */
+typedef void (*tsi_ssl_handshaker_factory_destructor)(
+ tsi_ssl_handshaker_factory* factory);
+
+/* Virtual table for tsi_ssl_handshaker_factory. */
struct tsi_ssl_handshaker_factory_vtable {
- tsi_ssl_handshaker_factory_destructor destroy;
+ tsi_ssl_handshaker_factory_destructor destroy;
};
-/* Set destructor of handshaker_factory to new_destructor, returns previous
- destructor. */
-const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable(
- tsi_ssl_handshaker_factory* factory,
- tsi_ssl_handshaker_factory_vtable* new_vtable);
-
+/* Set destructor of handshaker_factory to new_destructor, returns previous
+ destructor. */
+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);
@@ -362,4 +362,4 @@ tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert(
tsi_result tsi_ssl_get_cert_chain_contents(STACK_OF(X509) * peer_chain,
tsi_peer_property* property);
-#endif /* GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_H */
+#endif /* GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_H */
diff --git a/contrib/libs/grpc/src/core/tsi/ssl_types.h b/contrib/libs/grpc/src/core/tsi/ssl_types.h
index b15d02be390..8b7d6d7e2ed 100644
--- a/contrib/libs/grpc/src/core/tsi/ssl_types.h
+++ b/contrib/libs/grpc/src/core/tsi/ssl_types.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_CORE_TSI_SSL_TYPES_H
-#define GRPC_CORE_TSI_SSL_TYPES_H
-
-/* A collection of macros to cast between various integer types that are
- * used differently between BoringSSL and OpenSSL:
- * TSI_INT_AS_SIZE(x): convert 'int x' to a length parameter for an OpenSSL
- * function
- * TSI_SIZE_AS_SIZE(x): convert 'size_t x' to a length parameter for an OpenSSL
- * function
- */
-
-#include <grpc/support/port_platform.h>
-
-#include <openssl/ssl.h>
-
-#ifdef OPENSSL_IS_BORINGSSL
-#define TSI_INT_AS_SIZE(x) ((size_t)(x))
-#define TSI_SIZE_AS_SIZE(x) (x)
-#else
-#define TSI_INT_AS_SIZE(x) (x)
-#define TSI_SIZE_AS_SIZE(x) ((int)(x))
-#endif
-
-#endif /* GRPC_CORE_TSI_SSL_TYPES_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_TSI_SSL_TYPES_H
+#define GRPC_CORE_TSI_SSL_TYPES_H
+
+/* A collection of macros to cast between various integer types that are
+ * used differently between BoringSSL and OpenSSL:
+ * TSI_INT_AS_SIZE(x): convert 'int x' to a length parameter for an OpenSSL
+ * function
+ * TSI_SIZE_AS_SIZE(x): convert 'size_t x' to a length parameter for an OpenSSL
+ * function
+ */
+
+#include <grpc/support/port_platform.h>
+
+#include <openssl/ssl.h>
+
+#ifdef OPENSSL_IS_BORINGSSL
+#define TSI_INT_AS_SIZE(x) ((size_t)(x))
+#define TSI_SIZE_AS_SIZE(x) (x)
+#else
+#define TSI_INT_AS_SIZE(x) (x)
+#define TSI_SIZE_AS_SIZE(x) ((int)(x))
+#endif
+
+#endif /* GRPC_CORE_TSI_SSL_TYPES_H */
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/BUILD b/contrib/libs/grpc/src/core/tsi/test_creds/BUILD
index 94bb5d4bdef..e747909fc70 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/BUILD
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/BUILD
@@ -1,20 +1,20 @@
-# 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.
-
-licenses(["notice"]) # Apache v2
-
-exports_files([
+# 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.
+
+licenses(["notice"]) # Apache v2
+
+exports_files([
"ca.pem",
"server1.key",
"server1.pem",
@@ -28,4 +28,4 @@ exports_files([
"badclient.pem",
"multi-domain.key",
"multi-domain.pem",
-])
+])
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/README b/contrib/libs/grpc/src/core/tsi/test_creds/README
index ee9b60ec590..6db803faf71 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/README
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/README
@@ -1,64 +1,64 @@
-The test credentials (CONFIRMEDTESTKEY) have been generated with the following
-commands:
-
-Bad credentials (badclient.* / badserver.*):
-============================================
-
-These are self-signed certificates:
-
+The test credentials (CONFIRMEDTESTKEY) have been generated with the following
+commands:
+
+Bad credentials (badclient.* / badserver.*):
+============================================
+
+These are self-signed certificates:
+
$ openssl req -x509 -newkey rsa:2048 -keyout badserver.key -out badserver.pem \
- -days 3650 -nodes
-
-When prompted for certificate information, everything is default except the
-common name which is set to badserver.test.google.com.
-
-
-Valid test credentials:
-=======================
-
-The ca is self-signed:
-----------------------
-
+ -days 3650 -nodes
+
+When prompted for certificate information, everything is default except the
+common name which is set to badserver.test.google.com.
+
+
+Valid test credentials:
+=======================
+
+The ca is self-signed:
+----------------------
+
$ openssl req -x509 -new -newkey rsa:2048 -nodes -keyout ca.key -out ca.pem \
-config ca-openssl.cnf -days 3650 -extensions v3_req
-When prompted for certificate information, everything is default.
-
-client is issued by CA:
------------------------
-
+When prompted for certificate information, everything is default.
+
+client is issued by CA:
+-----------------------
+
$ openssl genrsa -out client.key.rsa 2048
-$ openssl pkcs8 -topk8 -in client.key.rsa -out client.key -nocrypt
-$ openssl req -new -key client.key -out client.csr
-
-When prompted for certificate information, everything is default except the
-common name which is set to testclient.
-
+$ openssl pkcs8 -topk8 -in client.key.rsa -out client.key -nocrypt
+$ openssl req -new -key client.key -out client.csr
+
+When prompted for certificate information, everything is default except the
+common name which is set to testclient.
+
$ openssl x509 -req -CA ca.pem -CAkey ca.key -CAcreateserial -in client.csr \
-out client.pem -days 3650
-
-server0 is issued by CA:
-------------------------
-
+
+server0 is issued by CA:
+------------------------
+
$ openssl genrsa -out server0.key.rsa 2048
-$ openssl pkcs8 -topk8 -in server0.key.rsa -out server0.key -nocrypt
-$ openssl req -new -key server0.key -out server0.csr
-
-When prompted for certificate information, everything is default except the
-common name which is set to *.test.google.com.au.
-
+$ openssl pkcs8 -topk8 -in server0.key.rsa -out server0.key -nocrypt
+$ openssl req -new -key server0.key -out server0.csr
+
+When prompted for certificate information, everything is default except the
+common name which is set to *.test.google.com.au.
+
$ openssl x509 -req -CA ca.pem -CAkey ca.key -CAcreateserial -in server0.csr \
-out server0.pem -days 3650
-
-server1 is issued by CA with a special config for subject alternative names:
-----------------------------------------------------------------------------
-
+
+server1 is issued by CA with a special config for subject alternative names:
+----------------------------------------------------------------------------
+
$ openssl genrsa -out server1.key.rsa 2048
-$ openssl pkcs8 -topk8 -in server1.key.rsa -out server1.key -nocrypt
-$ openssl req -new -key server1.key -out server1.csr -config server1-openssl.cnf
-
-When prompted for certificate information, everything is default except the
-common name which is set to *.test.google.com.
-
+$ openssl pkcs8 -topk8 -in server1.key.rsa -out server1.key -nocrypt
+$ openssl req -new -key server1.key -out server1.csr -config server1-openssl.cnf
+
+When prompted for certificate information, everything is default except the
+common name which is set to *.test.google.com.
+
$ openssl x509 -req -CA ca.pem -CAkey ca.key -CAcreateserial -in server1.csr \
-out server1.pem -extensions req_ext -extfile server1-openssl.cnf -days 3650
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/badclient.key b/contrib/libs/grpc/src/core/tsi/test_creds/badclient.key
index 6cd102b8308..457ff8e141e 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/badclient.key
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/badclient.key
@@ -1,4 +1,4 @@
------BEGIN PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDvdzKDTYvRgjBO
UOrzDwkAZGwNFHHlMYyMGI5tItj3tCzXkbpM0uz3ZjHVahu+eYc+KvYApM64F2dB
b16hs713FCk8mihYABjnSndrQsl/U2v8YFT7DipfLReqqaOGu2o9HdvWfiUlaiC/
@@ -25,4 +25,4 @@ Jg1ej1bUgXcDbTnaEhzbdLiTFsg5NzMtKwOjdDIpZQKBgEIHeJIqiGjYgf7mUlX2
vNWgFNlzApkFSCQ8TkzkDOjtCdSHfdRDJ6+q8cS2TSQ7QPoAlI1woS0G48TNbVSo
wD0jNVRTdpA6R5FPsg09ohB/caSn0zlGVha2GS08ceYrn7nn4PSZ/UIYTm3pjUlV
H5tvHv0gG2C5vy3tIYQtSQCk
------END PRIVATE KEY-----
+-----END PRIVATE KEY-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/badclient.pem b/contrib/libs/grpc/src/core/tsi/test_creds/badclient.pem
index 345da3932d9..ccbb38ba5bf 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/badclient.pem
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/badclient.pem
@@ -1,4 +1,4 @@
------BEGIN CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
MIIDszCCApugAwIBAgIUONWbkUn1obHCw9L7lMNEE5REvb8wDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEiMCAGA1UEAwwZYmFkY2xpZW50LnRl
@@ -19,4 +19,4 @@ nCGrK8wRKGb/mqW9d5pP72Et1Q6OW6DAKqGfjDWh2MzSPHBxcCLeyigO1wqd4W1T
nvvql6l4L+B5IT/c+/EHO3PwbI9v6MGTtLjsZgkRKItaPh+YeJdmBYhRD1BvWb6s
VwEb7aQ1oSF+esUvMmjGVuHXuQvWJahnjYdYT2DikyqR+AwaKzre4GJMHsX3/Cf8
qdxyI+B1jUwNr7sLA2EYDjnUR0jEHcrOBSpIQyRMGWduj0P16yb9
------END CERTIFICATE-----
+-----END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/badserver.key b/contrib/libs/grpc/src/core/tsi/test_creds/badserver.key
index 1f5a31666cb..b8f95429c1c 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/badserver.key
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/badserver.key
@@ -1,4 +1,4 @@
------BEGIN PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDRY2Z886nT6KF4
tjgJTX0l1M4j8bQp+jKfXz+hwUZbn/PnCXJlu/5denpyu4XrLxr6Ix4Il97SrKfQ
iGaSZQ8hcq6WQdEDfuo/U7R/dk6lYG7q+yg7+xHm02DzVdPLp09kLhU+fWH3Wek0
@@ -25,4 +25,4 @@ QA0IWGVOzMwHpZKWFViI4BDBDxQaO0xMoS/Hd0w0XQKBgF5uZXXrNLmCeU6oco1R
gjGJE4gRwaSVcVJbs/VLbBmHT1VhBGsiluBuTpbmzDfyHWHJprnthlSTgqHXSax1
6GvHZ2NHBqmD2uxEGuwBffzhwWVxHpgSrRgvnnaeIph2Iv92/ATN5LCc5vF+SNGx
2kKWYTDSRu9q1xHpXcax+nmJ
------END PRIVATE KEY-----
+-----END PRIVATE KEY-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/badserver.pem b/contrib/libs/grpc/src/core/tsi/test_creds/badserver.pem
index 217dd640eba..6b9bec60945 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/badserver.pem
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/badserver.pem
@@ -1,4 +1,4 @@
------BEGIN CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
MIIDszCCApugAwIBAgIULEum14ranwlUZjuZchSWaHtj8Z4wDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEiMCAGA1UEAwwZYmFkc2VydmVyLnRl
@@ -19,4 +19,4 @@ hTaiQ4AfXWjO7H8o2B/rneZtA21NDCwvFxTXeJzAVnBkpIePR//KmuHjtCMjsrtP
ovckcTRGmhWJJ9sRx4HCsJXygBvnCIIIYC585aU4+nE53UDNT2T+Bd4b1vPmwf9R
9XgbyN6AhQ+0F11zlnftwsJ23nbnXqX/fpG/YZuhnPwaUILRodc6HZQtf/8xpRcA
0dKMdnL2YtBjuL5QFJMLT0mdsmnXj3h/oK8894nYBZYSmlb3bzZK
------END CERTIFICATE-----
+-----END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/ca-openssl.cnf b/contrib/libs/grpc/src/core/tsi/test_creds/ca-openssl.cnf
index e97b945e4bb..04f9618f760 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/ca-openssl.cnf
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/ca-openssl.cnf
@@ -1,17 +1,17 @@
-[req]
-distinguished_name = req_distinguished_name
-req_extensions = v3_req
-
-[req_distinguished_name]
-countryName = Country Name (2 letter code)
-countryName_default = AU
-stateOrProvinceName = State or Province Name (full name)
-stateOrProvinceName_default = Some-State
-organizationName = Organization Name (eg, company)
-organizationName_default = Internet Widgits Pty Ltd
-commonName = Common Name (eg, YOUR name)
-commonName_default = testca
-
-[v3_req]
-basicConstraints = CA:true
-keyUsage = critical, keyCertSign
+[req]
+distinguished_name = req_distinguished_name
+req_extensions = v3_req
+
+[req_distinguished_name]
+countryName = Country Name (2 letter code)
+countryName_default = AU
+stateOrProvinceName = State or Province Name (full name)
+stateOrProvinceName_default = Some-State
+organizationName = Organization Name (eg, company)
+organizationName_default = Internet Widgits Pty Ltd
+commonName = Common Name (eg, YOUR name)
+commonName_default = testca
+
+[v3_req]
+basicConstraints = CA:true
+keyUsage = critical, keyCertSign
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/ca.key b/contrib/libs/grpc/src/core/tsi/test_creds/ca.key
index 03be0bfa6ee..bae980931d0 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/ca.key
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/ca.key
@@ -1,4 +1,4 @@
------BEGIN PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwYvShd+UXQvOg
z4GH6pRT3KGrPDbDw45fma7+I0LJQ4GupoeLuYYfHvcYPTV2I3MLO+VxCp00gfo1
BIvsNOkGNxrrqNhP27ve9l7YwOuvWdVu4u9+73znRx3GJQ4ie/nF/z6xMcbQL5r5
@@ -25,4 +25,4 @@ fDAmtCIGz/A2uQ5YIRQuMzr6VZJAGUgLndQtlfd7AoGBAMq1imggFKd1rt49XCnO
t97lpWOT+TlWYblHr01tOw+esawG5MFucqVI6tGpBSccTRQw6orWf4GK3KmkgQ6J
UgHKjwYsA0sf4U5vppkdkbAbM/WwUPOTQpGFRERyJqMqFGIc4wMtZOJBxXwf+9iD
l8tvan8w/6HugqnI7qqkTgLq
------END PRIVATE KEY-----
+-----END PRIVATE KEY-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/ca.pem b/contrib/libs/grpc/src/core/tsi/test_creds/ca.pem
index 49d39cd8ed5..5f626380138 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/ca.pem
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/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/core/tsi/test_creds/client.key b/contrib/libs/grpc/src/core/tsi/test_creds/client.key
index 349b40033dd..e960acf836e 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/client.key
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/client.key
@@ -1,4 +1,4 @@
------BEGIN PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyqYRp+DXVp72N
FbQH8hdhTZLycZXOlJhmMsrJmrjn2p7pI/8mTZ/0FC+SGWBGZV+ELiHrmCX5zfaI
Lr9Iuw7Ghr3Vzoefi8r62rLupVPNi/qdqyjWk2dECHC9Z3+Ag3KzKTyerXWjKcvy
@@ -25,4 +25,4 @@ Jlz1xz0b6DkmKWTiV3r9OPHKJ8P7IeJxAZWmZzCdDuwkv0i+WW+z0zsIe3JjEavN
F/AQG7ukgipB6N6AkB9kDbgCs1FLgd199MQrEncug5hfpq8QerbyMatmA+GXoGMb
7vztKEH85yzp4n02FNL6H7xL4VVILvyZHdolmiORJ4qT2hZnl8pEQ2TYuF4RlHUd
nSwXX+2o0J/nF85fm4AwWKAc
------END PRIVATE KEY-----
+-----END PRIVATE KEY-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/client.pem b/contrib/libs/grpc/src/core/tsi/test_creds/client.pem
index 8815875f327..38316448725 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/client.pem
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/client.pem
@@ -1,4 +1,4 @@
------BEGIN CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
MIIDNzCCAh8CFGyX00RCepOv/qCJ1oVdTtY92U83MA0GCSqGSIb3DQEBCwUAMFYx
CzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRl
cm5ldCBXaWRnaXRzIFB0eSBMdGQxDzANBgNVBAMMBnRlc3RjYTAeFw0yMDAzMTgw
@@ -17,4 +17,4 @@ gijiDssKAfxTAmUM93N6+Q8yJK5immxlbeYfijoBvmkzyB/B+qNRPsx0n7aFGnfv
oWfkW296iPhWLiwknpC3xB6oK3vRbK4Zj1OaGb0grK7VN8EyhBix2xVF61i4dzCK
kMIpl7CUpw1Mb2z8q3F2bHBS7iF7g1Ccn5VGcO+aJ+6PWydaeqJ6VEBF0Nwv9woe
mL5AluNRLaqjZvE=
------END CERTIFICATE-----
+-----END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/server0.key b/contrib/libs/grpc/src/core/tsi/test_creds/server0.key
index 261097a87e3..11845c0a694 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/server0.key
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/server0.key
@@ -1,4 +1,4 @@
------BEGIN PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCei9aKutDNg2mr
COICW4hT6+LVJfI5J6DZ3yqb6MBzbc//VeUj1OCX/vt5vvPm1Qb5XNk1MOIFPEW6
t2/0Mhj2VbQfjDe/PhZRhwu4PBtuoJBDeBsKkdnxD0I+4G0XRbeTtUsGMGBgWSAd
@@ -25,4 +25,4 @@ gFuLUxtU6kkIG3MqsVI8icjs2HVUmRAktZ7PXwECgYA9V/zZe2DpP36gp63wRk6S
FI7bDbLPQCKah23mwp3WeP5T+/HmFFRrl0OCaDLwudTolqgPa47CV7JYa9LmJAPj
QBxcnL4CxjlaaS3V9kxVWOXabMEtwSUurELJwFKTEC/AFN9dR/nv4AzXInZznotG
7qDX8EhfjbFVJw4riAmlEw==
------END PRIVATE KEY-----
+-----END PRIVATE KEY-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/server0.pem b/contrib/libs/grpc/src/core/tsi/test_creds/server0.pem
index ab20787fa5b..2da85815fcb 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/server0.pem
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/server0.pem
@@ -1,4 +1,4 @@
------BEGIN CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
MIIDQTCCAikCFGyX00RCepOv/qCJ1oVdTtY92U84MA0GCSqGSIb3DQEBCwUAMFYx
CzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRl
cm5ldCBXaWRnaXRzIFB0eSBMdGQxDzANBgNVBAMMBnRlc3RjYTAeFw0yMDAzMTgw
@@ -17,4 +17,4 @@ If1egkjBCUZKVSWqYRKB6AMqjpp7/dF06j6zAaAH54jaLv9VmiBtsFyd017AsC9W
+OG2ke2dNtXySfVX4VusCcji86qb5sr6hNIQWMXk6dZoLDsZvwvVi7KnrqQOza8J
klcJXV8Hsnq/faHr/ZmsIA65N0+H8KuYfbO+s5nKPG9th6ZZAu4aY2VDei++TH+H
EAQhivPNUC1DgCmx0P7vKLhgka7S
------END CERTIFICATE-----
+-----END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/server1-openssl.cnf b/contrib/libs/grpc/src/core/tsi/test_creds/server1-openssl.cnf
index 8a021082891..3f7bb8e2bf7 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/server1-openssl.cnf
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/server1-openssl.cnf
@@ -1,26 +1,26 @@
-[req]
-distinguished_name = req_distinguished_name
-req_extensions = v3_req
-
-[req_distinguished_name]
-countryName = Country Name (2 letter code)
-countryName_default = US
-stateOrProvinceName = State or Province Name (full name)
-stateOrProvinceName_default = Illinois
-localityName = Locality Name (eg, city)
-localityName_default = Chicago
-organizationName = Organization Name (eg, company)
-organizationName_default = Example, Co.
-commonName = Common Name (eg, YOUR name)
-commonName_max = 64
-
-[v3_req]
-basicConstraints = CA:FALSE
-keyUsage = nonRepudiation, digitalSignature, keyEncipherment
-subjectAltName = @alt_names
-
-[alt_names]
-DNS.1 = *.test.google.fr
-DNS.2 = waterzooi.test.google.be
-DNS.3 = *.test.youtube.com
-IP.1 = "192.168.1.3"
+[req]
+distinguished_name = req_distinguished_name
+req_extensions = v3_req
+
+[req_distinguished_name]
+countryName = Country Name (2 letter code)
+countryName_default = US
+stateOrProvinceName = State or Province Name (full name)
+stateOrProvinceName_default = Illinois
+localityName = Locality Name (eg, city)
+localityName_default = Chicago
+organizationName = Organization Name (eg, company)
+organizationName_default = Example, Co.
+commonName = Common Name (eg, YOUR name)
+commonName_max = 64
+
+[v3_req]
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+subjectAltName = @alt_names
+
+[alt_names]
+DNS.1 = *.test.google.fr
+DNS.2 = waterzooi.test.google.be
+DNS.3 = *.test.youtube.com
+IP.1 = "192.168.1.3"
diff --git a/contrib/libs/grpc/src/core/tsi/test_creds/server1.key b/contrib/libs/grpc/src/core/tsi/test_creds/server1.key
index 086462992cf..25cdade2fb3 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/server1.key
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/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/core/tsi/test_creds/server1.pem b/contrib/libs/grpc/src/core/tsi/test_creds/server1.pem
index 88244f856c6..d37efbaafae 100644
--- a/contrib/libs/grpc/src/core/tsi/test_creds/server1.pem
+++ b/contrib/libs/grpc/src/core/tsi/test_creds/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/core/tsi/transport_security.cc b/contrib/libs/grpc/src/core/tsi/transport_security.cc
index 035e7cc5454..c3987ffa9a5 100644
--- a/contrib/libs/grpc/src/core/tsi/transport_security.cc
+++ b/contrib/libs/grpc/src/core/tsi/transport_security.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 <grpc/support/port_platform.h>
-
-#include "src/core/tsi/transport_security.h"
-
-#include <grpc/support/alloc.h>
-#include <grpc/support/string_util.h>
-
-#include <stdlib.h>
-#include <string.h>
-
-/* --- Tracing. --- */
-
-grpc_core::TraceFlag tsi_tracing_enabled(false, "tsi");
-
-/* --- tsi_result common implementation. --- */
-
-const char* tsi_result_to_string(tsi_result result) {
- switch (result) {
- case TSI_OK:
- return "TSI_OK";
- case TSI_UNKNOWN_ERROR:
- return "TSI_UNKNOWN_ERROR";
- case TSI_INVALID_ARGUMENT:
- return "TSI_INVALID_ARGUMENT";
- case TSI_PERMISSION_DENIED:
- return "TSI_PERMISSION_DENIED";
- case TSI_INCOMPLETE_DATA:
- return "TSI_INCOMPLETE_DATA";
- case TSI_FAILED_PRECONDITION:
- return "TSI_FAILED_PRECONDITION";
- case TSI_UNIMPLEMENTED:
- return "TSI_UNIMPLEMENTED";
- case TSI_INTERNAL_ERROR:
- return "TSI_INTERNAL_ERROR";
- case TSI_DATA_CORRUPTED:
- return "TSI_DATA_CORRUPTED";
- case TSI_NOT_FOUND:
- return "TSI_NOT_FOUND";
- case TSI_PROTOCOL_FAILURE:
- return "TSI_PROTOCOL_FAILURE";
- case TSI_HANDSHAKE_IN_PROGRESS:
- return "TSI_HANDSHAKE_IN_PROGRESS";
- case TSI_OUT_OF_RESOURCES:
- return "TSI_OUT_OF_RESOURCES";
- case TSI_ASYNC:
- return "TSI_ASYNC";
- default:
- return "UNKNOWN";
- }
-}
-
+/*
+ *
+ * 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/tsi/transport_security.h"
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+
+#include <stdlib.h>
+#include <string.h>
+
+/* --- Tracing. --- */
+
+grpc_core::TraceFlag tsi_tracing_enabled(false, "tsi");
+
+/* --- tsi_result common implementation. --- */
+
+const char* tsi_result_to_string(tsi_result result) {
+ switch (result) {
+ case TSI_OK:
+ return "TSI_OK";
+ case TSI_UNKNOWN_ERROR:
+ return "TSI_UNKNOWN_ERROR";
+ case TSI_INVALID_ARGUMENT:
+ return "TSI_INVALID_ARGUMENT";
+ case TSI_PERMISSION_DENIED:
+ return "TSI_PERMISSION_DENIED";
+ case TSI_INCOMPLETE_DATA:
+ return "TSI_INCOMPLETE_DATA";
+ case TSI_FAILED_PRECONDITION:
+ return "TSI_FAILED_PRECONDITION";
+ case TSI_UNIMPLEMENTED:
+ return "TSI_UNIMPLEMENTED";
+ case TSI_INTERNAL_ERROR:
+ return "TSI_INTERNAL_ERROR";
+ case TSI_DATA_CORRUPTED:
+ return "TSI_DATA_CORRUPTED";
+ case TSI_NOT_FOUND:
+ return "TSI_NOT_FOUND";
+ case TSI_PROTOCOL_FAILURE:
+ return "TSI_PROTOCOL_FAILURE";
+ case TSI_HANDSHAKE_IN_PROGRESS:
+ return "TSI_HANDSHAKE_IN_PROGRESS";
+ case TSI_OUT_OF_RESOURCES:
+ return "TSI_OUT_OF_RESOURCES";
+ case TSI_ASYNC:
+ return "TSI_ASYNC";
+ default:
+ return "UNKNOWN";
+ }
+}
+
const char* tsi_security_level_to_string(tsi_security_level security_level) {
switch (security_level) {
case TSI_SECURITY_NONE:
@@ -80,150 +80,150 @@ const char* tsi_security_level_to_string(tsi_security_level security_level) {
}
}
-/* --- tsi_frame_protector common implementation. ---
-
- Calls specific implementation after state/input validation. */
-
-tsi_result tsi_frame_protector_protect(tsi_frame_protector* self,
- const unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size) {
- if (self == nullptr || self->vtable == nullptr ||
- unprotected_bytes == nullptr || unprotected_bytes_size == nullptr ||
- protected_output_frames == nullptr ||
- protected_output_frames_size == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->protect == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->protect(self, unprotected_bytes, unprotected_bytes_size,
- protected_output_frames,
- protected_output_frames_size);
-}
-
-tsi_result tsi_frame_protector_protect_flush(
- tsi_frame_protector* self, unsigned char* protected_output_frames,
- size_t* protected_output_frames_size, size_t* still_pending_size) {
- if (self == nullptr || self->vtable == nullptr ||
- protected_output_frames == nullptr ||
- protected_output_frames_size == nullptr ||
- still_pending_size == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->protect_flush == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->protect_flush(self, protected_output_frames,
- protected_output_frames_size,
- still_pending_size);
-}
-
-tsi_result tsi_frame_protector_unprotect(
- tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
- size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size) {
- if (self == nullptr || self->vtable == nullptr ||
- protected_frames_bytes == nullptr ||
- protected_frames_bytes_size == nullptr || unprotected_bytes == nullptr ||
- unprotected_bytes_size == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->unprotect == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->unprotect(self, protected_frames_bytes,
- protected_frames_bytes_size, unprotected_bytes,
- unprotected_bytes_size);
-}
-
-void tsi_frame_protector_destroy(tsi_frame_protector* self) {
- if (self == nullptr) return;
- self->vtable->destroy(self);
-}
-
-/* --- tsi_handshaker common implementation. ---
-
- Calls specific implementation after state/input validation. */
-
-tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
- unsigned char* bytes,
- size_t* bytes_size) {
- if (self == nullptr || self->vtable == nullptr || bytes == nullptr ||
- bytes_size == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
+/* --- tsi_frame_protector common implementation. ---
+
+ Calls specific implementation after state/input validation. */
+
+tsi_result tsi_frame_protector_protect(tsi_frame_protector* self,
+ const unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size) {
+ if (self == nullptr || self->vtable == nullptr ||
+ unprotected_bytes == nullptr || unprotected_bytes_size == nullptr ||
+ protected_output_frames == nullptr ||
+ protected_output_frames_size == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->protect == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->protect(self, unprotected_bytes, unprotected_bytes_size,
+ protected_output_frames,
+ protected_output_frames_size);
+}
+
+tsi_result tsi_frame_protector_protect_flush(
+ tsi_frame_protector* self, unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size, size_t* still_pending_size) {
+ if (self == nullptr || self->vtable == nullptr ||
+ protected_output_frames == nullptr ||
+ protected_output_frames_size == nullptr ||
+ still_pending_size == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->protect_flush == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->protect_flush(self, protected_output_frames,
+ protected_output_frames_size,
+ still_pending_size);
+}
+
+tsi_result tsi_frame_protector_unprotect(
+ tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
+ size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size) {
+ if (self == nullptr || self->vtable == nullptr ||
+ protected_frames_bytes == nullptr ||
+ protected_frames_bytes_size == nullptr || unprotected_bytes == nullptr ||
+ unprotected_bytes_size == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->unprotect == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->unprotect(self, protected_frames_bytes,
+ protected_frames_bytes_size, unprotected_bytes,
+ unprotected_bytes_size);
+}
+
+void tsi_frame_protector_destroy(tsi_frame_protector* self) {
+ if (self == nullptr) return;
+ self->vtable->destroy(self);
+}
+
+/* --- tsi_handshaker common implementation. ---
+
+ Calls specific implementation after state/input validation. */
+
+tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
+ unsigned char* bytes,
+ size_t* bytes_size) {
+ if (self == nullptr || self->vtable == nullptr || bytes == nullptr ||
+ bytes_size == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN;
- if (self->vtable->get_bytes_to_send_to_peer == nullptr)
- return TSI_UNIMPLEMENTED;
- return self->vtable->get_bytes_to_send_to_peer(self, bytes, bytes_size);
-}
-
-tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self,
- const unsigned char* bytes,
- size_t* bytes_size) {
- if (self == nullptr || self->vtable == nullptr || bytes == nullptr ||
- bytes_size == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
+ if (self->vtable->get_bytes_to_send_to_peer == nullptr)
+ return TSI_UNIMPLEMENTED;
+ return self->vtable->get_bytes_to_send_to_peer(self, bytes, bytes_size);
+}
+
+tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self,
+ const unsigned char* bytes,
+ size_t* bytes_size) {
+ if (self == nullptr || self->vtable == nullptr || bytes == nullptr ||
+ bytes_size == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN;
- if (self->vtable->process_bytes_from_peer == nullptr)
- return TSI_UNIMPLEMENTED;
- return self->vtable->process_bytes_from_peer(self, bytes, bytes_size);
-}
-
-tsi_result tsi_handshaker_get_result(tsi_handshaker* self) {
- if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT;
- if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
+ if (self->vtable->process_bytes_from_peer == nullptr)
+ return TSI_UNIMPLEMENTED;
+ return self->vtable->process_bytes_from_peer(self, bytes, bytes_size);
+}
+
+tsi_result tsi_handshaker_get_result(tsi_handshaker* self) {
+ if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT;
+ if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN;
- if (self->vtable->get_result == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->get_result(self);
-}
-
-tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer) {
- if (self == nullptr || self->vtable == nullptr || peer == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- memset(peer, 0, sizeof(tsi_peer));
- if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
+ if (self->vtable->get_result == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->get_result(self);
+}
+
+tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer) {
+ if (self == nullptr || self->vtable == nullptr || peer == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ memset(peer, 0, sizeof(tsi_peer));
+ if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN;
- if (tsi_handshaker_get_result(self) != TSI_OK) {
- return TSI_FAILED_PRECONDITION;
- }
- if (self->vtable->extract_peer == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->extract_peer(self, peer);
-}
-
-tsi_result tsi_handshaker_create_frame_protector(
- tsi_handshaker* self, size_t* max_protected_frame_size,
- tsi_frame_protector** protector) {
- tsi_result result;
- if (self == nullptr || self->vtable == nullptr || protector == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
+ if (tsi_handshaker_get_result(self) != TSI_OK) {
+ return TSI_FAILED_PRECONDITION;
+ }
+ if (self->vtable->extract_peer == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->extract_peer(self, peer);
+}
+
+tsi_result tsi_handshaker_create_frame_protector(
+ tsi_handshaker* self, size_t* max_protected_frame_size,
+ tsi_frame_protector** protector) {
+ tsi_result result;
+ if (self == nullptr || self->vtable == nullptr || protector == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN;
- if (tsi_handshaker_get_result(self) != TSI_OK) return TSI_FAILED_PRECONDITION;
- if (self->vtable->create_frame_protector == nullptr) return TSI_UNIMPLEMENTED;
- result = self->vtable->create_frame_protector(self, max_protected_frame_size,
- protector);
- if (result == TSI_OK) {
- self->frame_protector_created = true;
- }
- return result;
-}
-
-tsi_result tsi_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) {
- if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT;
- if (self->handshaker_result_created) return TSI_FAILED_PRECONDITION;
+ if (tsi_handshaker_get_result(self) != TSI_OK) return TSI_FAILED_PRECONDITION;
+ if (self->vtable->create_frame_protector == nullptr) return TSI_UNIMPLEMENTED;
+ result = self->vtable->create_frame_protector(self, max_protected_frame_size,
+ protector);
+ if (result == TSI_OK) {
+ self->frame_protector_created = true;
+ }
+ return result;
+}
+
+tsi_result tsi_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) {
+ if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT;
+ if (self->handshaker_result_created) return TSI_FAILED_PRECONDITION;
if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN;
- if (self->vtable->next == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->next(self, received_bytes, received_bytes_size,
- bytes_to_send, bytes_to_send_size,
- handshaker_result, cb, user_data);
-}
-
+ if (self->vtable->next == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->next(self, received_bytes, received_bytes_size,
+ bytes_to_send, bytes_to_send_size,
+ handshaker_result, cb, user_data);
+}
+
void tsi_handshaker_shutdown(tsi_handshaker* self) {
if (self == nullptr || self->vtable == nullptr) return;
if (self->vtable->shutdown != nullptr) {
@@ -232,125 +232,125 @@ void tsi_handshaker_shutdown(tsi_handshaker* self) {
self->handshake_shutdown = true;
}
-void tsi_handshaker_destroy(tsi_handshaker* self) {
- if (self == nullptr) return;
- self->vtable->destroy(self);
-}
-
-/* --- tsi_handshaker_result implementation. --- */
-
-tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result* self,
- tsi_peer* peer) {
- if (self == nullptr || self->vtable == nullptr || peer == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- memset(peer, 0, sizeof(tsi_peer));
- if (self->vtable->extract_peer == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->extract_peer(self, peer);
-}
-
-tsi_result tsi_handshaker_result_create_frame_protector(
- const tsi_handshaker_result* self, size_t* max_protected_frame_size,
- tsi_frame_protector** protector) {
- if (self == nullptr || self->vtable == nullptr || protector == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->create_frame_protector == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->create_frame_protector(self, max_protected_frame_size,
- protector);
-}
-
-tsi_result tsi_handshaker_result_get_unused_bytes(
- const tsi_handshaker_result* self, const unsigned char** bytes,
- size_t* bytes_size) {
- if (self == nullptr || self->vtable == nullptr || bytes == nullptr ||
- bytes_size == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->get_unused_bytes == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->get_unused_bytes(self, bytes, bytes_size);
-}
-
-void tsi_handshaker_result_destroy(tsi_handshaker_result* self) {
- if (self == nullptr) return;
- self->vtable->destroy(self);
-}
-
-/* --- tsi_peer implementation. --- */
-
-tsi_peer_property tsi_init_peer_property(void) {
- tsi_peer_property property;
- memset(&property, 0, sizeof(tsi_peer_property));
- return property;
-}
-
-static void tsi_peer_destroy_list_property(tsi_peer_property* children,
- size_t child_count) {
- size_t i;
- for (i = 0; i < child_count; i++) {
- tsi_peer_property_destruct(&children[i]);
- }
- gpr_free(children);
-}
-
-void tsi_peer_property_destruct(tsi_peer_property* property) {
- if (property->name != nullptr) {
- gpr_free(property->name);
- }
- if (property->value.data != nullptr) {
- gpr_free(property->value.data);
- }
- *property = tsi_init_peer_property(); /* Reset everything to 0. */
-}
-
-void tsi_peer_destruct(tsi_peer* self) {
- if (self == nullptr) return;
- if (self->properties != nullptr) {
- tsi_peer_destroy_list_property(self->properties, self->property_count);
- self->properties = nullptr;
- }
- self->property_count = 0;
-}
-
-tsi_result tsi_construct_allocated_string_peer_property(
- const char* name, size_t value_length, tsi_peer_property* property) {
- *property = tsi_init_peer_property();
- if (name != nullptr) property->name = gpr_strdup(name);
- if (value_length > 0) {
- property->value.data = static_cast<char*>(gpr_zalloc(value_length));
- property->value.length = value_length;
- }
- return TSI_OK;
-}
-
-tsi_result tsi_construct_string_peer_property_from_cstring(
- const char* name, const char* value, tsi_peer_property* property) {
- return tsi_construct_string_peer_property(name, value, strlen(value),
- property);
-}
-
-tsi_result tsi_construct_string_peer_property(const char* name,
- const char* value,
- size_t value_length,
- tsi_peer_property* property) {
- tsi_result result = tsi_construct_allocated_string_peer_property(
- name, value_length, property);
- if (result != TSI_OK) return result;
- if (value_length > 0) {
- memcpy(property->value.data, value, value_length);
- }
- return TSI_OK;
-}
-
-tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer) {
- memset(peer, 0, sizeof(tsi_peer));
- if (property_count > 0) {
- peer->properties = static_cast<tsi_peer_property*>(
- gpr_zalloc(property_count * sizeof(tsi_peer_property)));
- peer->property_count = property_count;
- }
- return TSI_OK;
-}
+void tsi_handshaker_destroy(tsi_handshaker* self) {
+ if (self == nullptr) return;
+ self->vtable->destroy(self);
+}
+
+/* --- tsi_handshaker_result implementation. --- */
+
+tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result* self,
+ tsi_peer* peer) {
+ if (self == nullptr || self->vtable == nullptr || peer == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ memset(peer, 0, sizeof(tsi_peer));
+ if (self->vtable->extract_peer == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->extract_peer(self, peer);
+}
+
+tsi_result tsi_handshaker_result_create_frame_protector(
+ const tsi_handshaker_result* self, size_t* max_protected_frame_size,
+ tsi_frame_protector** protector) {
+ if (self == nullptr || self->vtable == nullptr || protector == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->create_frame_protector == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->create_frame_protector(self, max_protected_frame_size,
+ protector);
+}
+
+tsi_result tsi_handshaker_result_get_unused_bytes(
+ const tsi_handshaker_result* self, const unsigned char** bytes,
+ size_t* bytes_size) {
+ if (self == nullptr || self->vtable == nullptr || bytes == nullptr ||
+ bytes_size == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->get_unused_bytes == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->get_unused_bytes(self, bytes, bytes_size);
+}
+
+void tsi_handshaker_result_destroy(tsi_handshaker_result* self) {
+ if (self == nullptr) return;
+ self->vtable->destroy(self);
+}
+
+/* --- tsi_peer implementation. --- */
+
+tsi_peer_property tsi_init_peer_property(void) {
+ tsi_peer_property property;
+ memset(&property, 0, sizeof(tsi_peer_property));
+ return property;
+}
+
+static void tsi_peer_destroy_list_property(tsi_peer_property* children,
+ size_t child_count) {
+ size_t i;
+ for (i = 0; i < child_count; i++) {
+ tsi_peer_property_destruct(&children[i]);
+ }
+ gpr_free(children);
+}
+
+void tsi_peer_property_destruct(tsi_peer_property* property) {
+ if (property->name != nullptr) {
+ gpr_free(property->name);
+ }
+ if (property->value.data != nullptr) {
+ gpr_free(property->value.data);
+ }
+ *property = tsi_init_peer_property(); /* Reset everything to 0. */
+}
+
+void tsi_peer_destruct(tsi_peer* self) {
+ if (self == nullptr) return;
+ if (self->properties != nullptr) {
+ tsi_peer_destroy_list_property(self->properties, self->property_count);
+ self->properties = nullptr;
+ }
+ self->property_count = 0;
+}
+
+tsi_result tsi_construct_allocated_string_peer_property(
+ const char* name, size_t value_length, tsi_peer_property* property) {
+ *property = tsi_init_peer_property();
+ if (name != nullptr) property->name = gpr_strdup(name);
+ if (value_length > 0) {
+ property->value.data = static_cast<char*>(gpr_zalloc(value_length));
+ property->value.length = value_length;
+ }
+ return TSI_OK;
+}
+
+tsi_result tsi_construct_string_peer_property_from_cstring(
+ const char* name, const char* value, tsi_peer_property* property) {
+ return tsi_construct_string_peer_property(name, value, strlen(value),
+ property);
+}
+
+tsi_result tsi_construct_string_peer_property(const char* name,
+ const char* value,
+ size_t value_length,
+ tsi_peer_property* property) {
+ tsi_result result = tsi_construct_allocated_string_peer_property(
+ name, value_length, property);
+ if (result != TSI_OK) return result;
+ if (value_length > 0) {
+ memcpy(property->value.data, value, value_length);
+ }
+ return TSI_OK;
+}
+
+tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer) {
+ memset(peer, 0, sizeof(tsi_peer));
+ if (property_count > 0) {
+ peer->properties = static_cast<tsi_peer_property*>(
+ gpr_zalloc(property_count * sizeof(tsi_peer_property)));
+ peer->property_count = property_count;
+ }
+ return TSI_OK;
+}
const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer,
const char* name) {
diff --git a/contrib/libs/grpc/src/core/tsi/transport_security.h b/contrib/libs/grpc/src/core/tsi/transport_security.h
index d3b1c7f4aa9..6b71dd397f5 100644
--- a/contrib/libs/grpc/src/core/tsi/transport_security.h
+++ b/contrib/libs/grpc/src/core/tsi/transport_security.h
@@ -1,127 +1,127 @@
-/*
- *
- * 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_TSI_TRANSPORT_SECURITY_H
-#define GRPC_CORE_TSI_TRANSPORT_SECURITY_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdbool.h>
-
-#include "src/core/lib/debug/trace.h"
-#include "src/core/tsi/transport_security_interface.h"
-
-extern grpc_core::TraceFlag tsi_tracing_enabled;
-
-/* Base for tsi_frame_protector implementations.
- See transport_security_interface.h for documentation. */
+/*
+ *
+ * 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_TSI_TRANSPORT_SECURITY_H
+#define GRPC_CORE_TSI_TRANSPORT_SECURITY_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdbool.h>
+
+#include "src/core/lib/debug/trace.h"
+#include "src/core/tsi/transport_security_interface.h"
+
+extern grpc_core::TraceFlag tsi_tracing_enabled;
+
+/* Base for tsi_frame_protector implementations.
+ See transport_security_interface.h for documentation. */
struct tsi_frame_protector_vtable {
- tsi_result (*protect)(tsi_frame_protector* self,
- const unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size);
- tsi_result (*protect_flush)(tsi_frame_protector* self,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size,
- size_t* still_pending_size);
- tsi_result (*unprotect)(tsi_frame_protector* self,
- const unsigned char* protected_frames_bytes,
- size_t* protected_frames_bytes_size,
- unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size);
- void (*destroy)(tsi_frame_protector* self);
+ tsi_result (*protect)(tsi_frame_protector* self,
+ const unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size);
+ tsi_result (*protect_flush)(tsi_frame_protector* self,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size,
+ size_t* still_pending_size);
+ tsi_result (*unprotect)(tsi_frame_protector* self,
+ const unsigned char* protected_frames_bytes,
+ size_t* protected_frames_bytes_size,
+ unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size);
+ void (*destroy)(tsi_frame_protector* self);
};
-struct tsi_frame_protector {
- const tsi_frame_protector_vtable* vtable;
-};
-
-/* Base for tsi_handshaker implementations.
- See transport_security_interface.h for documentation. */
+struct tsi_frame_protector {
+ const tsi_frame_protector_vtable* vtable;
+};
+
+/* Base for tsi_handshaker implementations.
+ See transport_security_interface.h for documentation. */
struct tsi_handshaker_vtable {
- tsi_result (*get_bytes_to_send_to_peer)(tsi_handshaker* self,
- unsigned char* bytes,
- size_t* bytes_size);
- tsi_result (*process_bytes_from_peer)(tsi_handshaker* self,
- const unsigned char* bytes,
- size_t* bytes_size);
- tsi_result (*get_result)(tsi_handshaker* self);
- tsi_result (*extract_peer)(tsi_handshaker* self, tsi_peer* peer);
- tsi_result (*create_frame_protector)(tsi_handshaker* self,
- size_t* max_protected_frame_size,
- tsi_frame_protector** protector);
- void (*destroy)(tsi_handshaker* self);
- tsi_result (*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_result (*get_bytes_to_send_to_peer)(tsi_handshaker* self,
+ unsigned char* bytes,
+ size_t* bytes_size);
+ tsi_result (*process_bytes_from_peer)(tsi_handshaker* self,
+ const unsigned char* bytes,
+ size_t* bytes_size);
+ tsi_result (*get_result)(tsi_handshaker* self);
+ tsi_result (*extract_peer)(tsi_handshaker* self, tsi_peer* peer);
+ tsi_result (*create_frame_protector)(tsi_handshaker* self,
+ size_t* max_protected_frame_size,
+ tsi_frame_protector** protector);
+ void (*destroy)(tsi_handshaker* self);
+ tsi_result (*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);
void (*shutdown)(tsi_handshaker* self);
};
-struct tsi_handshaker {
- const tsi_handshaker_vtable* vtable;
- bool frame_protector_created;
- bool handshaker_result_created;
+struct tsi_handshaker {
+ const tsi_handshaker_vtable* vtable;
+ bool frame_protector_created;
+ bool handshaker_result_created;
bool handshake_shutdown;
-};
-
-/* Base for tsi_handshaker_result implementations.
- See transport_security_interface.h for documentation.
- The exec_ctx parameter in create_zero_copy_grpc_protector is supposed to be
- of type grpc_exec_ctx*, but we're using void* instead to avoid making the TSI
- API depend on grpc. The create_zero_copy_grpc_protector() method is only used
- in grpc, where we do need the exec_ctx passed through, but the API still
- needs to compile in other applications, where grpc_exec_ctx is not defined.
-*/
+};
+
+/* Base for tsi_handshaker_result implementations.
+ See transport_security_interface.h for documentation.
+ The exec_ctx parameter in create_zero_copy_grpc_protector is supposed to be
+ of type grpc_exec_ctx*, but we're using void* instead to avoid making the TSI
+ API depend on grpc. The create_zero_copy_grpc_protector() method is only used
+ in grpc, where we do need the exec_ctx passed through, but the API still
+ needs to compile in other applications, where grpc_exec_ctx is not defined.
+*/
struct tsi_handshaker_result_vtable {
- tsi_result (*extract_peer)(const tsi_handshaker_result* self, tsi_peer* peer);
- tsi_result (*create_zero_copy_grpc_protector)(
- const tsi_handshaker_result* self,
- size_t* max_output_protected_frame_size,
- tsi_zero_copy_grpc_protector** protector);
- tsi_result (*create_frame_protector)(const tsi_handshaker_result* self,
- size_t* max_output_protected_frame_size,
- tsi_frame_protector** protector);
- tsi_result (*get_unused_bytes)(const tsi_handshaker_result* self,
- const unsigned char** bytes,
- size_t* bytes_size);
- void (*destroy)(tsi_handshaker_result* self);
-};
-struct tsi_handshaker_result {
- const tsi_handshaker_result_vtable* vtable;
+ tsi_result (*extract_peer)(const tsi_handshaker_result* self, tsi_peer* peer);
+ tsi_result (*create_zero_copy_grpc_protector)(
+ const tsi_handshaker_result* self,
+ size_t* max_output_protected_frame_size,
+ tsi_zero_copy_grpc_protector** protector);
+ tsi_result (*create_frame_protector)(const tsi_handshaker_result* self,
+ size_t* max_output_protected_frame_size,
+ tsi_frame_protector** protector);
+ tsi_result (*get_unused_bytes)(const tsi_handshaker_result* self,
+ const unsigned char** bytes,
+ size_t* bytes_size);
+ void (*destroy)(tsi_handshaker_result* self);
};
-
-/* Peer and property construction/destruction functions. */
-tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer);
-tsi_peer_property tsi_init_peer_property(void);
-void tsi_peer_property_destruct(tsi_peer_property* property);
-tsi_result tsi_construct_string_peer_property(const char* name,
- const char* value,
- size_t value_length,
- tsi_peer_property* property);
-tsi_result tsi_construct_allocated_string_peer_property(
- const char* name, size_t value_length, tsi_peer_property* property);
-tsi_result tsi_construct_string_peer_property_from_cstring(
- const char* name, const char* value, tsi_peer_property* property);
+struct tsi_handshaker_result {
+ const tsi_handshaker_result_vtable* vtable;
+};
+
+/* Peer and property construction/destruction functions. */
+tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer);
+tsi_peer_property tsi_init_peer_property(void);
+void tsi_peer_property_destruct(tsi_peer_property* property);
+tsi_result tsi_construct_string_peer_property(const char* name,
+ const char* value,
+ size_t value_length,
+ tsi_peer_property* property);
+tsi_result tsi_construct_allocated_string_peer_property(
+ const char* name, size_t value_length, tsi_peer_property* property);
+tsi_result tsi_construct_string_peer_property_from_cstring(
+ const char* name, const char* value, tsi_peer_property* property);
const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer,
const char* name);
-/* Utils. */
-char* tsi_strdup(const char* src); /* Sadly, no strdup in C89. */
-
-#endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_H */
+/* Utils. */
+char* tsi_strdup(const char* src); /* Sadly, no strdup in C89. */
+
+#endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_H */
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 cec872690de..95c7217d13c 100644
--- a/contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc
+++ b/contrib/libs/grpc/src/core/tsi/transport_security_grpc.cc
@@ -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.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "src/core/tsi/transport_security_grpc.h"
-
-/* This method creates a tsi_zero_copy_grpc_protector object. */
-tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector(
- const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
- tsi_zero_copy_grpc_protector** protector) {
- if (self == nullptr || self->vtable == nullptr || protector == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->create_zero_copy_grpc_protector == nullptr) {
- return TSI_UNIMPLEMENTED;
- }
- return self->vtable->create_zero_copy_grpc_protector(
- self, max_output_protected_frame_size, protector);
-}
-
-/* --- tsi_zero_copy_grpc_protector common implementation. ---
-
- Calls specific implementation after state/input validation. */
-
-tsi_result tsi_zero_copy_grpc_protector_protect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices) {
- if (self == nullptr || self->vtable == nullptr ||
- unprotected_slices == nullptr || protected_slices == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->protect == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->protect(self, unprotected_slices, protected_slices);
-}
-
-tsi_result tsi_zero_copy_grpc_protector_unprotect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices) {
- if (self == nullptr || self->vtable == nullptr ||
- protected_slices == nullptr || unprotected_slices == nullptr) {
- return TSI_INVALID_ARGUMENT;
- }
- if (self->vtable->unprotect == nullptr) return TSI_UNIMPLEMENTED;
- return self->vtable->unprotect(self, protected_slices, unprotected_slices);
-}
-
-void tsi_zero_copy_grpc_protector_destroy(tsi_zero_copy_grpc_protector* self) {
- if (self == nullptr) return;
- self->vtable->destroy(self);
-}
+/*
+ *
+ * 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/tsi/transport_security_grpc.h"
+
+/* This method creates a tsi_zero_copy_grpc_protector object. */
+tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector(
+ const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
+ tsi_zero_copy_grpc_protector** protector) {
+ if (self == nullptr || self->vtable == nullptr || protector == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->create_zero_copy_grpc_protector == nullptr) {
+ return TSI_UNIMPLEMENTED;
+ }
+ return self->vtable->create_zero_copy_grpc_protector(
+ self, max_output_protected_frame_size, protector);
+}
+
+/* --- tsi_zero_copy_grpc_protector common implementation. ---
+
+ Calls specific implementation after state/input validation. */
+
+tsi_result tsi_zero_copy_grpc_protector_protect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices) {
+ if (self == nullptr || self->vtable == nullptr ||
+ unprotected_slices == nullptr || protected_slices == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->protect == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->protect(self, unprotected_slices, protected_slices);
+}
+
+tsi_result tsi_zero_copy_grpc_protector_unprotect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices) {
+ if (self == nullptr || self->vtable == nullptr ||
+ protected_slices == nullptr || unprotected_slices == nullptr) {
+ return TSI_INVALID_ARGUMENT;
+ }
+ if (self->vtable->unprotect == nullptr) return TSI_UNIMPLEMENTED;
+ return self->vtable->unprotect(self, protected_slices, unprotected_slices);
+}
+
+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_zero_copy_grpc_protector* self, size_t* 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 4779b686c66..4e22db06fc2 100644
--- a/contrib/libs/grpc/src/core/tsi/transport_security_grpc.h
+++ b/contrib/libs/grpc/src/core/tsi/transport_security_grpc.h
@@ -1,79 +1,79 @@
-/*
- *
- * 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_TSI_TRANSPORT_SECURITY_GRPC_H
-#define GRPC_CORE_TSI_TRANSPORT_SECURITY_GRPC_H
-
-#include <grpc/support/port_platform.h>
-
-#include <grpc/slice_buffer.h>
-#include "src/core/tsi/transport_security.h"
-
-/* This method creates a tsi_zero_copy_grpc_protector object. It return TSI_OK
- assuming there is no fatal error.
- The caller is responsible for destroying the protector. */
-tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector(
- const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
- tsi_zero_copy_grpc_protector** protector);
-
-/* -- tsi_zero_copy_grpc_protector object -- */
-
-/* Outputs protected frames.
- - unprotected_slices is the unprotected data to be protected.
- - protected_slices is the protected output frames. One or more frames
- may be produced in this protect function.
- - This method returns TSI_OK in case of success or a specific error code in
- case of failure. */
-tsi_result tsi_zero_copy_grpc_protector_protect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices);
-
-/* Outputs unprotected bytes.
- - protected_slices is the bytes of protected frames.
- - unprotected_slices is the unprotected output data.
- - This method returns TSI_OK in case of success. Success includes cases where
- there is not enough data to output in which case unprotected_slices has 0
- bytes. */
-tsi_result tsi_zero_copy_grpc_protector_unprotect(
- tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices);
-
-/* Destroys the tsi_zero_copy_grpc_protector object. */
-void tsi_zero_copy_grpc_protector_destroy(tsi_zero_copy_grpc_protector* self);
-
+/*
+ *
+ * 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_TSI_TRANSPORT_SECURITY_GRPC_H
+#define GRPC_CORE_TSI_TRANSPORT_SECURITY_GRPC_H
+
+#include <grpc/support/port_platform.h>
+
+#include <grpc/slice_buffer.h>
+#include "src/core/tsi/transport_security.h"
+
+/* This method creates a tsi_zero_copy_grpc_protector object. It return TSI_OK
+ assuming there is no fatal error.
+ The caller is responsible for destroying the protector. */
+tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector(
+ const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
+ tsi_zero_copy_grpc_protector** protector);
+
+/* -- tsi_zero_copy_grpc_protector object -- */
+
+/* Outputs protected frames.
+ - unprotected_slices is the unprotected data to be protected.
+ - protected_slices is the protected output frames. One or more frames
+ may be produced in this protect function.
+ - This method returns TSI_OK in case of success or a specific error code in
+ case of failure. */
+tsi_result tsi_zero_copy_grpc_protector_protect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices);
+
+/* Outputs unprotected bytes.
+ - protected_slices is the bytes of protected frames.
+ - unprotected_slices is the unprotected output data.
+ - This method returns TSI_OK in case of success. Success includes cases where
+ there is not enough data to output in which case unprotected_slices has 0
+ bytes. */
+tsi_result tsi_zero_copy_grpc_protector_unprotect(
+ tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices,
+ grpc_slice_buffer* unprotected_slices);
+
+/* 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(
tsi_zero_copy_grpc_protector* self, size_t* max_frame_size);
-/* Base for tsi_zero_copy_grpc_protector implementations. */
+/* Base for tsi_zero_copy_grpc_protector implementations. */
struct tsi_zero_copy_grpc_protector_vtable {
- tsi_result (*protect)(tsi_zero_copy_grpc_protector* self,
- grpc_slice_buffer* unprotected_slices,
- grpc_slice_buffer* protected_slices);
- tsi_result (*unprotect)(tsi_zero_copy_grpc_protector* self,
- grpc_slice_buffer* protected_slices,
- grpc_slice_buffer* unprotected_slices);
- void (*destroy)(tsi_zero_copy_grpc_protector* self);
+ tsi_result (*protect)(tsi_zero_copy_grpc_protector* self,
+ grpc_slice_buffer* unprotected_slices,
+ grpc_slice_buffer* protected_slices);
+ tsi_result (*unprotect)(tsi_zero_copy_grpc_protector* self,
+ 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,
size_t* max_frame_size);
};
-struct tsi_zero_copy_grpc_protector {
- const tsi_zero_copy_grpc_protector_vtable* vtable;
-};
-
-#endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_GRPC_H */
+struct tsi_zero_copy_grpc_protector {
+ const tsi_zero_copy_grpc_protector_vtable* vtable;
+};
+
+#endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_GRPC_H */
diff --git a/contrib/libs/grpc/src/core/tsi/transport_security_interface.h b/contrib/libs/grpc/src/core/tsi/transport_security_interface.h
index 4608f400914..dff0aa3835a 100644
--- a/contrib/libs/grpc/src/core/tsi/transport_security_interface.h
+++ b/contrib/libs/grpc/src/core/tsi/transport_security_interface.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_CORE_TSI_TRANSPORT_SECURITY_INTERFACE_H
-#define GRPC_CORE_TSI_TRANSPORT_SECURITY_INTERFACE_H
-
-#include <grpc/support/port_platform.h>
-
-#include <stdint.h>
-#include <stdlib.h>
-
-#include "src/core/lib/debug/trace.h"
-
-/* --- tsi result --- */
-
-typedef enum {
- TSI_OK = 0,
- TSI_UNKNOWN_ERROR = 1,
- TSI_INVALID_ARGUMENT = 2,
- TSI_PERMISSION_DENIED = 3,
- TSI_INCOMPLETE_DATA = 4,
- TSI_FAILED_PRECONDITION = 5,
- TSI_UNIMPLEMENTED = 6,
- TSI_INTERNAL_ERROR = 7,
- TSI_DATA_CORRUPTED = 8,
- TSI_NOT_FOUND = 9,
- TSI_PROTOCOL_FAILURE = 10,
- TSI_HANDSHAKE_IN_PROGRESS = 11,
- TSI_OUT_OF_RESOURCES = 12,
+/*
+ *
+ * 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_TSI_TRANSPORT_SECURITY_INTERFACE_H
+#define GRPC_CORE_TSI_TRANSPORT_SECURITY_INTERFACE_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "src/core/lib/debug/trace.h"
+
+/* --- tsi result --- */
+
+typedef enum {
+ TSI_OK = 0,
+ TSI_UNKNOWN_ERROR = 1,
+ TSI_INVALID_ARGUMENT = 2,
+ TSI_PERMISSION_DENIED = 3,
+ TSI_INCOMPLETE_DATA = 4,
+ TSI_FAILED_PRECONDITION = 5,
+ TSI_UNIMPLEMENTED = 6,
+ TSI_INTERNAL_ERROR = 7,
+ TSI_DATA_CORRUPTED = 8,
+ TSI_NOT_FOUND = 9,
+ TSI_PROTOCOL_FAILURE = 10,
+ TSI_HANDSHAKE_IN_PROGRESS = 11,
+ TSI_OUT_OF_RESOURCES = 12,
TSI_ASYNC = 13,
TSI_HANDSHAKE_SHUTDOWN = 14,
TSI_CLOSE_NOTIFY = 15, // Indicates that the connection should be closed.
-} tsi_result;
-
-typedef enum {
+} tsi_result;
+
+typedef enum {
TSI_SECURITY_MIN,
TSI_SECURITY_NONE = TSI_SECURITY_MIN,
TSI_INTEGRITY_ONLY,
@@ -56,410 +56,410 @@ typedef enum {
} tsi_security_level;
typedef enum {
- // Default option
- TSI_DONT_REQUEST_CLIENT_CERTIFICATE,
- TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY,
- TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY,
- TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY,
- TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY,
-} tsi_client_certificate_request_type;
-
+ // Default option
+ TSI_DONT_REQUEST_CLIENT_CERTIFICATE,
+ TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY,
+ TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY,
+ TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY,
+ TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY,
+} tsi_client_certificate_request_type;
+
typedef enum {
TSI_TLS1_2,
TSI_TLS1_3,
} tsi_tls_version;
-const char* tsi_result_to_string(tsi_result result);
+const char* tsi_result_to_string(tsi_result result);
const char* tsi_security_level_to_string(tsi_security_level security_level);
-
-/* --- tsi tracing --- */
-
-extern grpc_core::TraceFlag tsi_tracing_enabled;
-
-/* -- tsi_zero_copy_grpc_protector object --
-
- This object protects and unprotects grpc slice buffers with zero or minimized
- memory copy once the handshake is done. Implementations of this object must be
- thread compatible. This object depends on grpc and the details of this object
- is defined in transport_security_grpc.h. */
-
-typedef struct tsi_zero_copy_grpc_protector tsi_zero_copy_grpc_protector;
-
-/* --- tsi_frame_protector object ---
-
- This object protects and unprotects buffers once the handshake is done.
- Implementations of this object must be thread compatible. */
-
-typedef struct tsi_frame_protector tsi_frame_protector;
-
-/* Outputs protected frames.
- - unprotected_bytes is an input only parameter and points to the data
- to be protected.
- - unprotected_bytes_size is an input/output parameter used by the caller to
- specify how many bytes are available in unprotected_bytes. The output
- value is the number of bytes consumed during the call.
- - protected_output_frames points to a buffer allocated by the caller that
- will be written.
- - protected_output_frames_size is an input/output parameter used by the
- caller to specify how many bytes are available in protected_output_frames.
- As an output, this value indicates the number of bytes written.
- - This method returns TSI_OK in case of success or a specific error code in
- case of failure. Note that even if all the input unprotected bytes are
- consumed, they may not have been processed into the returned protected
- output frames. The caller should call the protect_flush method
- to make sure that there are no more protected bytes buffered in the
- protector.
-
- A typical way to call this method would be:
-
- ------------------------------------------------------------------------
- unsigned char protected_buffer[4096];
- size_t protected_buffer_size = sizeof(protected_buffer);
- tsi_result result = TSI_OK;
- while (message_size > 0) {
- size_t protected_buffer_size_to_send = protected_buffer_size;
- size_t processed_message_size = message_size;
- result = tsi_frame_protector_protect(protector,
- message_bytes,
- &processed_message_size,
- protected_buffer,
- &protected_buffer_size_to_send);
- if (result != TSI_OK) break;
- send_bytes_to_peer(protected_buffer, protected_buffer_size_to_send);
- message_bytes += processed_message_size;
- message_size -= processed_message_size;
-
- // Don't forget to flush.
- if (message_size == 0) {
- size_t still_pending_size;
- do {
- protected_buffer_size_to_send = protected_buffer_size;
- result = tsi_frame_protector_protect_flush(
- protector, protected_buffer,
- &protected_buffer_size_to_send, &still_pending_size);
- if (result != TSI_OK) break;
- send_bytes_to_peer(protected_buffer, protected_buffer_size_to_send);
- } while (still_pending_size > 0);
- }
- }
-
- if (result != TSI_OK) HandleError(result);
- ------------------------------------------------------------------------ */
-tsi_result tsi_frame_protector_protect(tsi_frame_protector* self,
- const unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size,
- unsigned char* protected_output_frames,
- size_t* protected_output_frames_size);
-
-/* Indicates that we need to flush the bytes buffered in the protector and get
- the resulting frame.
- - protected_output_frames points to a buffer allocated by the caller that
- will be written.
- - protected_output_frames_size is an input/output parameter used by the
- caller to specify how many bytes are available in protected_output_frames.
- - still_pending_bytes is an output parameter indicating the number of bytes
- that still need to be flushed from the protector.*/
-tsi_result tsi_frame_protector_protect_flush(
- tsi_frame_protector* self, unsigned char* protected_output_frames,
- size_t* protected_output_frames_size, size_t* still_pending_size);
-
-/* Outputs unprotected bytes.
- - protected_frames_bytes is an input only parameter and points to the
- protected frames to be unprotected.
- - protected_frames_bytes_size is an input/output only parameter used by the
- caller to specify how many bytes are available in protected_bytes. The
- output value is the number of bytes consumed during the call.
- Implementations will buffer up to a frame of protected data.
- - unprotected_bytes points to a buffer allocated by the caller that will be
- written.
- - unprotected_bytes_size is an input/output parameter used by the caller to
- specify how many bytes are available in unprotected_bytes. This
- value is expected to be at most max_protected_frame_size minus overhead
- which means that max_protected_frame_size is a safe bet. The output value
- is the number of bytes actually written.
- If *unprotected_bytes_size is unchanged, there may be more data remaining
- to unprotect, and the caller should call this function again.
-
- - This method returns TSI_OK in case of success. Success includes cases where
- there is not enough data to output a frame in which case
- unprotected_bytes_size will be set to 0 and cases where the internal buffer
- needs to be read before new protected data can be processed in which case
- protected_frames_size will be set to 0. */
-tsi_result tsi_frame_protector_unprotect(
- tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
- size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
- size_t* unprotected_bytes_size);
-
-/* Destroys the tsi_frame_protector object. */
-void tsi_frame_protector_destroy(tsi_frame_protector* self);
-
-/* --- tsi_peer objects ---
-
- tsi_peer objects are a set of properties. The peer owns the properties. */
-
-/* This property is of type TSI_PEER_PROPERTY_STRING. */
-#define TSI_CERTIFICATE_TYPE_PEER_PROPERTY "certificate_type"
-
+
+/* --- tsi tracing --- */
+
+extern grpc_core::TraceFlag tsi_tracing_enabled;
+
+/* -- tsi_zero_copy_grpc_protector object --
+
+ This object protects and unprotects grpc slice buffers with zero or minimized
+ memory copy once the handshake is done. Implementations of this object must be
+ thread compatible. This object depends on grpc and the details of this object
+ is defined in transport_security_grpc.h. */
+
+typedef struct tsi_zero_copy_grpc_protector tsi_zero_copy_grpc_protector;
+
+/* --- tsi_frame_protector object ---
+
+ This object protects and unprotects buffers once the handshake is done.
+ Implementations of this object must be thread compatible. */
+
+typedef struct tsi_frame_protector tsi_frame_protector;
+
+/* Outputs protected frames.
+ - unprotected_bytes is an input only parameter and points to the data
+ to be protected.
+ - unprotected_bytes_size is an input/output parameter used by the caller to
+ specify how many bytes are available in unprotected_bytes. The output
+ value is the number of bytes consumed during the call.
+ - protected_output_frames points to a buffer allocated by the caller that
+ will be written.
+ - protected_output_frames_size is an input/output parameter used by the
+ caller to specify how many bytes are available in protected_output_frames.
+ As an output, this value indicates the number of bytes written.
+ - This method returns TSI_OK in case of success or a specific error code in
+ case of failure. Note that even if all the input unprotected bytes are
+ consumed, they may not have been processed into the returned protected
+ output frames. The caller should call the protect_flush method
+ to make sure that there are no more protected bytes buffered in the
+ protector.
+
+ A typical way to call this method would be:
+
+ ------------------------------------------------------------------------
+ unsigned char protected_buffer[4096];
+ size_t protected_buffer_size = sizeof(protected_buffer);
+ tsi_result result = TSI_OK;
+ while (message_size > 0) {
+ size_t protected_buffer_size_to_send = protected_buffer_size;
+ size_t processed_message_size = message_size;
+ result = tsi_frame_protector_protect(protector,
+ message_bytes,
+ &processed_message_size,
+ protected_buffer,
+ &protected_buffer_size_to_send);
+ if (result != TSI_OK) break;
+ send_bytes_to_peer(protected_buffer, protected_buffer_size_to_send);
+ message_bytes += processed_message_size;
+ message_size -= processed_message_size;
+
+ // Don't forget to flush.
+ if (message_size == 0) {
+ size_t still_pending_size;
+ do {
+ protected_buffer_size_to_send = protected_buffer_size;
+ result = tsi_frame_protector_protect_flush(
+ protector, protected_buffer,
+ &protected_buffer_size_to_send, &still_pending_size);
+ if (result != TSI_OK) break;
+ send_bytes_to_peer(protected_buffer, protected_buffer_size_to_send);
+ } while (still_pending_size > 0);
+ }
+ }
+
+ if (result != TSI_OK) HandleError(result);
+ ------------------------------------------------------------------------ */
+tsi_result tsi_frame_protector_protect(tsi_frame_protector* self,
+ const unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size,
+ unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size);
+
+/* Indicates that we need to flush the bytes buffered in the protector and get
+ the resulting frame.
+ - protected_output_frames points to a buffer allocated by the caller that
+ will be written.
+ - protected_output_frames_size is an input/output parameter used by the
+ caller to specify how many bytes are available in protected_output_frames.
+ - still_pending_bytes is an output parameter indicating the number of bytes
+ that still need to be flushed from the protector.*/
+tsi_result tsi_frame_protector_protect_flush(
+ tsi_frame_protector* self, unsigned char* protected_output_frames,
+ size_t* protected_output_frames_size, size_t* still_pending_size);
+
+/* Outputs unprotected bytes.
+ - protected_frames_bytes is an input only parameter and points to the
+ protected frames to be unprotected.
+ - protected_frames_bytes_size is an input/output only parameter used by the
+ caller to specify how many bytes are available in protected_bytes. The
+ output value is the number of bytes consumed during the call.
+ Implementations will buffer up to a frame of protected data.
+ - unprotected_bytes points to a buffer allocated by the caller that will be
+ written.
+ - unprotected_bytes_size is an input/output parameter used by the caller to
+ specify how many bytes are available in unprotected_bytes. This
+ value is expected to be at most max_protected_frame_size minus overhead
+ which means that max_protected_frame_size is a safe bet. The output value
+ is the number of bytes actually written.
+ If *unprotected_bytes_size is unchanged, there may be more data remaining
+ to unprotect, and the caller should call this function again.
+
+ - This method returns TSI_OK in case of success. Success includes cases where
+ there is not enough data to output a frame in which case
+ unprotected_bytes_size will be set to 0 and cases where the internal buffer
+ needs to be read before new protected data can be processed in which case
+ protected_frames_size will be set to 0. */
+tsi_result tsi_frame_protector_unprotect(
+ tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
+ size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
+ size_t* unprotected_bytes_size);
+
+/* Destroys the tsi_frame_protector object. */
+void tsi_frame_protector_destroy(tsi_frame_protector* self);
+
+/* --- tsi_peer objects ---
+
+ tsi_peer objects are a set of properties. The peer owns the properties. */
+
+/* This property is of type TSI_PEER_PROPERTY_STRING. */
+#define TSI_CERTIFICATE_TYPE_PEER_PROPERTY "certificate_type"
+
/* This property represents security level of a channel. */
#define TSI_SECURITY_LEVEL_PEER_PROPERTY "security_level"
-/* Property values may contain NULL characters just like C++ strings.
- The length field gives the length of the string. */
-typedef struct tsi_peer_property {
- char* name;
- struct {
- char* data;
- size_t length;
- } value;
-} tsi_peer_property;
-
+/* Property values may contain NULL characters just like C++ strings.
+ The length field gives the length of the string. */
+typedef struct tsi_peer_property {
+ char* name;
+ struct {
+ char* data;
+ size_t length;
+ } value;
+} tsi_peer_property;
+
struct tsi_peer {
- tsi_peer_property* properties;
- size_t property_count;
+ tsi_peer_property* properties;
+ size_t property_count;
};
-/* Destructs the tsi_peer object. */
-void tsi_peer_destruct(tsi_peer* self);
-
-/* --- tsi_handshaker_result object ---
-
- This object contains all necessary handshake results and data such as peer
- info, negotiated keys, unused handshake bytes, when the handshake completes.
- Implementations of this object must be thread compatible. */
-
-typedef struct tsi_handshaker_result tsi_handshaker_result;
-
-/* This method extracts tsi peer. It returns TSI_OK assuming there is no fatal
- error.
- The caller is responsible for destructing the peer. */
-tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result* self,
- tsi_peer* peer);
-
-/* This method creates a tsi_frame_protector object. It returns TSI_OK assuming
- there is no fatal error.
- The caller is responsible for destroying the protector. */
-tsi_result tsi_handshaker_result_create_frame_protector(
- const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
- tsi_frame_protector** protector);
-
-/* This method returns the unused bytes from the handshake. It returns TSI_OK
- assuming there is no fatal error.
- Ownership of the bytes is retained by the handshaker result. As a
- consequence, the caller must not free the bytes. */
-tsi_result tsi_handshaker_result_get_unused_bytes(
- const tsi_handshaker_result* self, const unsigned char** bytes,
- size_t* byte_size);
-
-/* This method releases the tsi_handshaker_handshaker object. After this method
- is called, no other method can be called on the object. */
-void tsi_handshaker_result_destroy(tsi_handshaker_result* self);
-
-/* --- tsi_handshaker objects ----
-
- Implementations of this object must be thread compatible.
-
- ------------------------------------------------------------------------
-
- A typical usage supporting both synchronous and asynchronous TSI handshaker
- implementations would be:
-
- ------------------------------------------------------------------------
-
- typedef struct {
- tsi_handshaker *handshaker;
- tsi_handshaker_result *handshaker_result;
- unsigned char *handshake_buffer;
- size_t handshake_buffer_size;
- ...
- } security_handshaker;
-
- void do_handshake(security_handshaker *h, ...) {
- // Start the handshake by the calling do_handshake_next.
- do_handshake_next(h, NULL, 0);
- ...
- }
-
- // This method is the callback function when data is received from the
- // peer. This method will read bytes into the handshake buffer and call
- // do_handshake_next.
- void on_handshake_data_received_from_peer(void *user_data) {
- security_handshaker *h = (security_handshaker *)user_data;
- size_t bytes_received_size = h->handshake_buffer_size;
- read_bytes_from_peer(h->handshake_buffer, &bytes_received_size);
- do_handshake_next(h, h->handshake_buffer, bytes_received_size);
- }
-
- // This method processes a step of handshake, calling tsi_handshaker_next.
- void do_handshake_next(security_handshaker *h,
- const unsigned char* bytes_received,
- size_t bytes_received_size) {
- tsi_result status = TSI_OK;
- unsigned char *bytes_to_send = NULL;
- size_t bytes_to_send_size = 0;
- tsi_handshaker_result *result = NULL;
- status = tsi_handshaker_next(
- handshaker, bytes_received, bytes_received_size, &bytes_to_send,
- &bytes_to_send_size, &result, on_handshake_next_done, h);
- // If TSI handshaker is asynchronous, on_handshake_next_done will be
- // executed inside tsi_handshaker_next.
- if (status == TSI_ASYNC) return;
- // If TSI handshaker is synchronous, invoke callback directly in this
- // thread.
- on_handshake_next_done(status, (void *)h, bytes_to_send,
- bytes_to_send_size, result);
- }
-
- // This is the callback function to execute after tsi_handshaker_next.
- // It is passed to tsi_handshaker_next as a function parameter.
- void on_handshake_next_done(
- tsi_result status, void *user_data, const unsigned char *bytes_to_send,
- size_t bytes_to_send_size, tsi_handshaker_result *result) {
- security_handshaker *h = (security_handshaker *)user_data;
- if (status == TSI_INCOMPLETE_DATA) {
- // Schedule an asynchronous read from the peer. If handshake data are
- // received, on_handshake_data_received_from_peer will be called.
- async_read_from_peer(..., ..., on_handshake_data_received_from_peer);
- return;
- }
- if (status != TSI_OK) return;
-
- if (bytes_to_send_size > 0) {
- send_bytes_to_peer(bytes_to_send, bytes_to_send_size);
- }
-
- if (result != NULL) {
- // Handshake completed.
- h->result = result;
- // Check the Peer.
- tsi_peer peer;
- status = tsi_handshaker_result_extract_peer(result, &peer);
- if (status != TSI_OK) return;
- status = check_peer(&peer);
- tsi_peer_destruct(&peer);
- if (status != TSI_OK) return;
-
- // Create the protector.
- tsi_frame_protector* protector = NULL;
- status = tsi_handshaker_result_create_frame_protector(result, NULL,
- &protector);
- if (status != TSI_OK) return;
-
- // Do not forget to unprotect outstanding data if any.
- ....
- }
- }
- ------------------------------------------------------------------------ */
-typedef struct tsi_handshaker tsi_handshaker;
-
+/* Destructs the tsi_peer object. */
+void tsi_peer_destruct(tsi_peer* self);
+
+/* --- tsi_handshaker_result object ---
+
+ This object contains all necessary handshake results and data such as peer
+ info, negotiated keys, unused handshake bytes, when the handshake completes.
+ Implementations of this object must be thread compatible. */
+
+typedef struct tsi_handshaker_result tsi_handshaker_result;
+
+/* This method extracts tsi peer. It returns TSI_OK assuming there is no fatal
+ error.
+ The caller is responsible for destructing the peer. */
+tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result* self,
+ tsi_peer* peer);
+
+/* This method creates a tsi_frame_protector object. It returns TSI_OK assuming
+ there is no fatal error.
+ The caller is responsible for destroying the protector. */
+tsi_result tsi_handshaker_result_create_frame_protector(
+ const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
+ tsi_frame_protector** protector);
+
+/* This method returns the unused bytes from the handshake. It returns TSI_OK
+ assuming there is no fatal error.
+ Ownership of the bytes is retained by the handshaker result. As a
+ consequence, the caller must not free the bytes. */
+tsi_result tsi_handshaker_result_get_unused_bytes(
+ const tsi_handshaker_result* self, const unsigned char** bytes,
+ size_t* byte_size);
+
+/* This method releases the tsi_handshaker_handshaker object. After this method
+ is called, no other method can be called on the object. */
+void tsi_handshaker_result_destroy(tsi_handshaker_result* self);
+
+/* --- tsi_handshaker objects ----
+
+ Implementations of this object must be thread compatible.
+
+ ------------------------------------------------------------------------
+
+ A typical usage supporting both synchronous and asynchronous TSI handshaker
+ implementations would be:
+
+ ------------------------------------------------------------------------
+
+ typedef struct {
+ tsi_handshaker *handshaker;
+ tsi_handshaker_result *handshaker_result;
+ unsigned char *handshake_buffer;
+ size_t handshake_buffer_size;
+ ...
+ } security_handshaker;
+
+ void do_handshake(security_handshaker *h, ...) {
+ // Start the handshake by the calling do_handshake_next.
+ do_handshake_next(h, NULL, 0);
+ ...
+ }
+
+ // This method is the callback function when data is received from the
+ // peer. This method will read bytes into the handshake buffer and call
+ // do_handshake_next.
+ void on_handshake_data_received_from_peer(void *user_data) {
+ security_handshaker *h = (security_handshaker *)user_data;
+ size_t bytes_received_size = h->handshake_buffer_size;
+ read_bytes_from_peer(h->handshake_buffer, &bytes_received_size);
+ do_handshake_next(h, h->handshake_buffer, bytes_received_size);
+ }
+
+ // This method processes a step of handshake, calling tsi_handshaker_next.
+ void do_handshake_next(security_handshaker *h,
+ const unsigned char* bytes_received,
+ size_t bytes_received_size) {
+ tsi_result status = TSI_OK;
+ unsigned char *bytes_to_send = NULL;
+ size_t bytes_to_send_size = 0;
+ tsi_handshaker_result *result = NULL;
+ status = tsi_handshaker_next(
+ handshaker, bytes_received, bytes_received_size, &bytes_to_send,
+ &bytes_to_send_size, &result, on_handshake_next_done, h);
+ // If TSI handshaker is asynchronous, on_handshake_next_done will be
+ // executed inside tsi_handshaker_next.
+ if (status == TSI_ASYNC) return;
+ // If TSI handshaker is synchronous, invoke callback directly in this
+ // thread.
+ on_handshake_next_done(status, (void *)h, bytes_to_send,
+ bytes_to_send_size, result);
+ }
+
+ // This is the callback function to execute after tsi_handshaker_next.
+ // It is passed to tsi_handshaker_next as a function parameter.
+ void on_handshake_next_done(
+ tsi_result status, void *user_data, const unsigned char *bytes_to_send,
+ size_t bytes_to_send_size, tsi_handshaker_result *result) {
+ security_handshaker *h = (security_handshaker *)user_data;
+ if (status == TSI_INCOMPLETE_DATA) {
+ // Schedule an asynchronous read from the peer. If handshake data are
+ // received, on_handshake_data_received_from_peer will be called.
+ async_read_from_peer(..., ..., on_handshake_data_received_from_peer);
+ return;
+ }
+ if (status != TSI_OK) return;
+
+ if (bytes_to_send_size > 0) {
+ send_bytes_to_peer(bytes_to_send, bytes_to_send_size);
+ }
+
+ if (result != NULL) {
+ // Handshake completed.
+ h->result = result;
+ // Check the Peer.
+ tsi_peer peer;
+ status = tsi_handshaker_result_extract_peer(result, &peer);
+ if (status != TSI_OK) return;
+ status = check_peer(&peer);
+ tsi_peer_destruct(&peer);
+ if (status != TSI_OK) return;
+
+ // Create the protector.
+ tsi_frame_protector* protector = NULL;
+ status = tsi_handshaker_result_create_frame_protector(result, NULL,
+ &protector);
+ if (status != TSI_OK) return;
+
+ // Do not forget to unprotect outstanding data if any.
+ ....
+ }
+ }
+ ------------------------------------------------------------------------ */
+typedef struct tsi_handshaker tsi_handshaker;
+
/* TODO(jiangtaoli2016): Cleans up deprecated methods when we are ready. */
-/* TO BE DEPRECATED SOON. Use tsi_handshaker_next instead.
- Gets bytes that need to be sent to the peer.
- - bytes is the buffer that will be written with the data to be sent to the
- peer.
- - bytes_size is an input/output parameter specifying the capacity of the
- bytes parameter as input and the number of bytes written as output.
- Returns TSI_OK if all the data to send to the peer has been written or if
- nothing has to be sent to the peer (in which base bytes_size outputs to 0),
- otherwise returns TSI_INCOMPLETE_DATA which indicates that this method
- needs to be called again to get all the bytes to send to the peer (there
- was more data to write than the specified bytes_size). In case of a fatal
- error in the handshake, another specific error code is returned. */
-tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
- unsigned char* bytes,
- size_t* bytes_size);
-
-/* TO BE DEPRECATED SOON. Use tsi_handshaker_next instead.
- Processes bytes received from the peer.
- - bytes is the buffer containing the data.
- - bytes_size is an input/output parameter specifying the size of the data as
- input and the number of bytes consumed as output.
- Return TSI_OK if the handshake has all the data it needs to process,
- otherwise return TSI_INCOMPLETE_DATA which indicates that this method
- needs to be called again to complete the data needed for processing. In
- case of a fatal error in the handshake, another specific error code is
- returned. */
-tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self,
- const unsigned char* bytes,
- size_t* bytes_size);
-
-/* TO BE DEPRECATED SOON.
- Gets the result of the handshaker.
- Returns TSI_OK if the hanshake completed successfully and there has been no
- errors. Returns TSI_HANDSHAKE_IN_PROGRESS if the handshaker is not done yet
- but no error has been encountered so far. Otherwise the handshaker failed
- with the returned error. */
-tsi_result tsi_handshaker_get_result(tsi_handshaker* self);
-
-/* TO BE DEPRECATED SOON.
- Returns 1 if the handshake is in progress, 0 otherwise. */
-#define tsi_handshaker_is_in_progress(h) \
- (tsi_handshaker_get_result((h)) == TSI_HANDSHAKE_IN_PROGRESS)
-
-/* TO BE DEPRECATED SOON. Use tsi_handshaker_result_extract_peer instead.
- This method may return TSI_FAILED_PRECONDITION if
- tsi_handshaker_is_in_progress returns 1, it returns TSI_OK otherwise
- assuming the handshaker is not in a fatal error state.
- The caller is responsible for destructing the peer. */
-tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer);
-
-/* TO BE DEPRECATED SOON. Use tsi_handshaker_result_create_frame_protector
- instead.
- This method creates a tsi_frame_protector object after the handshake phase
- is done. After this method has been called successfully, the only method
- that can be called on this object is Destroy.
- - max_output_protected_frame_size is an input/output parameter specifying the
- desired max output protected frame size as input and outputing the actual
- max output frame size as the output. Passing NULL is OK and will result in
- the implementation choosing the default maximum protected frame size. Note
- that this size only applies to outgoing frames (generated with
- tsi_frame_protector_protect) and not incoming frames (input of
- tsi_frame_protector_unprotect).
- - protector is an output parameter pointing to the newly created
- tsi_frame_protector object.
- This method may return TSI_FAILED_PRECONDITION if
- tsi_handshaker_is_in_progress returns 1, it returns TSI_OK otherwise assuming
- the handshaker is not in a fatal error state.
- The caller is responsible for destroying the protector. */
-tsi_result tsi_handshaker_create_frame_protector(
- tsi_handshaker* self, size_t* max_output_protected_frame_size,
- tsi_frame_protector** protector);
-
-/* Callback function definition for tsi_handshaker_next.
- - status indicates the status of the next operation.
- - user_data is the argument to callback function passed from the caller.
- - bytes_to_send is the data buffer to be sent to the peer.
- - bytes_to_send_size is the size of data buffer to be sent to the peer.
- - handshaker_result is the result of handshake when the handshake completes,
- is NULL otherwise. */
-typedef void (*tsi_handshaker_on_next_done_cb)(
- tsi_result status, void* user_data, const unsigned char* bytes_to_send,
- size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result);
-
-/* Conduct a next step of the handshake.
- - received_bytes is the buffer containing the data received from the peer.
- - received_bytes_size is the size of the data received from the peer.
- - bytes_to_send is the data buffer to be sent to the peer.
- - bytes_to_send_size is the size of data buffer to be sent to the peer.
- - handshaker_result is the result of handshake if the handshake completes.
- - cb is the callback function defined above. It can be NULL for synchronous
- TSI handshaker implementation.
- - user_data is the argument to callback function passed from the caller.
- This method returns TSI_ASYNC if the TSI handshaker implementation is
- asynchronous, and in this case, the callback is guaranteed to run in another
- thread owned by TSI. It returns TSI_OK if the handshake completes or if
- there are data to send to the peer, otherwise returns TSI_INCOMPLETE_DATA
- which indicates that this method needs to be called again with more data
- from the peer. In case of a fatal error in the handshake, another specific
- error code is returned.
- The caller is responsible for destroying the handshaker_result. However,
- the caller should not free bytes_to_send, as the buffer is owned by the
- tsi_handshaker object. */
-tsi_result tsi_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);
-
+/* TO BE DEPRECATED SOON. Use tsi_handshaker_next instead.
+ Gets bytes that need to be sent to the peer.
+ - bytes is the buffer that will be written with the data to be sent to the
+ peer.
+ - bytes_size is an input/output parameter specifying the capacity of the
+ bytes parameter as input and the number of bytes written as output.
+ Returns TSI_OK if all the data to send to the peer has been written or if
+ nothing has to be sent to the peer (in which base bytes_size outputs to 0),
+ otherwise returns TSI_INCOMPLETE_DATA which indicates that this method
+ needs to be called again to get all the bytes to send to the peer (there
+ was more data to write than the specified bytes_size). In case of a fatal
+ error in the handshake, another specific error code is returned. */
+tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
+ unsigned char* bytes,
+ size_t* bytes_size);
+
+/* TO BE DEPRECATED SOON. Use tsi_handshaker_next instead.
+ Processes bytes received from the peer.
+ - bytes is the buffer containing the data.
+ - bytes_size is an input/output parameter specifying the size of the data as
+ input and the number of bytes consumed as output.
+ Return TSI_OK if the handshake has all the data it needs to process,
+ otherwise return TSI_INCOMPLETE_DATA which indicates that this method
+ needs to be called again to complete the data needed for processing. In
+ case of a fatal error in the handshake, another specific error code is
+ returned. */
+tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self,
+ const unsigned char* bytes,
+ size_t* bytes_size);
+
+/* TO BE DEPRECATED SOON.
+ Gets the result of the handshaker.
+ Returns TSI_OK if the hanshake completed successfully and there has been no
+ errors. Returns TSI_HANDSHAKE_IN_PROGRESS if the handshaker is not done yet
+ but no error has been encountered so far. Otherwise the handshaker failed
+ with the returned error. */
+tsi_result tsi_handshaker_get_result(tsi_handshaker* self);
+
+/* TO BE DEPRECATED SOON.
+ Returns 1 if the handshake is in progress, 0 otherwise. */
+#define tsi_handshaker_is_in_progress(h) \
+ (tsi_handshaker_get_result((h)) == TSI_HANDSHAKE_IN_PROGRESS)
+
+/* TO BE DEPRECATED SOON. Use tsi_handshaker_result_extract_peer instead.
+ This method may return TSI_FAILED_PRECONDITION if
+ tsi_handshaker_is_in_progress returns 1, it returns TSI_OK otherwise
+ assuming the handshaker is not in a fatal error state.
+ The caller is responsible for destructing the peer. */
+tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer);
+
+/* TO BE DEPRECATED SOON. Use tsi_handshaker_result_create_frame_protector
+ instead.
+ This method creates a tsi_frame_protector object after the handshake phase
+ is done. After this method has been called successfully, the only method
+ that can be called on this object is Destroy.
+ - max_output_protected_frame_size is an input/output parameter specifying the
+ desired max output protected frame size as input and outputing the actual
+ max output frame size as the output. Passing NULL is OK and will result in
+ the implementation choosing the default maximum protected frame size. Note
+ that this size only applies to outgoing frames (generated with
+ tsi_frame_protector_protect) and not incoming frames (input of
+ tsi_frame_protector_unprotect).
+ - protector is an output parameter pointing to the newly created
+ tsi_frame_protector object.
+ This method may return TSI_FAILED_PRECONDITION if
+ tsi_handshaker_is_in_progress returns 1, it returns TSI_OK otherwise assuming
+ the handshaker is not in a fatal error state.
+ The caller is responsible for destroying the protector. */
+tsi_result tsi_handshaker_create_frame_protector(
+ tsi_handshaker* self, size_t* max_output_protected_frame_size,
+ tsi_frame_protector** protector);
+
+/* Callback function definition for tsi_handshaker_next.
+ - status indicates the status of the next operation.
+ - user_data is the argument to callback function passed from the caller.
+ - bytes_to_send is the data buffer to be sent to the peer.
+ - bytes_to_send_size is the size of data buffer to be sent to the peer.
+ - handshaker_result is the result of handshake when the handshake completes,
+ is NULL otherwise. */
+typedef void (*tsi_handshaker_on_next_done_cb)(
+ tsi_result status, void* user_data, const unsigned char* bytes_to_send,
+ size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result);
+
+/* Conduct a next step of the handshake.
+ - received_bytes is the buffer containing the data received from the peer.
+ - received_bytes_size is the size of the data received from the peer.
+ - bytes_to_send is the data buffer to be sent to the peer.
+ - bytes_to_send_size is the size of data buffer to be sent to the peer.
+ - handshaker_result is the result of handshake if the handshake completes.
+ - cb is the callback function defined above. It can be NULL for synchronous
+ TSI handshaker implementation.
+ - user_data is the argument to callback function passed from the caller.
+ This method returns TSI_ASYNC if the TSI handshaker implementation is
+ asynchronous, and in this case, the callback is guaranteed to run in another
+ thread owned by TSI. It returns TSI_OK if the handshake completes or if
+ there are data to send to the peer, otherwise returns TSI_INCOMPLETE_DATA
+ which indicates that this method needs to be called again with more data
+ from the peer. In case of a fatal error in the handshake, another specific
+ error code is returned.
+ The caller is responsible for destroying the handshaker_result. However,
+ the caller should not free bytes_to_send, as the buffer is owned by the
+ tsi_handshaker object. */
+tsi_result tsi_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);
+
/* This method shuts down a TSI handshake that is in progress.
*
* This method will be invoked when TSI handshake should be terminated before
@@ -467,15 +467,15 @@ tsi_result tsi_handshaker_next(
*/
void tsi_handshaker_shutdown(tsi_handshaker* self);
-/* This method releases the tsi_handshaker object. After this method is called,
- no other method can be called on the object. */
-void tsi_handshaker_destroy(tsi_handshaker* self);
-
-/* This method initializes the necessary shared objects used for tsi
- implementation. */
-void tsi_init();
-
-/* This method destroys the shared objects created by tsi_init. */
-void tsi_destroy();
-
-#endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_INTERFACE_H */
+/* This method releases the tsi_handshaker object. After this method is called,
+ no other method can be called on the object. */
+void tsi_handshaker_destroy(tsi_handshaker* self);
+
+/* This method initializes the necessary shared objects used for tsi
+ implementation. */
+void tsi_init();
+
+/* This method destroys the shared objects created by tsi_init. */
+void tsi_destroy();
+
+#endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_INTERFACE_H */
diff --git a/contrib/libs/grpc/src/cpp/README.md b/contrib/libs/grpc/src/cpp/README.md
index 967a0a43b7f..a077a639969 100755
--- a/contrib/libs/grpc/src/cpp/README.md
+++ b/contrib/libs/grpc/src/cpp/README.md
@@ -163,7 +163,7 @@ You can find out how to build and run our simplest gRPC C++ example in our
[C++ quick start](../../examples/cpp).
For more detailed documentation on using gRPC in C++ , see our main
-documentation site at [grpc.io](https://grpc.io), specifically:
+documentation site at [grpc.io](https://grpc.io), specifically:
* [Overview](https://grpc.io/docs): An introduction to gRPC with a simple
Hello World example in all our supported languages, including C++.
diff --git a/contrib/libs/grpc/src/cpp/client/channel_cc.cc b/contrib/libs/grpc/src/cpp/client/channel_cc.cc
index ac95c29efcd..03374b11f9f 100644
--- a/contrib/libs/grpc/src/cpp/client/channel_cc.cc
+++ b/contrib/libs/grpc/src/cpp/client/channel_cc.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/channel.h>
#include <cstring>
#include <memory>
@@ -25,20 +25,20 @@
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/completion_queue.h>
-#include <grpcpp/impl/call.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+#include <grpcpp/client_context.h>
+#include <grpcpp/completion_queue.h>
+#include <grpcpp/impl/call.h>
#include <grpcpp/impl/codegen/call_op_set.h>
-#include <grpcpp/impl/codegen/completion_queue_tag.h>
-#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/impl/rpc_method.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/support/channel_arguments.h>
-#include <grpcpp/support/config.h>
-#include <grpcpp/support/status.h>
-#include "src/core/lib/gpr/string.h"
+#include <grpcpp/impl/codegen/completion_queue_tag.h>
+#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/impl/rpc_method.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/support/channel_arguments.h>
+#include <grpcpp/support/config.h>
+#include <grpcpp/support/status.h>
+#include "src/core/lib/gpr/string.h"
#include "src/core/lib/surface/completion_queue.h"
namespace grpc {
@@ -69,11 +69,11 @@ inline grpc_slice SliceFromArray(const char* arr, size_t len) {
TString GetChannelInfoField(grpc_channel* channel,
grpc_channel_info* channel_info,
char*** channel_info_field) {
- char* value = nullptr;
+ char* value = nullptr;
memset(channel_info, 0, sizeof(*channel_info));
*channel_info_field = &value;
grpc_channel_get_info(channel, channel_info);
- if (value == nullptr) return "";
+ if (value == nullptr) return "";
TString result = value;
gpr_free(value);
return result;
@@ -105,7 +105,7 @@ void ChannelResetConnectionBackoff(Channel* channel) {
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;
+ grpc_call* c_call = nullptr;
if (kRegistered) {
c_call = grpc_channel_create_registered_call(
c_channel_, context->propagate_from_call_,
@@ -120,19 +120,19 @@ void ChannelResetConnectionBackoff(Channel* channel) {
}
grpc_slice method_slice =
SliceFromArray(method.name(), strlen(method.name()));
- grpc_slice host_slice;
- if (host_str != nullptr) {
+ grpc_slice host_slice;
+ if (host_str != nullptr) {
host_slice = ::grpc::SliceFromCopiedString(*host_str);
- }
- c_call = grpc_channel_create_call(
- c_channel_, context->propagate_from_call_,
- context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
- host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
- nullptr);
- grpc_slice_unref(method_slice);
- if (host_str != nullptr) {
- grpc_slice_unref(host_slice);
- }
+ }
+ c_call = grpc_channel_create_call(
+ c_channel_, context->propagate_from_call_,
+ context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
+ host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
+ nullptr);
+ grpc_slice_unref(method_slice);
+ if (host_str != nullptr) {
+ grpc_slice_unref(host_slice);
+ }
}
grpc_census_call_set_context(c_call, context->census_context());
@@ -161,7 +161,7 @@ void Channel::PerformOpsOnCall(::grpc::internal::CallOpSetInterface* ops,
void* Channel::RegisterMethod(const char* method) {
return grpc_channel_register_call(
- c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
+ c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr);
}
grpc_connectivity_state Channel::GetState(bool try_to_connect) {
@@ -169,7 +169,7 @@ grpc_connectivity_state Channel::GetState(bool try_to_connect) {
}
namespace {
-
+
class TagSaver final : public ::grpc::internal::CompletionQueueTag {
public:
explicit TagSaver(void* tag) : tag_(tag) {}
@@ -198,10 +198,10 @@ bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) {
::grpc::CompletionQueue cq;
bool ok = false;
- void* tag = nullptr;
- NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
+ void* tag = nullptr;
+ NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr);
cq.Next(&tag, &ok);
- GPR_ASSERT(tag == nullptr);
+ GPR_ASSERT(tag == nullptr);
return ok;
}
diff --git a/contrib/libs/grpc/src/cpp/client/client_context.cc b/contrib/libs/grpc/src/cpp/client/client_context.cc
index b75343d0895..67f4168617e 100644
--- a/contrib/libs/grpc/src/cpp/client/client_context.cc
+++ b/contrib/libs/grpc/src/cpp/client/client_context.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/client_context.h>
+#include <grpcpp/client_context.h>
#include <grpc/compression.h>
#include <grpc/grpc.h>
@@ -26,10 +26,10 @@
#include <grpcpp/impl/codegen/interceptor_common.h>
#include <grpcpp/impl/codegen/sync.h>
-#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/time.h>
+#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/security/credentials.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/time.h>
namespace grpc {
@@ -59,15 +59,15 @@ ClientContext::ClientContext()
call_canceled_(false),
deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)),
census_context_(nullptr),
- propagate_from_call_(nullptr),
+ propagate_from_call_(nullptr),
compression_algorithm_(GRPC_COMPRESS_NONE),
- initial_metadata_corked_(false) {
+ initial_metadata_corked_(false) {
g_client_callbacks->DefaultConstructor(this);
}
ClientContext::~ClientContext() {
if (call_) {
- grpc_call_unref(call_);
+ grpc_call_unref(call_);
}
g_client_callbacks->Destructor(this);
}
@@ -132,8 +132,8 @@ void ClientContext::set_call(grpc_call* call,
void ClientContext::set_compression_algorithm(
grpc_compression_algorithm algorithm) {
- compression_algorithm_ = algorithm;
- const char* algorithm_name = nullptr;
+ compression_algorithm_ = algorithm;
+ const char* algorithm_name = nullptr;
if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) {
gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.",
algorithm);
@@ -172,7 +172,7 @@ TString ClientContext::peer() const {
void ClientContext::SetGlobalCallbacks(GlobalCallbacks* client_callbacks) {
GPR_ASSERT(g_client_callbacks == g_default_client_callbacks);
- GPR_ASSERT(client_callbacks != nullptr);
+ GPR_ASSERT(client_callbacks != nullptr);
GPR_ASSERT(client_callbacks != g_default_client_callbacks);
g_client_callbacks = client_callbacks;
}
diff --git a/contrib/libs/grpc/src/cpp/client/create_channel.cc b/contrib/libs/grpc/src/cpp/client/create_channel.cc
index 97327490ed2..f8ec80c09e0 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel.cc
+++ b/contrib/libs/grpc/src/cpp/client/create_channel.cc
@@ -1,28 +1,28 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/create_channel.h>
-#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/create_channel.h>
+#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/security/credentials.h>
-#include <grpcpp/support/channel_arguments.h>
+#include <grpcpp/support/channel_arguments.h>
#include "src/cpp/client/create_channel_internal.h"
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 da2a878a227..f1a89d86c62 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc
+++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc
@@ -1,24 +1,24 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/channel.h>
struct grpc_channel;
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 09d4e56b023..9224b4ceac8 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.h
+++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -23,7 +23,7 @@
#include <grpcpp/channel.h>
#include <grpcpp/impl/codegen/client_interceptor.h>
-#include <grpcpp/support/config.h>
+#include <grpcpp/support/config.h>
struct grpc_channel;
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 db09eda8a66..d58410df8dd 100644
--- a/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc
+++ b/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc
@@ -1,25 +1,25 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/grpc_posix.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/support/channel_arguments.h>
#include "src/cpp/client/create_channel_internal.h"
diff --git a/contrib/libs/grpc/src/cpp/client/credentials_cc.cc b/contrib/libs/grpc/src/cpp/client/credentials_cc.cc
index 9dfb2f491ca..9847edd3420 100644
--- a/contrib/libs/grpc/src/cpp/client/credentials_cc.cc
+++ b/contrib/libs/grpc/src/cpp/client/credentials_cc.cc
@@ -1,23 +1,23 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/grpc_library.h>
-#include <grpcpp/security/credentials.h>
+#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/security/credentials.h>
namespace grpc {
diff --git a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc
index e5bafff70af..b8e122d6ba0 100644
--- a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc
@@ -1,27 +1,27 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/security/credentials.h>
+#include <grpcpp/security/credentials.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/support/channel_arguments.h>
-#include <grpcpp/support/config.h>
+#include <grpcpp/channel.h>
+#include <grpcpp/support/channel_arguments.h>
+#include <grpcpp/support/config.h>
#include "src/cpp/client/create_channel_internal.h"
namespace grpc {
diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc
index 0f6db3caa53..830ae02c48c 100644
--- a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -22,11 +22,11 @@
#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 <grpc/support/string_util.h>
+#include <grpcpp/channel.h>
#include <grpcpp/impl/codegen/status.h>
-#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/support/channel_arguments.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"
@@ -82,16 +82,16 @@ bool SecureCallCredentials::ApplyToCall(grpc_call* call) {
namespace {
std::shared_ptr<ChannelCredentials> WrapChannelCredentials(
grpc_channel_credentials* creds) {
- return creds == nullptr ? nullptr
- : std::shared_ptr<ChannelCredentials>(
- new SecureChannelCredentials(creds));
+ return creds == nullptr ? nullptr
+ : std::shared_ptr<ChannelCredentials>(
+ new SecureChannelCredentials(creds));
}
std::shared_ptr<CallCredentials> WrapCallCredentials(
grpc_call_credentials* creds) {
- return creds == nullptr ? nullptr
- : std::shared_ptr<CallCredentials>(
- new SecureCallCredentials(creds));
+ return creds == nullptr ? nullptr
+ : std::shared_ptr<CallCredentials>(
+ new SecureCallCredentials(creds));
}
} // namespace
@@ -115,8 +115,8 @@ std::shared_ptr<ChannelCredentials> SslCredentials(
return WrapChannelCredentials(c_creds);
}
-namespace experimental {
-
+namespace experimental {
+
namespace {
void ClearStsCredentialsOptions(StsCredentialsOptions* options) {
@@ -265,21 +265,21 @@ std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
c_plugin, min_security_level, nullptr));
}
-// Builds ALTS Credentials given ALTS specific options
-std::shared_ptr<ChannelCredentials> AltsCredentials(
- const AltsCredentialsOptions& options) {
+// Builds ALTS Credentials given ALTS specific options
+std::shared_ptr<ChannelCredentials> AltsCredentials(
+ const AltsCredentialsOptions& options) {
grpc::GrpcLibraryCodegen init; // To call grpc_init().
- grpc_alts_credentials_options* c_options =
- grpc_alts_credentials_client_options_create();
+ grpc_alts_credentials_options* c_options =
+ grpc_alts_credentials_client_options_create();
for (const auto& service_account : options.target_service_accounts) {
- grpc_alts_credentials_client_options_add_target_service_account(
+ grpc_alts_credentials_client_options_add_target_service_account(
c_options, service_account.c_str());
- }
- grpc_channel_credentials* c_creds = grpc_alts_credentials_create(c_options);
- grpc_alts_credentials_options_destroy(c_options);
- return WrapChannelCredentials(c_creds);
-}
-
+ }
+ grpc_channel_credentials* c_creds = grpc_alts_credentials_create(c_options);
+ grpc_alts_credentials_options_destroy(c_options);
+ return WrapChannelCredentials(c_creds);
+}
+
// Builds Local Credentials
std::shared_ptr<ChannelCredentials> LocalCredentials(
grpc_local_connect_type type) {
@@ -294,8 +294,8 @@ std::shared_ptr<ChannelCredentials> TlsCredentials(
grpc_tls_credentials_create(options.c_credentials_options()));
}
-} // namespace experimental
-
+} // namespace experimental
+
// Builds credentials for use when running in GCE
std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
grpc::GrpcLibraryCodegen init; // To call grpc_init().
@@ -362,18 +362,18 @@ std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
return nullptr;
}
-std::shared_ptr<CallCredentials> CompositeCallCredentials(
- const std::shared_ptr<CallCredentials>& creds1,
- const std::shared_ptr<CallCredentials>& creds2) {
- SecureCallCredentials* s_creds1 = creds1->AsSecureCredentials();
- SecureCallCredentials* s_creds2 = creds2->AsSecureCredentials();
- if (s_creds1 != nullptr && s_creds2 != nullptr) {
- return WrapCallCredentials(grpc_composite_call_credentials_create(
- s_creds1->GetRawCreds(), s_creds2->GetRawCreds(), nullptr));
- }
- return nullptr;
-}
-
+std::shared_ptr<CallCredentials> CompositeCallCredentials(
+ const std::shared_ptr<CallCredentials>& creds1,
+ const std::shared_ptr<CallCredentials>& creds2) {
+ SecureCallCredentials* s_creds1 = creds1->AsSecureCredentials();
+ SecureCallCredentials* s_creds2 = creds2->AsSecureCredentials();
+ if (s_creds1 != nullptr && s_creds2 != nullptr) {
+ return WrapCallCredentials(grpc_composite_call_credentials_create(
+ s_creds1->GetRawCreds(), s_creds2->GetRawCreds(), nullptr));
+ }
+ return nullptr;
+}
+
std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
std::unique_ptr<MetadataCredentialsPlugin> plugin) {
grpc::GrpcLibraryCodegen init; // To call grpc_init().
@@ -391,7 +391,7 @@ std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
namespace {
void DeleteWrapper(void* wrapper, grpc_error* /*ignored*/) {
MetadataCredentialsPluginWrapper* w =
- static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
+ static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
delete w;
}
} // namespace
@@ -411,19 +411,19 @@ void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) {
GRPC_ERROR_NONE);
}
-int MetadataCredentialsPluginWrapper::GetMetadata(
+int MetadataCredentialsPluginWrapper::GetMetadata(
void* wrapper, grpc_auth_metadata_context context,
- grpc_credentials_plugin_metadata_cb cb, void* user_data,
- grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
- size_t* num_creds_md, grpc_status_code* status,
- const char** error_details) {
+ 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) {
GPR_ASSERT(wrapper);
MetadataCredentialsPluginWrapper* w =
- static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
+ static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
if (!w->plugin_) {
- *num_creds_md = 0;
- *status = GRPC_STATUS_OK;
- *error_details = nullptr;
+ *num_creds_md = 0;
+ *status = GRPC_STATUS_OK;
+ *error_details = nullptr;
return 1;
}
if (w->plugin_->IsBlocking()) {
@@ -431,36 +431,36 @@ int MetadataCredentialsPluginWrapper::GetMetadata(
// 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.
+ // Asynchronous return.
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);
});
- return 0;
+ return 0;
} else {
- // Synchronous return.
- w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
- error_details);
- return 1;
+ // Synchronous return.
+ w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
+ error_details);
+ return 1;
}
}
-namespace {
-
-void UnrefMetadata(const std::vector<grpc_metadata>& md) {
+namespace {
+
+void UnrefMetadata(const std::vector<grpc_metadata>& md) {
for (const auto& metadatum : md) {
grpc_slice_unref(metadatum.key);
grpc_slice_unref(metadatum.value);
- }
-}
-
-} // namespace
-
+ }
+}
+
+} // namespace
+
void MetadataCredentialsPluginWrapper::InvokePlugin(
grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb,
- void* user_data, grpc_metadata creds_md[4], size_t* num_creds_md,
- grpc_status_code* status_code, const char** error_details) {
+ void* user_data, grpc_metadata creds_md[4], size_t* num_creds_md,
+ grpc_status_code* status_code, const char** error_details) {
std::multimap<TString, TString> metadata;
// const_cast is safe since the SecureAuthContext only inc/dec the refcount
@@ -478,32 +478,32 @@ void MetadataCredentialsPluginWrapper::InvokePlugin(
md_entry.flags = 0;
md.push_back(md_entry);
}
- if (creds_md != nullptr) {
- // Synchronous return.
- if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
- *num_creds_md = 0;
- *status_code = GRPC_STATUS_INTERNAL;
- *error_details = gpr_strdup(
- "blocking plugin credentials returned too many metadata keys");
- UnrefMetadata(md);
- } else {
- for (const auto& elem : md) {
- creds_md[*num_creds_md].key = elem.key;
- creds_md[*num_creds_md].value = elem.value;
- creds_md[*num_creds_md].flags = elem.flags;
- ++(*num_creds_md);
- }
- *status_code = static_cast<grpc_status_code>(status.error_code());
- *error_details =
- status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
- }
- } else {
- // Asynchronous return.
- cb(user_data, md.empty() ? nullptr : &md[0], md.size(),
- static_cast<grpc_status_code>(status.error_code()),
- status.error_message().c_str());
- UnrefMetadata(md);
- }
+ if (creds_md != nullptr) {
+ // Synchronous return.
+ if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
+ *num_creds_md = 0;
+ *status_code = GRPC_STATUS_INTERNAL;
+ *error_details = gpr_strdup(
+ "blocking plugin credentials returned too many metadata keys");
+ UnrefMetadata(md);
+ } else {
+ for (const auto& elem : md) {
+ creds_md[*num_creds_md].key = elem.key;
+ creds_md[*num_creds_md].value = elem.value;
+ creds_md[*num_creds_md].flags = elem.flags;
+ ++(*num_creds_md);
+ }
+ *status_code = static_cast<grpc_status_code>(status.error_code());
+ *error_details =
+ status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
+ }
+ } else {
+ // Asynchronous return.
+ cb(user_data, md.empty() ? nullptr : &md[0], md.size(),
+ static_cast<grpc_status_code>(status.error_code()),
+ status.error_message().c_str());
+ UnrefMetadata(md);
+ }
}
MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper(
diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.h b/contrib/libs/grpc/src/cpp/client/secure_credentials.h
index 4fc79346bf4..4d4ac5bce88 100644
--- a/contrib/libs/grpc/src/cpp/client/secure_credentials.h
+++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,9 +21,9 @@
#include <grpc/grpc_security.h>
-#include <grpcpp/security/credentials.h>
+#include <grpcpp/security/credentials.h>
#include <grpcpp/security/tls_credentials_options.h>
-#include <grpcpp/support/config.h>
+#include <grpcpp/support/config.h>
#include "y_absl/strings/str_cat.h"
#include "src/core/lib/security/credentials/credentials.h"
@@ -84,27 +84,27 @@ grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
} // namespace experimental
-class MetadataCredentialsPluginWrapper final : private GrpcLibraryCodegen {
+class MetadataCredentialsPluginWrapper final : private GrpcLibraryCodegen {
public:
static void Destroy(void* wrapper);
- static int GetMetadata(
- void* wrapper, grpc_auth_metadata_context context,
- grpc_credentials_plugin_metadata_cb cb, void* user_data,
- grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
- size_t* num_creds_md, grpc_status_code* status,
- const char** error_details);
+ static int GetMetadata(
+ void* wrapper, grpc_auth_metadata_context context,
+ grpc_credentials_plugin_metadata_cb cb, void* user_data,
+ grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
+ size_t* num_creds_md, grpc_status_code* status,
+ const char** error_details);
static char* DebugString(void* wrapper);
explicit MetadataCredentialsPluginWrapper(
std::unique_ptr<MetadataCredentialsPlugin> plugin);
private:
- void InvokePlugin(
- grpc_auth_metadata_context context,
- grpc_credentials_plugin_metadata_cb cb, void* user_data,
- grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
- size_t* num_creds_md, grpc_status_code* status_code,
- const char** error_details);
+ void InvokePlugin(
+ grpc_auth_metadata_context context,
+ grpc_credentials_plugin_metadata_cb cb, void* user_data,
+ grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
+ size_t* num_creds_md, grpc_status_code* status_code,
+ const char** error_details);
std::unique_ptr<ThreadPoolInterface> thread_pool_;
std::unique_ptr<MetadataCredentialsPlugin> plugin_;
};
diff --git a/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc b/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc
index e1e47cbb17b..fc32fa7748e 100644
--- a/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc
+++ b/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc
@@ -1,23 +1,23 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/core_codegen_interface.h>
-#include <grpcpp/impl/codegen/grpc_library.h>
+#include <grpcpp/impl/codegen/core_codegen_interface.h>
+#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
diff --git a/contrib/libs/grpc/src/cpp/common/alarm.cc b/contrib/libs/grpc/src/cpp/common/alarm.cc
index a2612874b20..addd1e80377 100644
--- a/contrib/libs/grpc/src/cpp/common/alarm.cc
+++ b/contrib/libs/grpc/src/cpp/common/alarm.cc
@@ -1,45 +1,45 @@
-/*
- * 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/alarm.h>
-
-#include <memory>
-
-#include <grpc/support/log.h>
-#include <grpc/support/port_platform.h>
-#include <grpcpp/completion_queue.h>
-#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/support/time.h>
-#include "src/core/lib/iomgr/exec_ctx.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/alarm.h>
+
+#include <memory>
+
+#include <grpc/support/log.h>
+#include <grpc/support/port_platform.h>
+#include <grpcpp/completion_queue.h>
+#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/support/time.h>
+#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/executor.h"
-#include "src/core/lib/iomgr/timer.h"
-#include "src/core/lib/surface/completion_queue.h"
-
-#include <grpc/support/log.h>
-#include "src/core/lib/debug/trace.h"
-
+#include "src/core/lib/iomgr/timer.h"
+#include "src/core/lib/surface/completion_queue.h"
+
+#include <grpc/support/log.h>
+#include "src/core/lib/debug/trace.h"
+
namespace grpc {
-
-namespace internal {
+
+namespace internal {
class AlarmImpl : public ::grpc::internal::CompletionQueueTag {
- public:
- AlarmImpl() : cq_(nullptr), tag_(nullptr) {
- gpr_ref_init(&refs_, 1);
- grpc_timer_init_unset(&timer_);
+ public:
+ AlarmImpl() : cq_(nullptr), tag_(nullptr) {
+ gpr_ref_init(&refs_, 1);
+ grpc_timer_init_unset(&timer_);
}
~AlarmImpl() {}
bool FinalizeResult(void** tag, bool* /*status*/) override {
@@ -73,10 +73,10 @@ class AlarmImpl : public ::grpc::internal::CompletionQueueTag {
this, grpc_schedule_on_exec_ctx);
grpc_timer_init(&timer_, grpc_timespec_to_millis_round_up(deadline),
&on_alarm_);
- }
+ }
void Set(gpr_timespec deadline, std::function<void(bool)> f) {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
// Don't use any CQ at all. Instead just use the timer to fire the function
callback_ = std::move(f);
Ref();
@@ -94,54 +94,54 @@ class AlarmImpl : public ::grpc::internal::CompletionQueueTag {
error);
},
this, grpc_schedule_on_exec_ctx);
- grpc_timer_init(&timer_, grpc_timespec_to_millis_round_up(deadline),
- &on_alarm_);
- }
- void Cancel() {
+ grpc_timer_init(&timer_, grpc_timespec_to_millis_round_up(deadline),
+ &on_alarm_);
+ }
+ void Cancel() {
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
- grpc_core::ExecCtx exec_ctx;
- grpc_timer_cancel(&timer_);
- }
- void Destroy() {
- Cancel();
- Unref();
- }
-
- private:
- void Ref() { gpr_ref(&refs_); }
- void Unref() {
- if (gpr_unref(&refs_)) {
- delete this;
- }
- }
-
- grpc_timer timer_;
- gpr_refcount refs_;
- grpc_closure on_alarm_;
- grpc_cq_completion completion_;
- // completion queue where events about this alarm will be posted
- grpc_completion_queue* cq_;
- void* tag_;
+ grpc_core::ExecCtx exec_ctx;
+ grpc_timer_cancel(&timer_);
+ }
+ void Destroy() {
+ Cancel();
+ Unref();
+ }
+
+ private:
+ void Ref() { gpr_ref(&refs_); }
+ void Unref() {
+ if (gpr_unref(&refs_)) {
+ delete this;
+ }
+ }
+
+ grpc_timer timer_;
+ gpr_refcount refs_;
+ grpc_closure on_alarm_;
+ grpc_cq_completion completion_;
+ // completion queue where events about this alarm will be posted
+ grpc_completion_queue* cq_;
+ void* tag_;
std::function<void(bool)> callback_;
-};
-} // namespace internal
-
+};
+} // namespace internal
+
static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer;
-
-Alarm::Alarm() : alarm_(new internal::AlarmImpl()) {
- g_gli_initializer.summon();
-}
-
+
+Alarm::Alarm() : alarm_(new internal::AlarmImpl()) {
+ g_gli_initializer.summon();
+}
+
void Alarm::SetInternal(::grpc::CompletionQueue* cq, gpr_timespec deadline,
void* tag) {
- // Note that we know that alarm_ is actually an internal::AlarmImpl
- // but we declared it as the base pointer to avoid a forward declaration
- // or exposing core data structures in the C++ public headers.
- // Thus it is safe to use a static_cast to the subclass here, and the
- // C++ style guide allows us to do so in this case
- static_cast<internal::AlarmImpl*>(alarm_)->Set(cq, deadline, tag);
-}
-
+ // Note that we know that alarm_ is actually an internal::AlarmImpl
+ // but we declared it as the base pointer to avoid a forward declaration
+ // or exposing core data structures in the C++ public headers.
+ // Thus it is safe to use a static_cast to the subclass here, and the
+ // C++ style guide allows us to do so in this case
+ static_cast<internal::AlarmImpl*>(alarm_)->Set(cq, deadline, tag);
+}
+
void Alarm::SetInternal(gpr_timespec deadline, std::function<void(bool)> f) {
// Note that we know that alarm_ is actually an internal::AlarmImpl
// but we declared it as the base pointer to avoid a forward declaration
@@ -151,11 +151,11 @@ void Alarm::SetInternal(gpr_timespec deadline, std::function<void(bool)> f) {
static_cast<internal::AlarmImpl*>(alarm_)->Set(deadline, std::move(f));
}
-Alarm::~Alarm() {
- if (alarm_ != nullptr) {
- static_cast<internal::AlarmImpl*>(alarm_)->Destroy();
- }
-}
-
-void Alarm::Cancel() { static_cast<internal::AlarmImpl*>(alarm_)->Cancel(); }
+Alarm::~Alarm() {
+ if (alarm_ != nullptr) {
+ static_cast<internal::AlarmImpl*>(alarm_)->Destroy();
+ }
+}
+
+void Alarm::Cancel() { static_cast<internal::AlarmImpl*>(alarm_)->Cancel(); }
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc b/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc
index fbb18e9915c..eb088fa9d96 100644
--- a/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc
+++ b/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/security/auth_context.h>
+#include <grpcpp/security/auth_context.h>
#include <grpc/grpc_security.h>
diff --git a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc
index 5a5dd91b5ec..8b8d4f688f5 100644
--- a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc
+++ b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc
@@ -1,32 +1,32 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/support/channel_arguments.h>
+#include <grpcpp/support/channel_arguments.h>
#include <sstream>
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/log.h>
-#include <grpcpp/grpcpp.h>
-#include <grpcpp/resource_quota.h>
+#include <grpcpp/grpcpp.h>
+#include <grpcpp/resource_quota.h>
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/socket_mutator.h"
-
+
namespace grpc {
ChannelArguments::ChannelArguments() {
@@ -66,7 +66,7 @@ ChannelArguments::ChannelArguments(const ChannelArguments& other)
}
ChannelArguments::~ChannelArguments() {
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
for (auto& arg : args_) {
if (arg.type == GRPC_ARG_POINTER) {
arg.value.pointer.vtable->destroy(arg.value.pointer.p);
@@ -84,27 +84,27 @@ void ChannelArguments::SetCompressionAlgorithm(
SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, algorithm);
}
-void ChannelArguments::SetGrpclbFallbackTimeout(int fallback_timeout) {
- SetInt(GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS, fallback_timeout);
-}
-
+void ChannelArguments::SetGrpclbFallbackTimeout(int fallback_timeout) {
+ SetInt(GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS, fallback_timeout);
+}
+
void ChannelArguments::SetSocketMutator(grpc_socket_mutator* mutator) {
if (!mutator) {
return;
}
grpc_arg mutator_arg = grpc_socket_mutator_to_arg(mutator);
bool replaced = false;
- grpc_core::ExecCtx exec_ctx;
+ grpc_core::ExecCtx exec_ctx;
for (auto& arg : args_) {
if (arg.type == mutator_arg.type &&
TString(arg.key) == TString(mutator_arg.key)) {
- GPR_ASSERT(!replaced);
+ GPR_ASSERT(!replaced);
arg.value.pointer.vtable->destroy(arg.value.pointer.p);
arg.value.pointer = mutator_arg.value.pointer;
replaced = true;
}
}
-
+
if (!replaced) {
strings_.push_back(TString(mutator_arg.key));
args_.push_back(mutator_arg);
@@ -122,18 +122,18 @@ void ChannelArguments::SetUserAgentPrefix(
return;
}
bool replaced = false;
- auto strings_it = strings_.begin();
+ auto strings_it = strings_.begin();
for (auto& arg : args_) {
- ++strings_it;
- if (arg.type == GRPC_ARG_STRING) {
+ ++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;
+ 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());
- replaced = true;
- break;
- }
- ++strings_it;
+ replaced = true;
+ break;
+ }
+ ++strings_it;
}
}
if (!replaced) {
diff --git a/contrib/libs/grpc/src/cpp/common/channel_filter.cc b/contrib/libs/grpc/src/cpp/common/channel_filter.cc
index 8df6c7b98f5..b0cc1aa6c35 100644
--- a/contrib/libs/grpc/src/cpp/common/channel_filter.cc
+++ b/contrib/libs/grpc/src/cpp/common/channel_filter.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,44 +21,44 @@
#include "src/core/lib/channel/channel_stack.h"
#include "src/cpp/common/channel_filter.h"
-#include <grpcpp/impl/codegen/slice.h>
-
+#include <grpcpp/impl/codegen/slice.h>
+
namespace grpc {
// MetadataBatch
-grpc_linked_mdelem* MetadataBatch::AddMetadata(const string& key,
- const string& value) {
- grpc_linked_mdelem* storage = new grpc_linked_mdelem;
- storage->md = grpc_mdelem_from_slices(SliceFromCopiedString(key),
- SliceFromCopiedString(value));
- GRPC_LOG_IF_ERROR("MetadataBatch::AddMetadata",
- grpc_metadata_batch_link_head(batch_, storage));
+grpc_linked_mdelem* MetadataBatch::AddMetadata(const string& key,
+ const string& value) {
+ grpc_linked_mdelem* storage = new grpc_linked_mdelem;
+ storage->md = grpc_mdelem_from_slices(SliceFromCopiedString(key),
+ SliceFromCopiedString(value));
+ GRPC_LOG_IF_ERROR("MetadataBatch::AddMetadata",
+ grpc_metadata_batch_link_head(batch_, storage));
return storage;
}
// ChannelData
-void ChannelData::StartTransportOp(grpc_channel_element* elem,
- TransportOp* op) {
- grpc_channel_next_op(elem, op->op());
+void ChannelData::StartTransportOp(grpc_channel_element* elem,
+ TransportOp* op) {
+ grpc_channel_next_op(elem, op->op());
}
-void ChannelData::GetInfo(grpc_channel_element* elem,
- const grpc_channel_info* channel_info) {
- grpc_channel_next_get_info(elem, channel_info);
+void ChannelData::GetInfo(grpc_channel_element* elem,
+ const grpc_channel_info* channel_info) {
+ grpc_channel_next_get_info(elem, channel_info);
}
// CallData
-void CallData::StartTransportStreamOpBatch(grpc_call_element* elem,
- TransportStreamOpBatch* op) {
- grpc_call_next_op(elem, op->op());
+void CallData::StartTransportStreamOpBatch(grpc_call_element* elem,
+ TransportStreamOpBatch* op) {
+ grpc_call_next_op(elem, op->op());
}
-void CallData::SetPollsetOrPollsetSet(grpc_call_element* elem,
- grpc_polling_entity* pollent) {
- grpc_call_stack_ignore_set_pollset_or_pollset_set(elem, pollent);
+void CallData::SetPollsetOrPollsetSet(grpc_call_element* elem,
+ grpc_polling_entity* pollent) {
+ grpc_call_stack_ignore_set_pollset_or_pollset_set(elem, pollent);
}
// internal code used by RegisterChannelFilter()
@@ -66,14 +66,14 @@ void CallData::SetPollsetOrPollsetSet(grpc_call_element* elem,
namespace internal {
// Note: Implicitly initialized to nullptr due to static lifetime.
-std::vector<FilterRecord>* channel_filters;
+std::vector<FilterRecord>* channel_filters;
namespace {
-bool MaybeAddFilter(grpc_channel_stack_builder* builder, void* arg) {
- const FilterRecord& filter = *static_cast<FilterRecord*>(arg);
+bool MaybeAddFilter(grpc_channel_stack_builder* builder, void* arg) {
+ const FilterRecord& filter = *static_cast<FilterRecord*>(arg);
if (filter.include_filter) {
- const grpc_channel_args* args =
+ const grpc_channel_args* args =
grpc_channel_stack_builder_get_channel_arguments(builder);
if (!filter.include_filter(*args)) return true;
}
@@ -85,9 +85,9 @@ bool MaybeAddFilter(grpc_channel_stack_builder* builder, void* arg) {
void ChannelFilterPluginInit() {
for (size_t i = 0; i < channel_filters->size(); ++i) {
- FilterRecord& filter = (*channel_filters)[i];
+ FilterRecord& filter = (*channel_filters)[i];
grpc_channel_init_register_stage(filter.stack_type, filter.priority,
- MaybeAddFilter, (void*)&filter);
+ MaybeAddFilter, (void*)&filter);
}
}
diff --git a/contrib/libs/grpc/src/cpp/common/channel_filter.h b/contrib/libs/grpc/src/cpp/common/channel_filter.h
index 5ce720b3075..9720230fc21 100644
--- a/contrib/libs/grpc/src/cpp/common/channel_filter.h
+++ b/contrib/libs/grpc/src/cpp/common/channel_filter.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,7 +21,7 @@
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
-#include <grpcpp/impl/codegen/config.h>
+#include <grpcpp/impl/codegen/config.h>
#include <functional>
#include <vector>
@@ -47,22 +47,22 @@ class MetadataBatch {
/// Borrows a pointer to \a batch, but does NOT take ownership.
/// The caller must ensure that \a batch continues to exist for as
/// long as the MetadataBatch object does.
- explicit MetadataBatch(grpc_metadata_batch* batch) : batch_(batch) {}
+ explicit MetadataBatch(grpc_metadata_batch* batch) : batch_(batch) {}
- grpc_metadata_batch* batch() const { return batch_; }
+ grpc_metadata_batch* batch() const { return batch_; }
/// Adds metadata and returns the newly allocated storage.
/// The caller takes ownership of the result, which must exist for the
/// lifetime of the gRPC call.
- grpc_linked_mdelem* AddMetadata(const string& key, const string& value);
+ grpc_linked_mdelem* AddMetadata(const string& key, const string& value);
class const_iterator : public std::iterator<std::bidirectional_iterator_tag,
const grpc_mdelem> {
public:
- const grpc_mdelem& operator*() const { return elem_->md; }
- const grpc_mdelem operator->() const { return elem_->md; }
+ const grpc_mdelem& operator*() const { return elem_->md; }
+ const grpc_mdelem operator->() const { return elem_->md; }
- const_iterator& operator++() {
+ const_iterator& operator++() {
elem_ = elem_->next;
return *this;
}
@@ -71,7 +71,7 @@ class MetadataBatch {
operator++();
return tmp;
}
- const_iterator& operator--() {
+ const_iterator& operator--() {
elem_ = elem_->prev;
return *this;
}
@@ -81,25 +81,25 @@ class MetadataBatch {
return tmp;
}
- bool operator==(const const_iterator& other) const {
+ bool operator==(const const_iterator& other) const {
return elem_ == other.elem_;
}
- bool operator!=(const const_iterator& other) const {
+ bool operator!=(const const_iterator& other) const {
return elem_ != other.elem_;
}
private:
friend class MetadataBatch;
- explicit const_iterator(grpc_linked_mdelem* elem) : elem_(elem) {}
+ explicit const_iterator(grpc_linked_mdelem* elem) : elem_(elem) {}
- grpc_linked_mdelem* elem_;
+ grpc_linked_mdelem* elem_;
};
const_iterator begin() const { return const_iterator(batch_->list.head); }
const_iterator end() const { return const_iterator(nullptr); }
private:
- grpc_metadata_batch* batch_; // Not owned.
+ grpc_metadata_batch* batch_; // Not owned.
};
/// A C++ wrapper for the \c grpc_transport_op struct.
@@ -108,103 +108,103 @@ class TransportOp {
/// Borrows a pointer to \a op, but does NOT take ownership.
/// The caller must ensure that \a op continues to exist for as
/// long as the TransportOp object does.
- explicit TransportOp(grpc_transport_op* op) : op_(op) {}
+ explicit TransportOp(grpc_transport_op* op) : op_(op) {}
- grpc_transport_op* op() const { return op_; }
+ grpc_transport_op* op() const { return op_; }
// TODO(roth): Add a C++ wrapper for grpc_error?
- grpc_error* disconnect_with_error() const {
+ grpc_error* disconnect_with_error() const {
return op_->disconnect_with_error;
}
- bool send_goaway() const { return op_->goaway_error != GRPC_ERROR_NONE; }
+ bool send_goaway() const { return op_->goaway_error != GRPC_ERROR_NONE; }
// TODO(roth): Add methods for additional fields as needed.
private:
- grpc_transport_op* op_; // Not owned.
+ grpc_transport_op* op_; // Not owned.
};
-/// A C++ wrapper for the \c grpc_transport_stream_op_batch struct.
-class TransportStreamOpBatch {
+/// A C++ wrapper for the \c grpc_transport_stream_op_batch struct.
+class TransportStreamOpBatch {
public:
/// Borrows a pointer to \a op, but does NOT take ownership.
/// The caller must ensure that \a op continues to exist for as
- /// long as the TransportStreamOpBatch object does.
- explicit TransportStreamOpBatch(grpc_transport_stream_op_batch* op)
+ /// long as the TransportStreamOpBatch object does.
+ explicit TransportStreamOpBatch(grpc_transport_stream_op_batch* op)
: op_(op),
- send_initial_metadata_(
- op->send_initial_metadata
- ? op->payload->send_initial_metadata.send_initial_metadata
- : nullptr),
- send_trailing_metadata_(
- op->send_trailing_metadata
- ? op->payload->send_trailing_metadata.send_trailing_metadata
- : nullptr),
- recv_initial_metadata_(
- op->recv_initial_metadata
- ? op->payload->recv_initial_metadata.recv_initial_metadata
- : nullptr),
- recv_trailing_metadata_(
- op->recv_trailing_metadata
- ? op->payload->recv_trailing_metadata.recv_trailing_metadata
- : nullptr) {}
-
- grpc_transport_stream_op_batch* op() const { return op_; }
-
- grpc_closure* on_complete() const { return op_->on_complete; }
- void set_on_complete(grpc_closure* closure) { op_->on_complete = closure; }
-
- MetadataBatch* send_initial_metadata() {
- return op_->send_initial_metadata ? &send_initial_metadata_ : nullptr;
+ send_initial_metadata_(
+ op->send_initial_metadata
+ ? op->payload->send_initial_metadata.send_initial_metadata
+ : nullptr),
+ send_trailing_metadata_(
+ op->send_trailing_metadata
+ ? op->payload->send_trailing_metadata.send_trailing_metadata
+ : nullptr),
+ recv_initial_metadata_(
+ op->recv_initial_metadata
+ ? op->payload->recv_initial_metadata.recv_initial_metadata
+ : nullptr),
+ recv_trailing_metadata_(
+ op->recv_trailing_metadata
+ ? op->payload->recv_trailing_metadata.recv_trailing_metadata
+ : nullptr) {}
+
+ grpc_transport_stream_op_batch* op() const { return op_; }
+
+ grpc_closure* on_complete() const { return op_->on_complete; }
+ void set_on_complete(grpc_closure* closure) { op_->on_complete = closure; }
+
+ MetadataBatch* send_initial_metadata() {
+ return op_->send_initial_metadata ? &send_initial_metadata_ : nullptr;
}
- MetadataBatch* send_trailing_metadata() {
- return op_->send_trailing_metadata ? &send_trailing_metadata_ : nullptr;
+ MetadataBatch* send_trailing_metadata() {
+ return op_->send_trailing_metadata ? &send_trailing_metadata_ : nullptr;
}
- MetadataBatch* recv_initial_metadata() {
- return op_->recv_initial_metadata ? &recv_initial_metadata_ : nullptr;
+ MetadataBatch* recv_initial_metadata() {
+ return op_->recv_initial_metadata ? &recv_initial_metadata_ : nullptr;
}
- MetadataBatch* recv_trailing_metadata() {
- return op_->recv_trailing_metadata ? &recv_trailing_metadata_ : nullptr;
+ MetadataBatch* recv_trailing_metadata() {
+ return op_->recv_trailing_metadata ? &recv_trailing_metadata_ : nullptr;
}
- uint32_t* send_initial_metadata_flags() const {
- return op_->send_initial_metadata ? &op_->payload->send_initial_metadata
- .send_initial_metadata_flags
- : nullptr;
+ uint32_t* send_initial_metadata_flags() const {
+ return op_->send_initial_metadata ? &op_->payload->send_initial_metadata
+ .send_initial_metadata_flags
+ : nullptr;
}
- grpc_closure* recv_initial_metadata_ready() const {
- return op_->recv_initial_metadata
- ? op_->payload->recv_initial_metadata.recv_initial_metadata_ready
- : nullptr;
+ grpc_closure* recv_initial_metadata_ready() const {
+ return op_->recv_initial_metadata
+ ? op_->payload->recv_initial_metadata.recv_initial_metadata_ready
+ : nullptr;
}
- void set_recv_initial_metadata_ready(grpc_closure* closure) {
- op_->payload->recv_initial_metadata.recv_initial_metadata_ready = closure;
+ void set_recv_initial_metadata_ready(grpc_closure* closure) {
+ op_->payload->recv_initial_metadata.recv_initial_metadata_ready = closure;
}
- grpc_core::OrphanablePtr<grpc_core::ByteStream>* send_message() const {
- return op_->send_message ? &op_->payload->send_message.send_message
- : nullptr;
+ grpc_core::OrphanablePtr<grpc_core::ByteStream>* send_message() const {
+ return op_->send_message ? &op_->payload->send_message.send_message
+ : nullptr;
}
- void set_send_message(
- grpc_core::OrphanablePtr<grpc_core::ByteStream> send_message) {
- op_->send_message = true;
- op_->payload->send_message.send_message = std::move(send_message);
+ void set_send_message(
+ grpc_core::OrphanablePtr<grpc_core::ByteStream> send_message) {
+ op_->send_message = true;
+ op_->payload->send_message.send_message = std::move(send_message);
+ }
+
+ grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message() const {
+ return op_->recv_message ? op_->payload->recv_message.recv_message
+ : nullptr;
}
-
- grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message() const {
- return op_->recv_message ? op_->payload->recv_message.recv_message
- : nullptr;
- }
- void set_recv_message(
- grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message) {
- op_->recv_message = true;
- op_->payload->recv_message.recv_message = recv_message;
+ void set_recv_message(
+ grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message) {
+ op_->recv_message = true;
+ op_->payload->recv_message.recv_message = recv_message;
}
- census_context* get_census_context() const {
- return static_cast<census_context*>(
- op_->payload->context[GRPC_CONTEXT_TRACING].value);
+ census_context* get_census_context() const {
+ return static_cast<census_context*>(
+ op_->payload->context[GRPC_CONTEXT_TRACING].value);
}
const gpr_atm* get_peer_string() const {
@@ -220,7 +220,7 @@ class TransportStreamOpBatch {
}
private:
- grpc_transport_stream_op_batch* op_; // Not owned.
+ grpc_transport_stream_op_batch* op_; // Not owned.
MetadataBatch send_initial_metadata_;
MetadataBatch send_trailing_metadata_;
MetadataBatch recv_initial_metadata_;
@@ -230,52 +230,52 @@ class TransportStreamOpBatch {
/// Represents channel data.
class ChannelData {
public:
- ChannelData() {}
+ ChannelData() {}
virtual ~ChannelData() {}
- // TODO(roth): Come up with a more C++-like API for the channel element.
-
- /// Initializes the channel data.
+ // 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*/) {
return GRPC_ERROR_NONE;
}
- // Called before destruction.
+ // Called before destruction.
virtual void Destroy(grpc_channel_element* /*elem*/) {}
- virtual void StartTransportOp(grpc_channel_element* elem, TransportOp* op);
+ virtual void StartTransportOp(grpc_channel_element* elem, TransportOp* op);
- virtual void GetInfo(grpc_channel_element* elem,
- const grpc_channel_info* channel_info);
+ virtual void GetInfo(grpc_channel_element* elem,
+ const grpc_channel_info* channel_info);
};
/// Represents call data.
class CallData {
public:
- CallData() {}
+ CallData() {}
virtual ~CallData() {}
- // TODO(roth): Come up with a more C++-like API for the call element.
-
+ // 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*/) {
return GRPC_ERROR_NONE;
}
- // Called before destruction.
+ // Called before destruction.
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,
- TransportStreamOpBatch* op);
+ virtual void StartTransportStreamOpBatch(grpc_call_element* elem,
+ TransportStreamOpBatch* op);
/// Sets a pollset or pollset set.
- virtual void SetPollsetOrPollsetSet(grpc_call_element* elem,
- grpc_polling_entity* pollent);
+ virtual void SetPollsetOrPollsetSet(grpc_call_element* elem,
+ grpc_polling_entity* pollent);
};
namespace internal {
@@ -288,73 +288,73 @@ class ChannelFilter final {
public:
static const size_t channel_data_size = sizeof(ChannelDataType);
- static grpc_error* InitChannelElement(grpc_channel_element* elem,
- grpc_channel_element_args* args) {
- // Construct the object in the already-allocated memory.
- ChannelDataType* channel_data = new (elem->channel_data) ChannelDataType();
- return channel_data->Init(elem, args);
+ static grpc_error* InitChannelElement(grpc_channel_element* elem,
+ grpc_channel_element_args* args) {
+ // Construct the object in the already-allocated memory.
+ ChannelDataType* channel_data = new (elem->channel_data) ChannelDataType();
+ return channel_data->Init(elem, args);
}
- static void DestroyChannelElement(grpc_channel_element* elem) {
- ChannelDataType* channel_data =
- static_cast<ChannelDataType*>(elem->channel_data);
- channel_data->Destroy(elem);
- channel_data->~ChannelDataType();
+ static void DestroyChannelElement(grpc_channel_element* elem) {
+ ChannelDataType* channel_data =
+ static_cast<ChannelDataType*>(elem->channel_data);
+ channel_data->Destroy(elem);
+ channel_data->~ChannelDataType();
}
- static void StartTransportOp(grpc_channel_element* elem,
- grpc_transport_op* op) {
- ChannelDataType* channel_data =
- static_cast<ChannelDataType*>(elem->channel_data);
+ static void StartTransportOp(grpc_channel_element* elem,
+ grpc_transport_op* op) {
+ ChannelDataType* channel_data =
+ static_cast<ChannelDataType*>(elem->channel_data);
TransportOp op_wrapper(op);
- channel_data->StartTransportOp(elem, &op_wrapper);
+ channel_data->StartTransportOp(elem, &op_wrapper);
}
- static void GetChannelInfo(grpc_channel_element* elem,
- const grpc_channel_info* channel_info) {
- ChannelDataType* channel_data =
- static_cast<ChannelDataType*>(elem->channel_data);
- channel_data->GetInfo(elem, channel_info);
+ static void GetChannelInfo(grpc_channel_element* elem,
+ const grpc_channel_info* channel_info) {
+ ChannelDataType* channel_data =
+ static_cast<ChannelDataType*>(elem->channel_data);
+ channel_data->GetInfo(elem, channel_info);
}
static const size_t call_data_size = sizeof(CallDataType);
- static grpc_error* InitCallElement(grpc_call_element* elem,
- const grpc_call_element_args* args) {
+ static grpc_error* InitCallElement(grpc_call_element* elem,
+ const grpc_call_element_args* args) {
// Construct the object in the already-allocated memory.
- CallDataType* call_data = new (elem->call_data) CallDataType();
- return call_data->Init(elem, args);
+ CallDataType* call_data = new (elem->call_data) CallDataType();
+ return call_data->Init(elem, args);
}
- static void DestroyCallElement(grpc_call_element* elem,
- const grpc_call_final_info* final_info,
- grpc_closure* then_call_closure) {
- CallDataType* call_data = static_cast<CallDataType*>(elem->call_data);
- call_data->Destroy(elem, final_info, then_call_closure);
- call_data->~CallDataType();
+ static void DestroyCallElement(grpc_call_element* elem,
+ const grpc_call_final_info* final_info,
+ grpc_closure* then_call_closure) {
+ CallDataType* call_data = static_cast<CallDataType*>(elem->call_data);
+ call_data->Destroy(elem, final_info, then_call_closure);
+ call_data->~CallDataType();
}
- static void StartTransportStreamOpBatch(grpc_call_element* elem,
- grpc_transport_stream_op_batch* op) {
- CallDataType* call_data = static_cast<CallDataType*>(elem->call_data);
- TransportStreamOpBatch op_wrapper(op);
- call_data->StartTransportStreamOpBatch(elem, &op_wrapper);
+ static void StartTransportStreamOpBatch(grpc_call_element* elem,
+ grpc_transport_stream_op_batch* op) {
+ CallDataType* call_data = static_cast<CallDataType*>(elem->call_data);
+ TransportStreamOpBatch op_wrapper(op);
+ call_data->StartTransportStreamOpBatch(elem, &op_wrapper);
}
- static void SetPollsetOrPollsetSet(grpc_call_element* elem,
- grpc_polling_entity* pollent) {
- CallDataType* call_data = static_cast<CallDataType*>(elem->call_data);
- call_data->SetPollsetOrPollsetSet(elem, pollent);
+ static void SetPollsetOrPollsetSet(grpc_call_element* elem,
+ grpc_polling_entity* pollent) {
+ CallDataType* call_data = static_cast<CallDataType*>(elem->call_data);
+ call_data->SetPollsetOrPollsetSet(elem, pollent);
}
};
struct FilterRecord {
grpc_channel_stack_type stack_type;
int priority;
- std::function<bool(const grpc_channel_args&)> include_filter;
+ std::function<bool(const grpc_channel_args&)> include_filter;
grpc_channel_filter filter;
};
-extern std::vector<FilterRecord>* channel_filters;
+extern std::vector<FilterRecord>* channel_filters;
void ChannelFilterPluginInit();
void ChannelFilterPluginShutdown();
@@ -373,8 +373,8 @@ void ChannelFilterPluginShutdown();
/// decide whether to add a filter or not.
template <typename ChannelDataType, typename CallDataType>
void RegisterChannelFilter(
- const char* name, grpc_channel_stack_type stack_type, int priority,
- std::function<bool(const grpc_channel_args&)> include_filter) {
+ const char* name, grpc_channel_stack_type stack_type, int priority,
+ std::function<bool(const grpc_channel_args&)> include_filter) {
// If we haven't been called before, initialize channel_filters and
// call grpc_register_plugin().
if (internal::channel_filters == nullptr) {
@@ -389,11 +389,11 @@ void RegisterChannelFilter(
stack_type,
priority,
include_filter,
- {FilterType::StartTransportStreamOpBatch, FilterType::StartTransportOp,
+ {FilterType::StartTransportStreamOpBatch, FilterType::StartTransportOp,
FilterType::call_data_size, FilterType::InitCallElement,
FilterType::SetPollsetOrPollsetSet, FilterType::DestroyCallElement,
FilterType::channel_data_size, FilterType::InitChannelElement,
- FilterType::DestroyChannelElement, FilterType::GetChannelInfo, name}};
+ FilterType::DestroyChannelElement, FilterType::GetChannelInfo, name}};
internal::channel_filters->push_back(filter_record);
}
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 96a7105eaf4..e5dc4fd590f 100644
--- a/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc
+++ b/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc
@@ -1,39 +1,39 @@
/*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/completion_queue.h>
+#include <grpcpp/completion_queue.h>
#include <memory>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
-#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/support/time.h>
+#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/support/time.h>
namespace grpc {
static internal::GrpcLibraryInitializer g_gli_initializer;
-// 'CompletionQueue' constructor can safely call GrpcLibraryCodegen(false) here
-// i.e not have GrpcLibraryCodegen call grpc_init(). This is because, to create
-// a 'grpc_completion_queue' instance (which is being passed as the input to
-// this constructor), one must have already called grpc_init().
-CompletionQueue::CompletionQueue(grpc_completion_queue* take)
- : GrpcLibraryCodegen(false), cq_(take) {
+// 'CompletionQueue' constructor can safely call GrpcLibraryCodegen(false) here
+// i.e not have GrpcLibraryCodegen call grpc_init(). This is because, to create
+// a 'grpc_completion_queue' instance (which is being passed as the input to
+// this constructor), one must have already called grpc_init().
+CompletionQueue::CompletionQueue(grpc_completion_queue* take)
+ : GrpcLibraryCodegen(false), cq_(take) {
InitialAvalanching();
}
@@ -70,30 +70,30 @@ CompletionQueue::NextStatus CompletionQueue::AsyncNextInternal(
}
}
-CompletionQueue::CompletionQueueTLSCache::CompletionQueueTLSCache(
- CompletionQueue* cq)
- : cq_(cq), flushed_(false) {
- grpc_completion_queue_thread_local_cache_init(cq_->cq_);
-}
-
-CompletionQueue::CompletionQueueTLSCache::~CompletionQueueTLSCache() {
- GPR_ASSERT(flushed_);
-}
-
-bool CompletionQueue::CompletionQueueTLSCache::Flush(void** tag, bool* ok) {
- int res = 0;
- void* res_tag;
- flushed_ = true;
- if (grpc_completion_queue_thread_local_cache_flush(cq_->cq_, &res_tag,
- &res)) {
+CompletionQueue::CompletionQueueTLSCache::CompletionQueueTLSCache(
+ CompletionQueue* cq)
+ : cq_(cq), flushed_(false) {
+ grpc_completion_queue_thread_local_cache_init(cq_->cq_);
+}
+
+CompletionQueue::CompletionQueueTLSCache::~CompletionQueueTLSCache() {
+ GPR_ASSERT(flushed_);
+}
+
+bool CompletionQueue::CompletionQueueTLSCache::Flush(void** tag, bool* ok) {
+ int res = 0;
+ void* res_tag;
+ 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);
- *ok = res == 1;
+ *ok = res == 1;
if (core_cq_tag->FinalizeResult(tag, ok)) {
- return true;
- }
- }
- return false;
-}
-
+ return true;
+ }
+ }
+ return false;
+}
+
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/common/core_codegen.cc b/contrib/libs/grpc/src/cpp/common/core_codegen.cc
index 75383ed5110..079e390f089 100644
--- a/contrib/libs/grpc/src/cpp/common/core_codegen.cc
+++ b/contrib/libs/grpc/src/cpp/common/core_codegen.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/core_codegen.h>
+#include <grpcpp/impl/codegen/core_codegen.h>
#include <stdlib.h>
@@ -29,7 +29,7 @@
#include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include <grpc/support/sync.h>
-#include <grpcpp/support/config.h>
+#include <grpcpp/support/config.h>
#include "src/core/lib/profiling/timers.h"
@@ -37,28 +37,28 @@ struct grpc_byte_buffer;
namespace grpc {
-const grpc_completion_queue_factory*
-CoreCodegen::grpc_completion_queue_factory_lookup(
- const grpc_completion_queue_attributes* attributes) {
- return ::grpc_completion_queue_factory_lookup(attributes);
-}
-
+const grpc_completion_queue_factory*
+CoreCodegen::grpc_completion_queue_factory_lookup(
+ const grpc_completion_queue_attributes* attributes) {
+ return ::grpc_completion_queue_factory_lookup(attributes);
+}
+
grpc_completion_queue* CoreCodegen::grpc_completion_queue_create(
- const grpc_completion_queue_factory* factory,
- const grpc_completion_queue_attributes* attributes, void* reserved) {
- return ::grpc_completion_queue_create(factory, attributes, reserved);
-}
-
-grpc_completion_queue* CoreCodegen::grpc_completion_queue_create_for_next(
+ const grpc_completion_queue_factory* factory,
+ const grpc_completion_queue_attributes* attributes, void* reserved) {
+ return ::grpc_completion_queue_create(factory, attributes, reserved);
+}
+
+grpc_completion_queue* CoreCodegen::grpc_completion_queue_create_for_next(
void* reserved) {
- return ::grpc_completion_queue_create_for_next(reserved);
-}
-
-grpc_completion_queue* CoreCodegen::grpc_completion_queue_create_for_pluck(
- void* reserved) {
- return ::grpc_completion_queue_create_for_pluck(reserved);
+ return ::grpc_completion_queue_create_for_next(reserved);
}
+grpc_completion_queue* CoreCodegen::grpc_completion_queue_create_for_pluck(
+ void* reserved) {
+ return ::grpc_completion_queue_create_for_pluck(reserved);
+}
+
void CoreCodegen::grpc_completion_queue_shutdown(grpc_completion_queue* cq) {
::grpc_completion_queue_shutdown(cq);
}
@@ -78,9 +78,9 @@ void* CoreCodegen::gpr_malloc(size_t size) { return ::gpr_malloc(size); }
void CoreCodegen::gpr_free(void* p) { return ::gpr_free(p); }
-void CoreCodegen::grpc_init() { ::grpc_init(); }
-void CoreCodegen::grpc_shutdown() { ::grpc_shutdown(); }
-
+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_destroy(gpr_mu* mu) { ::gpr_mu_destroy(mu); }
void CoreCodegen::gpr_mu_lock(gpr_mu* mu) { ::gpr_mu_lock(mu); }
@@ -94,18 +94,18 @@ int CoreCodegen::gpr_cv_wait(gpr_cv* cv, gpr_mu* mu,
void CoreCodegen::gpr_cv_signal(gpr_cv* cv) { ::gpr_cv_signal(cv); }
void CoreCodegen::gpr_cv_broadcast(gpr_cv* cv) { ::gpr_cv_broadcast(cv); }
-grpc_byte_buffer* CoreCodegen::grpc_byte_buffer_copy(grpc_byte_buffer* bb) {
- return ::grpc_byte_buffer_copy(bb);
-}
-
+grpc_byte_buffer* CoreCodegen::grpc_byte_buffer_copy(grpc_byte_buffer* bb) {
+ return ::grpc_byte_buffer_copy(bb);
+}
+
void CoreCodegen::grpc_byte_buffer_destroy(grpc_byte_buffer* bb) {
::grpc_byte_buffer_destroy(bb);
}
-size_t CoreCodegen::grpc_byte_buffer_length(grpc_byte_buffer* bb) {
- return ::grpc_byte_buffer_length(bb);
-}
-
+size_t CoreCodegen::grpc_byte_buffer_length(grpc_byte_buffer* bb) {
+ return ::grpc_byte_buffer_length(bb);
+}
+
grpc_call_error CoreCodegen::grpc_call_start_batch(grpc_call* call,
const grpc_op* ops,
size_t nops, void* tag,
@@ -113,20 +113,20 @@ grpc_call_error CoreCodegen::grpc_call_start_batch(grpc_call* call,
return ::grpc_call_start_batch(call, ops, nops, tag, reserved);
}
-grpc_call_error CoreCodegen::grpc_call_cancel_with_status(
- grpc_call* call, grpc_status_code status, const char* description,
- void* reserved) {
- return ::grpc_call_cancel_with_status(call, status, description, reserved);
-}
-void CoreCodegen::grpc_call_ref(grpc_call* call) { ::grpc_call_ref(call); }
-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);
-}
+grpc_call_error CoreCodegen::grpc_call_cancel_with_status(
+ grpc_call* call, grpc_status_code status, const char* description,
+ void* reserved) {
+ return ::grpc_call_cancel_with_status(call, status, description, reserved);
+}
+void CoreCodegen::grpc_call_ref(grpc_call* call) { ::grpc_call_ref(call); }
+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);
}
-
+
int CoreCodegen::grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader,
grpc_byte_buffer* buffer) {
return ::grpc_byte_buffer_reader_init(reader, buffer);
@@ -152,20 +152,20 @@ grpc_byte_buffer* CoreCodegen::grpc_raw_byte_buffer_create(grpc_slice* slice,
return ::grpc_raw_byte_buffer_create(slice, nslices);
}
-grpc_slice CoreCodegen::grpc_slice_new_with_user_data(void* p, size_t len,
- void (*destroy)(void*),
- void* user_data) {
- return ::grpc_slice_new_with_user_data(p, len, destroy, user_data);
-}
-
-grpc_slice CoreCodegen::grpc_slice_new_with_len(void* p, size_t len,
- void (*destroy)(void*,
- size_t)) {
- return ::grpc_slice_new_with_len(p, len, destroy);
-}
-
-grpc_slice CoreCodegen::grpc_empty_slice() { return ::grpc_empty_slice(); }
-
+grpc_slice CoreCodegen::grpc_slice_new_with_user_data(void* p, size_t len,
+ void (*destroy)(void*),
+ void* user_data) {
+ return ::grpc_slice_new_with_user_data(p, len, destroy, user_data);
+}
+
+grpc_slice CoreCodegen::grpc_slice_new_with_len(void* p, size_t len,
+ void (*destroy)(void*,
+ size_t)) {
+ return ::grpc_slice_new_with_len(p, len, destroy);
+}
+
+grpc_slice CoreCodegen::grpc_empty_slice() { return ::grpc_empty_slice(); }
+
grpc_slice CoreCodegen::grpc_slice_malloc(size_t length) {
return ::grpc_slice_malloc(length);
}
@@ -174,33 +174,33 @@ void CoreCodegen::grpc_slice_unref(grpc_slice slice) {
::grpc_slice_unref(slice);
}
-grpc_slice CoreCodegen::grpc_slice_ref(grpc_slice slice) {
- return ::grpc_slice_ref(slice);
-}
-
+grpc_slice CoreCodegen::grpc_slice_ref(grpc_slice slice) {
+ return ::grpc_slice_ref(slice);
+}
+
grpc_slice CoreCodegen::grpc_slice_split_tail(grpc_slice* s, size_t split) {
return ::grpc_slice_split_tail(s, split);
}
-grpc_slice CoreCodegen::grpc_slice_split_head(grpc_slice* s, size_t split) {
- return ::grpc_slice_split_head(s, split);
-}
-
-grpc_slice CoreCodegen::grpc_slice_sub(grpc_slice s, size_t begin, size_t end) {
- return ::grpc_slice_sub(s, begin, end);
-}
-
-grpc_slice CoreCodegen::grpc_slice_from_static_buffer(const void* buffer,
- size_t length) {
- return ::grpc_slice_from_static_buffer(buffer, length);
-}
-
-grpc_slice CoreCodegen::grpc_slice_from_copied_buffer(const void* buffer,
- size_t length) {
- return ::grpc_slice_from_copied_buffer(static_cast<const char*>(buffer),
- length);
-}
-
+grpc_slice CoreCodegen::grpc_slice_split_head(grpc_slice* s, size_t split) {
+ return ::grpc_slice_split_head(s, split);
+}
+
+grpc_slice CoreCodegen::grpc_slice_sub(grpc_slice s, size_t begin, size_t end) {
+ return ::grpc_slice_sub(s, begin, end);
+}
+
+grpc_slice CoreCodegen::grpc_slice_from_static_buffer(const void* buffer,
+ size_t length) {
+ return ::grpc_slice_from_static_buffer(buffer, length);
+}
+
+grpc_slice CoreCodegen::grpc_slice_from_copied_buffer(const void* buffer,
+ size_t length) {
+ return ::grpc_slice_from_copied_buffer(static_cast<const char*>(buffer),
+ length);
+}
+
void CoreCodegen::grpc_slice_buffer_add(grpc_slice_buffer* sb,
grpc_slice slice) {
::grpc_slice_buffer_add(sb, slice);
@@ -230,10 +230,10 @@ gpr_timespec CoreCodegen::gpr_time_0(gpr_clock_type type) {
return ::gpr_time_0(type);
}
-void CoreCodegen::assert_fail(const char* failed_assertion, const char* file,
- int line) {
- gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "assertion failed: %s",
- failed_assertion);
+void CoreCodegen::assert_fail(const char* failed_assertion, const char* file,
+ int line) {
+ gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "assertion failed: %s",
+ failed_assertion);
abort();
}
diff --git a/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc b/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc
index 4e5cbd03723..36e7b2a971e 100644
--- a/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc
+++ b/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc
@@ -1,24 +1,24 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 <grpc/grpc.h>
-#include <grpcpp/security/auth_context.h>
+#include <grpcpp/security/auth_context.h>
namespace grpc {
diff --git a/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc b/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc
index 64abff96338..40ec0841015 100644
--- a/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc
+++ b/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc
@@ -1,23 +1,23 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/resource_quota.h>
+#include <grpcpp/resource_quota.h>
namespace grpc {
diff --git a/contrib/libs/grpc/src/cpp/common/rpc_method.cc b/contrib/libs/grpc/src/cpp/common/rpc_method.cc
index a47dd3e4444..4c5b18e7bf7 100644
--- a/contrib/libs/grpc/src/cpp/common/rpc_method.cc
+++ b/contrib/libs/grpc/src/cpp/common/rpc_method.cc
@@ -1,21 +1,21 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/rpc_method.h>
+#include <grpcpp/impl/rpc_method.h>
namespace grpc {} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc b/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc
index e1f97889c8e..165523de859 100644
--- a/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc
+++ b/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/cpp/common/secure_auth_context.h b/contrib/libs/grpc/src/cpp/common/secure_auth_context.h
index 51013efac70..d2890c66150 100644
--- a/contrib/libs/grpc/src/cpp/common/secure_auth_context.h
+++ b/contrib/libs/grpc/src/cpp/common/secure_auth_context.h
@@ -1,25 +1,25 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_SECURE_AUTH_CONTEXT_H
#define GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H
-#include <grpcpp/security/auth_context.h>
+#include <grpcpp/security/auth_context.h>
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/security/context/security_context.h"
diff --git a/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc b/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc
index 844bc627ab3..08114a6c83f 100644
--- a/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc
+++ b/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/support/channel_arguments.h>
+#include <grpcpp/support/channel_arguments.h>
#include <grpc/grpc_security.h>
#include "src/core/lib/channel/channel_args.h"
diff --git a/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc b/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc
index 908c46629e6..6ddf22c1a57 100644
--- a/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc
+++ b/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc
@@ -1,25 +1,25 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 <grpc/grpc.h>
#include <grpc/grpc_security.h>
-#include <grpcpp/security/auth_context.h>
+#include <grpcpp/security/auth_context.h>
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/cpp/common/secure_auth_context.h"
diff --git a/contrib/libs/grpc/src/cpp/common/version_cc.cc b/contrib/libs/grpc/src/cpp/common/version_cc.cc
index 7f4228346a9..26501822aab 100644
--- a/contrib/libs/grpc/src/cpp/common/version_cc.cc
+++ b/contrib/libs/grpc/src/cpp/common/version_cc.cc
@@ -1,26 +1,26 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 is autogenerated from:
templates/src/core/surface/version.c.template */
-#include <grpcpp/grpcpp.h>
+#include <grpcpp/grpcpp.h>
namespace grpc {
TString Version() { return "1.33.2"; }
-} // namespace grpc
+} // 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 1b388210c05..cb669348f09 100644
--- a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc
+++ b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc
@@ -1,35 +1,35 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 <unordered_set>
#include <vector>
-#include <grpcpp/grpcpp.h>
+#include <grpcpp/grpcpp.h>
#include "src/cpp/ext/proto_server_reflection.h"
using grpc::Status;
using grpc::StatusCode;
-using grpc::reflection::v1alpha::ErrorResponse;
-using grpc::reflection::v1alpha::ExtensionNumberResponse;
-using grpc::reflection::v1alpha::ExtensionRequest;
-using grpc::reflection::v1alpha::FileDescriptorResponse;
-using grpc::reflection::v1alpha::ListServiceResponse;
+using grpc::reflection::v1alpha::ErrorResponse;
+using grpc::reflection::v1alpha::ExtensionNumberResponse;
+using grpc::reflection::v1alpha::ExtensionRequest;
+using grpc::reflection::v1alpha::FileDescriptorResponse;
+using grpc::reflection::v1alpha::ListServiceResponse;
using grpc::reflection::v1alpha::ServerReflectionRequest;
using grpc::reflection::v1alpha::ServerReflectionResponse;
using grpc::reflection::v1alpha::ServiceResponse;
diff --git a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h
index 2d17eed95a8..2255d56125e 100644
--- a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h
+++ b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -22,7 +22,7 @@
#include <unordered_set>
#include <vector>
-#include <grpcpp/grpcpp.h>
+#include <grpcpp/grpcpp.h>
#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h"
namespace grpc {
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 007193d7f72..6de2952ecdc 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
@@ -1,25 +1,25 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/ext/proto_server_reflection_plugin.h>
-#include <grpcpp/impl/server_builder_plugin.h>
-#include <grpcpp/impl/server_initializer.h>
-#include <grpcpp/server.h>
+#include <grpcpp/ext/proto_server_reflection_plugin.h>
+#include <grpcpp/impl/server_builder_plugin.h>
+#include <grpcpp/impl/server_initializer.h>
+#include <grpcpp/server.h>
#include "src/cpp/ext/proto_server_reflection.h"
diff --git a/contrib/libs/grpc/src/cpp/server/async_generic_service.cc b/contrib/libs/grpc/src/cpp/server/async_generic_service.cc
index 07697a52d1f..2a549e674fa 100644
--- a/contrib/libs/grpc/src/cpp/server/async_generic_service.cc
+++ b/contrib/libs/grpc/src/cpp/server/async_generic_service.cc
@@ -1,24 +1,24 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/generic/async_generic_service.h>
+#include <grpcpp/generic/async_generic_service.h>
-#include <grpcpp/server.h>
+#include <grpcpp/server.h>
namespace grpc {
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 9aad932429d..69be1ead746 100644
--- a/contrib/libs/grpc/src/cpp/server/channel_argument_option.cc
+++ b/contrib/libs/grpc/src/cpp/server/channel_argument_option.cc
@@ -1,65 +1,65 @@
-/*
- *
- * 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 <grpcpp/impl/channel_argument_option.h>
-
-namespace grpc {
-
-std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
+/*
+ *
+ * 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 <grpcpp/impl/channel_argument_option.h>
+
+namespace grpc {
+
+std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
const TString& name, const TString& value) {
- class StringOption final : public ServerBuilderOption {
- public:
+ class StringOption final : public ServerBuilderOption {
+ public:
StringOption(const TString& name, const TString& value)
- : name_(name), value_(value) {}
-
- virtual void UpdateArguments(ChannelArguments* args) override {
- args->SetString(name_, value_);
- }
- virtual void UpdatePlugins(
+ : name_(name), value_(value) {}
+
+ virtual void UpdateArguments(ChannelArguments* args) override {
+ args->SetString(name_, value_);
+ }
+ virtual void UpdatePlugins(
std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/)
override {}
-
- private:
+
+ private:
const TString name_;
const TString value_;
- };
- return std::unique_ptr<ServerBuilderOption>(new StringOption(name, value));
-}
-
-std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
+ };
+ return std::unique_ptr<ServerBuilderOption>(new StringOption(name, value));
+}
+
+std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
const TString& name, int value) {
- class IntOption final : public ServerBuilderOption {
- public:
+ class IntOption final : public ServerBuilderOption {
+ public:
IntOption(const TString& name, int value)
- : name_(name), value_(value) {}
-
- virtual void UpdateArguments(ChannelArguments* args) override {
- args->SetInt(name_, value_);
- }
- virtual void UpdatePlugins(
+ : name_(name), value_(value) {}
+
+ virtual void UpdateArguments(ChannelArguments* args) override {
+ args->SetInt(name_, value_);
+ }
+ virtual void UpdatePlugins(
std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/)
override {}
-
- private:
+
+ private:
const TString name_;
- const int value_;
- };
- return std::unique_ptr<ServerBuilderOption>(new IntOption(name, value));
-}
-
-} // namespace grpc
+ const int value_;
+ };
+ return std::unique_ptr<ServerBuilderOption>(new IntOption(name, value));
+}
+
+} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc b/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc
index 8ca3e32c2fb..16ca3783e87 100644
--- a/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc
+++ b/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -23,22 +23,22 @@
#ifndef GRPC_CUSTOM_DEFAULT_THREAD_POOL
namespace grpc {
-namespace {
+namespace {
-ThreadPoolInterface* CreateDefaultThreadPoolImpl() {
+ThreadPoolInterface* CreateDefaultThreadPoolImpl() {
int cores = gpr_cpu_num_cores();
if (!cores) cores = 4;
return new DynamicThreadPool(cores);
}
-CreateThreadPoolFunc g_ctp_impl = CreateDefaultThreadPoolImpl;
-
-} // namespace
-
-ThreadPoolInterface* CreateDefaultThreadPool() { return g_ctp_impl(); }
-
-void SetCreateThreadPool(CreateThreadPoolFunc func) { g_ctp_impl = func; }
-
+CreateThreadPoolFunc g_ctp_impl = CreateDefaultThreadPoolImpl;
+
+} // namespace
+
+ThreadPoolInterface* CreateDefaultThreadPool() { return g_ctp_impl(); }
+
+void SetCreateThreadPool(CreateThreadPoolFunc func) { g_ctp_impl = func; }
+
} // namespace grpc
#endif // !GRPC_CUSTOM_DEFAULT_THREAD_POOL
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 77c5d6a263d..db6036c9258 100644
--- a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc
+++ b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc
@@ -1,40 +1,40 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/dynamic_thread_pool.h"
-
-#include <grpc/support/log.h>
+#include "src/cpp/server/dynamic_thread_pool.h"
+
+#include <grpc/support/log.h>
#include <grpcpp/impl/codegen/sync.h>
-#include "src/core/lib/gprpp/thd.h"
-
+#include "src/core/lib/gprpp/thd.h"
+
namespace grpc {
-
+
DynamicThreadPool::DynamicThread::DynamicThread(DynamicThreadPool* pool)
: pool_(pool),
- thd_("grpcpp_dynamic_pool",
- [](void* th) {
- static_cast<DynamicThreadPool::DynamicThread*>(th)->ThreadFunc();
- },
- this) {
- thd_.Start();
+ thd_("grpcpp_dynamic_pool",
+ [](void* th) {
+ static_cast<DynamicThreadPool::DynamicThread*>(th)->ThreadFunc();
+ },
+ this) {
+ thd_.Start();
}
-DynamicThreadPool::DynamicThread::~DynamicThread() { thd_.Join(); }
+DynamicThreadPool::DynamicThread::~DynamicThread() { thd_.Join(); }
void DynamicThreadPool::DynamicThread::ThreadFunc() {
pool_->ThreadFunc();
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 6f9f943bc38..42d2ea4ba69 100644
--- a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h
+++ b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -23,10 +23,10 @@
#include <memory>
#include <queue>
-#include <grpcpp/support/config.h>
+#include <grpcpp/support/config.h>
#include "src/core/lib/gprpp/sync.h"
-#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/gprpp/thd.h"
#include "src/cpp/server/thread_pool_interface.h"
namespace grpc {
@@ -46,7 +46,7 @@ class DynamicThreadPool final : public ThreadPoolInterface {
private:
DynamicThreadPool* pool_;
- grpc_core::Thread thd_;
+ grpc_core::Thread thd_;
void ThreadFunc();
};
grpc_core::Mutex mu_;
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 3cc508d0cbf..16f81ea474a 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
@@ -1,37 +1,37 @@
-/*
- *
- * 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>
-
+/*
+ *
+ * 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 "upb/upb.hpp"
-#include <grpc/slice.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
+#include <grpc/slice.h>
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
#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 "upb/upb.hpp"
-
+
#define MAX_SERVICE_NAME_LENGTH 200
-namespace grpc {
+namespace grpc {
//
// DefaultHealthCheckService
@@ -144,12 +144,12 @@ void DefaultHealthCheckService::ServiceData::RemoveCallHandler(
// DefaultHealthCheckService::HealthCheckServiceImpl
//
-namespace {
-const char kHealthCheckMethodName[] = "/grpc.health.v1.Health/Check";
+namespace {
+const char kHealthCheckMethodName[] = "/grpc.health.v1.Health/Check";
const char kHealthWatchMethodName[] = "/grpc.health.v1.Health/Watch";
-} // namespace
-
-DefaultHealthCheckService::HealthCheckServiceImpl::HealthCheckServiceImpl(
+} // namespace
+
+DefaultHealthCheckService::HealthCheckServiceImpl::HealthCheckServiceImpl(
DefaultHealthCheckService* database,
std::unique_ptr<ServerCompletionQueue> cq)
: database_(database), cq_(std::move(cq)) {
@@ -162,8 +162,8 @@ DefaultHealthCheckService::HealthCheckServiceImpl::HealthCheckServiceImpl(
// Create serving thread.
thread_ = std::unique_ptr<::grpc_core::Thread>(
new ::grpc_core::Thread("grpc_health_check_service", Serve, this));
-}
-
+}
+
DefaultHealthCheckService::HealthCheckServiceImpl::~HealthCheckServiceImpl() {
// We will reach here after the server starts shutting down.
shutdown_ = true;
@@ -201,28 +201,28 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::Serve(void* arg) {
bool DefaultHealthCheckService::HealthCheckServiceImpl::DecodeRequest(
const ByteBuffer& request, TString* service_name) {
- std::vector<Slice> slices;
+ std::vector<Slice> slices;
if (!request.Dump(&slices).ok()) return false;
- uint8_t* request_bytes = nullptr;
- size_t request_size = 0;
+ uint8_t* request_bytes = nullptr;
+ size_t request_size = 0;
if (slices.size() == 1) {
- request_bytes = const_cast<uint8_t*>(slices[0].begin());
- request_size = slices[0].size();
+ request_bytes = const_cast<uint8_t*>(slices[0].begin());
+ request_size = slices[0].size();
} else if (slices.size() > 1) {
request_bytes = static_cast<uint8_t*>(gpr_malloc(request.Length()));
- uint8_t* copy_to = request_bytes;
- for (size_t i = 0; i < slices.size(); i++) {
- memcpy(copy_to, slices[i].begin(), slices[i].size());
- copy_to += slices[i].size();
- }
- }
+ uint8_t* copy_to = request_bytes;
+ for (size_t i = 0; i < slices.size(); i++) {
+ memcpy(copy_to, slices[i].begin(), slices[i].size());
+ 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());
if (slices.size() > 1) {
gpr_free(request_bytes);
- }
+ }
if (request_struct == nullptr) {
return false;
}
@@ -234,7 +234,7 @@ bool DefaultHealthCheckService::HealthCheckServiceImpl::DecodeRequest(
service_name->assign(service.data, service.size);
return true;
}
-
+
bool DefaultHealthCheckService::HealthCheckServiceImpl::EncodeResponse(
ServingStatus status, ByteBuffer* response) {
upb::Arena arena;
@@ -253,12 +253,12 @@ bool DefaultHealthCheckService::HealthCheckServiceImpl::EncodeResponse(
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);
+ Slice encoded_response(response_slice, Slice::STEAL_REF);
+ ByteBuffer response_buffer(&encoded_response, 1);
+ response->Swap(&response_buffer);
return true;
-}
-
+}
+
//
// DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler
//
@@ -281,8 +281,8 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler::
service->RequestAsyncUnary(0, &handler->ctx_, &handler->request_,
&handler->writer_, cq, cq, &handler->next_);
}
-}
-
+}
+
DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler::
CheckCallHandler(ServerCompletionQueue* cq,
DefaultHealthCheckService* database,
@@ -329,17 +329,17 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler::
}
}
}
-}
-
+}
+
void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler::
OnFinishDone(std::shared_ptr<CallHandler> self, bool ok) {
if (ok) {
gpr_log(GPR_DEBUG, "[HCS %p] Health check call finished for handler %p",
service_, this);
- }
+ }
self.reset(); // To appease clang-tidy.
-}
-
+}
+
//
// DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler
//
@@ -368,9 +368,9 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
service->RequestAsyncServerStreaming(1, &handler->ctx_, &handler->request_,
&handler->stream_, cq, cq,
&handler->next_);
- }
-}
-
+ }
+}
+
DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
WatchCallHandler(ServerCompletionQueue* cq,
DefaultHealthCheckService* database,
@@ -403,8 +403,8 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
"[HCS %p] Health watch started for service \"%s\" (handler: %p)",
service_, service_name_.c_str(), this);
database_->RegisterCallHandler(service_name_, std::move(self));
-}
-
+}
+
void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
SendHealth(std::shared_ptr<CallHandler> self, ServingStatus status) {
grpc_core::MutexLock lock(&send_mu_);
@@ -501,4 +501,4 @@ void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler::
SendFinish(std::move(self), Status::CANCELLED);
}
-} // namespace grpc
+} // namespace grpc
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 9da1dfc15fa..3d7935ae8c2 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
@@ -1,50 +1,50 @@
-/*
- *
- * 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_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_H
-#define GRPC_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_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_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_H
+#define GRPC_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_H
+
#include <atomic>
#include <set>
-
+
#include <grpc/support/log.h>
#include <grpcpp/grpcpp.h>
-#include <grpcpp/health_check_service_interface.h>
+#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/service_type.h>
-#include <grpcpp/support/byte_buffer.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/thd.h"
-namespace grpc {
-
-// Default implementation of HealthCheckServiceInterface. Server will create and
-// own it.
-class DefaultHealthCheckService final : public HealthCheckServiceInterface {
- public:
+namespace grpc {
+
+// Default implementation of HealthCheckServiceInterface. Server will create and
+// own it.
+class DefaultHealthCheckService final : public HealthCheckServiceInterface {
+ public:
enum ServingStatus { NOT_FOUND, SERVING, NOT_SERVING };
- // The service impl to register with the server.
- class HealthCheckServiceImpl : public Service {
- public:
+ // The service impl to register with the server.
+ class HealthCheckServiceImpl : public Service {
+ public:
// Base class for call handlers.
class CallHandler {
public:
@@ -52,15 +52,15 @@ class DefaultHealthCheckService final : public HealthCheckServiceInterface {
virtual void SendHealth(std::shared_ptr<CallHandler> self,
ServingStatus status) = 0;
};
-
+
HealthCheckServiceImpl(DefaultHealthCheckService* database,
std::unique_ptr<ServerCompletionQueue> cq);
-
+
~HealthCheckServiceImpl();
void StartServingThread();
- private:
+ private:
// A tag that can be called with a bool argument. It's tailored for
// CallHandler's use. Before being used, it should be constructed with a
// method of CallHandler and a shared pointer to the handler. The
@@ -230,21 +230,21 @@ class DefaultHealthCheckService final : public HealthCheckServiceInterface {
grpc_core::Mutex cq_shutdown_mu_;
std::atomic_bool shutdown_{false};
std::unique_ptr<::grpc_core::Thread> thread_;
- };
-
- DefaultHealthCheckService();
+ };
+
+ DefaultHealthCheckService();
void SetServingStatus(const TString& service_name, bool serving) override;
- void SetServingStatus(bool serving) override;
+ void SetServingStatus(bool serving) override;
void Shutdown() override;
ServingStatus GetServingStatus(const TString& service_name) const;
-
+
HealthCheckServiceImpl* GetHealthCheckService(
std::unique_ptr<ServerCompletionQueue> cq);
- private:
+ private:
// Stores the current serving status of a service and any call
// handlers registered for updates when the service's status changes.
class ServiceData {
@@ -276,9 +276,9 @@ class DefaultHealthCheckService final : public HealthCheckServiceInterface {
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_;
-};
-
-} // namespace grpc
-
-#endif // GRPC_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_H
+ std::unique_ptr<HealthCheckServiceImpl> impl_;
+};
+
+} // namespace grpc
+
+#endif // GRPC_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_H
diff --git a/contrib/libs/grpc/src/cpp/server/health/health_check_service.cc b/contrib/libs/grpc/src/cpp/server/health/health_check_service.cc
index a0fa2d62f58..ce625563efd 100644
--- a/contrib/libs/grpc/src/cpp/server/health/health_check_service.cc
+++ b/contrib/libs/grpc/src/cpp/server/health/health_check_service.cc
@@ -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.
- *
- */
-
+/*
+ *
+ * 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 <grpcpp/health_check_service_interface.h>
-
+
namespace grpc {
-namespace {
-bool g_grpc_default_health_check_service_enabled = false;
-} // namespace
-
-bool DefaultHealthCheckServiceEnabled() {
- return g_grpc_default_health_check_service_enabled;
-}
-
-void EnableDefaultHealthCheckService(bool enable) {
- g_grpc_default_health_check_service_enabled = enable;
-}
-
+namespace {
+bool g_grpc_default_health_check_service_enabled = false;
+} // namespace
+
+bool DefaultHealthCheckServiceEnabled() {
+ return g_grpc_default_health_check_service_enabled;
+}
+
+void EnableDefaultHealthCheckService(bool enable) {
+ g_grpc_default_health_check_service_enabled = enable;
+}
+
} // namespace grpc
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 3fa384ace9e..7b176b07499 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
@@ -1,35 +1,35 @@
-/*
- *
- * 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 <grpcpp/ext/health_check_service_server_builder_option.h>
-
-namespace grpc {
-
-HealthCheckServiceServerBuilderOption::HealthCheckServiceServerBuilderOption(
- std::unique_ptr<HealthCheckServiceInterface> hc)
- : hc_(std::move(hc)) {}
-// Hand over hc_ to the server.
-void HealthCheckServiceServerBuilderOption::UpdateArguments(
- ChannelArguments* args) {
- args->SetPointer(kHealthCheckServiceInterfaceArg, hc_.release());
-}
-
-void HealthCheckServiceServerBuilderOption::UpdatePlugins(
+/*
+ *
+ * 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 <grpcpp/ext/health_check_service_server_builder_option.h>
+
+namespace grpc {
+
+HealthCheckServiceServerBuilderOption::HealthCheckServiceServerBuilderOption(
+ std::unique_ptr<HealthCheckServiceInterface> hc)
+ : hc_(std::move(hc)) {}
+// Hand over hc_ to the server.
+void HealthCheckServiceServerBuilderOption::UpdateArguments(
+ ChannelArguments* args) {
+ args->SetPointer(kHealthCheckServiceInterfaceArg, hc_.release());
+}
+
+void HealthCheckServiceServerBuilderOption::UpdatePlugins(
std::vector<std::unique_ptr<ServerBuilderPlugin>>* /*plugins*/) {}
-
-} // namespace grpc
+
+} // 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 3f33f4e045c..493f6067f4a 100644
--- a/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/security/server_credentials.h>
+#include <grpcpp/security/server_credentials.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc
index f07fa812a7d..46be0cd6aa2 100644
--- a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc
+++ b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.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.
- *
- */
-
+/*
+ *
+ * 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/impl/codegen/port_platform.h>
#include <stdio.h>
-#include <cstdlib>
-#include <set>
-#include <unordered_map>
-#include <vector>
-
+#include <cstdlib>
+#include <set>
+#include <unordered_map>
+#include <vector>
+
#include "src/core/lib/iomgr/socket_utils.h"
-#include "src/cpp/server/load_reporter/load_data_store.h"
-
-namespace grpc {
-namespace load_reporter {
-
-// Some helper functions.
-namespace {
-
-// Given a map from type K to a set of value type V, finds the set associated
-// with the given key and erases the value from the set. If the set becomes
-// empty, also erases the key-set pair. Returns true if the value is erased
-// successfully.
-template <typename K, typename V>
-bool UnorderedMapOfSetEraseKeyValue(std::unordered_map<K, std::set<V>>& map,
- const K& key, const V& value) {
- auto it = map.find(key);
- if (it != map.end()) {
- size_t erased = it->second.erase(value);
- if (it->second.size() == 0) {
- map.erase(it);
- }
- return erased;
- }
- return false;
-};
-
-// Given a map from type K to a set of value type V, removes the given key and
-// the associated set, and returns the set. Returns an empty set if the key is
-// not found.
-template <typename K, typename V>
-std::set<V> UnorderedMapOfSetExtract(std::unordered_map<K, std::set<V>>& map,
- const K& key) {
- auto it = map.find(key);
- if (it != map.end()) {
- auto set = std::move(it->second);
- map.erase(it);
- return set;
- }
- return {};
-};
-
-// From a non-empty container, returns a pointer to a random element.
-template <typename C>
-const typename C::value_type* RandomElement(const C& container) {
- GPR_ASSERT(!container.empty());
- auto it = container.begin();
- std::advance(it, std::rand() % container.size());
- return &(*it);
-}
-
-} // namespace
-
+#include "src/cpp/server/load_reporter/load_data_store.h"
+
+namespace grpc {
+namespace load_reporter {
+
+// Some helper functions.
+namespace {
+
+// Given a map from type K to a set of value type V, finds the set associated
+// with the given key and erases the value from the set. If the set becomes
+// empty, also erases the key-set pair. Returns true if the value is erased
+// successfully.
+template <typename K, typename V>
+bool UnorderedMapOfSetEraseKeyValue(std::unordered_map<K, std::set<V>>& map,
+ const K& key, const V& value) {
+ auto it = map.find(key);
+ if (it != map.end()) {
+ size_t erased = it->second.erase(value);
+ if (it->second.size() == 0) {
+ map.erase(it);
+ }
+ return erased;
+ }
+ return false;
+};
+
+// Given a map from type K to a set of value type V, removes the given key and
+// the associated set, and returns the set. Returns an empty set if the key is
+// not found.
+template <typename K, typename V>
+std::set<V> UnorderedMapOfSetExtract(std::unordered_map<K, std::set<V>>& map,
+ const K& key) {
+ auto it = map.find(key);
+ if (it != map.end()) {
+ auto set = std::move(it->second);
+ map.erase(it);
+ return set;
+ }
+ return {};
+};
+
+// From a non-empty container, returns a pointer to a random element.
+template <typename C>
+const typename C::value_type* RandomElement(const C& container) {
+ GPR_ASSERT(!container.empty());
+ auto it = container.begin();
+ std::advance(it, std::rand() % container.size());
+ return &(*it);
+}
+
+} // namespace
+
LoadRecordKey::LoadRecordKey(const TString& client_ip_and_token,
TString user_id)
: user_id_(std::move(user_id)) {
@@ -138,201 +138,201 @@ LoadRecordValue::LoadRecordValue(TString metric_name, uint64_t num_calls,
CallMetricValue(num_calls, total_metric_value));
}
-void PerBalancerStore::MergeRow(const LoadRecordKey& key,
- const LoadRecordValue& value) {
- // During suspension, the load data received will be dropped.
- if (!suspended_) {
- load_record_map_[key].MergeFrom(value);
- gpr_log(GPR_DEBUG,
- "[PerBalancerStore %p] Load data merged (Key: %s, Value: %s).",
- this, key.ToString().c_str(), value.ToString().c_str());
- } else {
- gpr_log(GPR_DEBUG,
- "[PerBalancerStore %p] Load data dropped (Key: %s, Value: %s).",
- this, key.ToString().c_str(), value.ToString().c_str());
- }
- // We always keep track of num_calls_in_progress_, so that when this
- // store is resumed, we still have a correct value of
- // num_calls_in_progress_.
- GPR_ASSERT(static_cast<int64_t>(num_calls_in_progress_) +
- value.GetNumCallsInProgressDelta() >=
- 0);
- num_calls_in_progress_ += value.GetNumCallsInProgressDelta();
-}
-
-void PerBalancerStore::Suspend() {
- suspended_ = true;
- load_record_map_.clear();
- gpr_log(GPR_DEBUG, "[PerBalancerStore %p] Suspended.", this);
-}
-
-void PerBalancerStore::Resume() {
- suspended_ = false;
- gpr_log(GPR_DEBUG, "[PerBalancerStore %p] Resumed.", this);
-}
-
-uint64_t PerBalancerStore::GetNumCallsInProgressForReport() {
- GPR_ASSERT(!suspended_);
- last_reported_num_calls_in_progress_ = num_calls_in_progress_;
- return num_calls_in_progress_;
-}
-
+void PerBalancerStore::MergeRow(const LoadRecordKey& key,
+ const LoadRecordValue& value) {
+ // During suspension, the load data received will be dropped.
+ if (!suspended_) {
+ load_record_map_[key].MergeFrom(value);
+ gpr_log(GPR_DEBUG,
+ "[PerBalancerStore %p] Load data merged (Key: %s, Value: %s).",
+ this, key.ToString().c_str(), value.ToString().c_str());
+ } else {
+ gpr_log(GPR_DEBUG,
+ "[PerBalancerStore %p] Load data dropped (Key: %s, Value: %s).",
+ this, key.ToString().c_str(), value.ToString().c_str());
+ }
+ // We always keep track of num_calls_in_progress_, so that when this
+ // store is resumed, we still have a correct value of
+ // num_calls_in_progress_.
+ GPR_ASSERT(static_cast<int64_t>(num_calls_in_progress_) +
+ value.GetNumCallsInProgressDelta() >=
+ 0);
+ num_calls_in_progress_ += value.GetNumCallsInProgressDelta();
+}
+
+void PerBalancerStore::Suspend() {
+ suspended_ = true;
+ load_record_map_.clear();
+ gpr_log(GPR_DEBUG, "[PerBalancerStore %p] Suspended.", this);
+}
+
+void PerBalancerStore::Resume() {
+ suspended_ = false;
+ gpr_log(GPR_DEBUG, "[PerBalancerStore %p] Resumed.", this);
+}
+
+uint64_t PerBalancerStore::GetNumCallsInProgressForReport() {
+ GPR_ASSERT(!suspended_);
+ last_reported_num_calls_in_progress_ = num_calls_in_progress_;
+ return num_calls_in_progress_;
+}
+
void PerHostStore::ReportStreamCreated(const TString& lb_id,
const TString& load_key) {
- GPR_ASSERT(lb_id != kInvalidLbId);
- SetUpForNewLbId(lb_id, load_key);
- // Prior to this one, there was no load balancer receiving report, so we may
- // have unassigned orphaned stores to assign to this new balancer.
- // TODO(juanlishen): If the load key of this new stream is the same with
- // some previously adopted orphan store, we may want to take the orphan to
- // this stream. Need to discuss with LB team.
- if (assigned_stores_.size() == 1) {
- for (const auto& p : per_balancer_stores_) {
+ GPR_ASSERT(lb_id != kInvalidLbId);
+ SetUpForNewLbId(lb_id, load_key);
+ // Prior to this one, there was no load balancer receiving report, so we may
+ // have unassigned orphaned stores to assign to this new balancer.
+ // TODO(juanlishen): If the load key of this new stream is the same with
+ // some previously adopted orphan store, we may want to take the orphan to
+ // this stream. Need to discuss with LB team.
+ if (assigned_stores_.size() == 1) {
+ for (const auto& p : per_balancer_stores_) {
const TString& other_lb_id = p.first;
- const std::unique_ptr<PerBalancerStore>& orphaned_store = p.second;
- if (other_lb_id != lb_id) {
- orphaned_store->Resume();
- AssignOrphanedStore(orphaned_store.get(), lb_id);
- }
- }
- }
- // The first connected balancer will adopt the kInvalidLbId.
- if (per_balancer_stores_.size() == 1) {
- SetUpForNewLbId(kInvalidLbId, "");
- ReportStreamClosed(kInvalidLbId);
- }
-}
-
+ const std::unique_ptr<PerBalancerStore>& orphaned_store = p.second;
+ if (other_lb_id != lb_id) {
+ orphaned_store->Resume();
+ AssignOrphanedStore(orphaned_store.get(), lb_id);
+ }
+ }
+ }
+ // The first connected balancer will adopt the kInvalidLbId.
+ if (per_balancer_stores_.size() == 1) {
+ SetUpForNewLbId(kInvalidLbId, "");
+ ReportStreamClosed(kInvalidLbId);
+ }
+}
+
void PerHostStore::ReportStreamClosed(const TString& lb_id) {
- auto it_store_for_gone_lb = per_balancer_stores_.find(lb_id);
- GPR_ASSERT(it_store_for_gone_lb != per_balancer_stores_.end());
- // Remove this closed stream from our records.
- GPR_ASSERT(UnorderedMapOfSetEraseKeyValue(
- load_key_to_receiving_lb_ids_, it_store_for_gone_lb->second->load_key(),
- lb_id));
- std::set<PerBalancerStore*> orphaned_stores =
- UnorderedMapOfSetExtract(assigned_stores_, lb_id);
- // The stores that were assigned to this balancer are orphaned now. They
- // should be re-assigned to other balancers which are still receiving reports.
- for (PerBalancerStore* orphaned_store : orphaned_stores) {
+ auto it_store_for_gone_lb = per_balancer_stores_.find(lb_id);
+ GPR_ASSERT(it_store_for_gone_lb != per_balancer_stores_.end());
+ // Remove this closed stream from our records.
+ GPR_ASSERT(UnorderedMapOfSetEraseKeyValue(
+ load_key_to_receiving_lb_ids_, it_store_for_gone_lb->second->load_key(),
+ lb_id));
+ std::set<PerBalancerStore*> orphaned_stores =
+ UnorderedMapOfSetExtract(assigned_stores_, lb_id);
+ // The stores that were assigned to this balancer are orphaned now. They
+ // should be re-assigned to other balancers which are still receiving reports.
+ for (PerBalancerStore* orphaned_store : orphaned_stores) {
const TString* new_receiver = nullptr;
- auto it = load_key_to_receiving_lb_ids_.find(orphaned_store->load_key());
- if (it != load_key_to_receiving_lb_ids_.end()) {
- // First, try to pick from the active balancers with the same load key.
- new_receiver = RandomElement(it->second);
- } else if (!assigned_stores_.empty()) {
- // If failed, pick from all the remaining active balancers.
- new_receiver = &(RandomElement(assigned_stores_)->first);
- }
- if (new_receiver != nullptr) {
- AssignOrphanedStore(orphaned_store, *new_receiver);
- } else {
- // Load data for an LB ID that can't be assigned to any stream should
- // be dropped.
- orphaned_store->Suspend();
- }
- }
-}
-
-PerBalancerStore* PerHostStore::FindPerBalancerStore(
+ auto it = load_key_to_receiving_lb_ids_.find(orphaned_store->load_key());
+ if (it != load_key_to_receiving_lb_ids_.end()) {
+ // First, try to pick from the active balancers with the same load key.
+ new_receiver = RandomElement(it->second);
+ } else if (!assigned_stores_.empty()) {
+ // If failed, pick from all the remaining active balancers.
+ new_receiver = &(RandomElement(assigned_stores_)->first);
+ }
+ if (new_receiver != nullptr) {
+ AssignOrphanedStore(orphaned_store, *new_receiver);
+ } else {
+ // Load data for an LB ID that can't be assigned to any stream should
+ // be dropped.
+ orphaned_store->Suspend();
+ }
+ }
+}
+
+PerBalancerStore* PerHostStore::FindPerBalancerStore(
const TString& lb_id) const {
- return per_balancer_stores_.find(lb_id) != per_balancer_stores_.end()
- ? per_balancer_stores_.find(lb_id)->second.get()
- : nullptr;
-}
-
-const std::set<PerBalancerStore*>* PerHostStore::GetAssignedStores(
+ return per_balancer_stores_.find(lb_id) != per_balancer_stores_.end()
+ ? per_balancer_stores_.find(lb_id)->second.get()
+ : nullptr;
+}
+
+const std::set<PerBalancerStore*>* PerHostStore::GetAssignedStores(
const TString& lb_id) const {
- auto it = assigned_stores_.find(lb_id);
- if (it == assigned_stores_.end()) return nullptr;
- return &(it->second);
-}
-
-void PerHostStore::AssignOrphanedStore(PerBalancerStore* orphaned_store,
+ auto it = assigned_stores_.find(lb_id);
+ if (it == assigned_stores_.end()) return nullptr;
+ return &(it->second);
+}
+
+void PerHostStore::AssignOrphanedStore(PerBalancerStore* orphaned_store,
const TString& new_receiver) {
- auto it = assigned_stores_.find(new_receiver);
- GPR_ASSERT(it != assigned_stores_.end());
- it->second.insert(orphaned_store);
- gpr_log(GPR_INFO,
- "[PerHostStore %p] Re-assigned orphaned store (%p) with original LB"
- " ID of %s to new receiver %s",
- this, orphaned_store, orphaned_store->lb_id().c_str(),
- new_receiver.c_str());
-}
-
+ auto it = assigned_stores_.find(new_receiver);
+ GPR_ASSERT(it != assigned_stores_.end());
+ it->second.insert(orphaned_store);
+ gpr_log(GPR_INFO,
+ "[PerHostStore %p] Re-assigned orphaned store (%p) with original LB"
+ " ID of %s to new receiver %s",
+ this, orphaned_store, orphaned_store->lb_id().c_str(),
+ new_receiver.c_str());
+}
+
void PerHostStore::SetUpForNewLbId(const TString& lb_id,
const TString& load_key) {
- // The top-level caller (i.e., LoadReportService) should guarantee the
- // lb_id is unique for each reporting stream.
- GPR_ASSERT(per_balancer_stores_.find(lb_id) == per_balancer_stores_.end());
- GPR_ASSERT(assigned_stores_.find(lb_id) == assigned_stores_.end());
- load_key_to_receiving_lb_ids_[load_key].insert(lb_id);
- std::unique_ptr<PerBalancerStore> per_balancer_store(
- new PerBalancerStore(lb_id, load_key));
- assigned_stores_[lb_id] = {per_balancer_store.get()};
- per_balancer_stores_[lb_id] = std::move(per_balancer_store);
-}
-
-PerBalancerStore* LoadDataStore::FindPerBalancerStore(
- const string& hostname, const string& lb_id) const {
- auto it = per_host_stores_.find(hostname);
- if (it != per_host_stores_.end()) {
- const PerHostStore& per_host_store = it->second;
- return per_host_store.FindPerBalancerStore(lb_id);
- } else {
- return nullptr;
- }
-}
-
+ // The top-level caller (i.e., LoadReportService) should guarantee the
+ // lb_id is unique for each reporting stream.
+ GPR_ASSERT(per_balancer_stores_.find(lb_id) == per_balancer_stores_.end());
+ GPR_ASSERT(assigned_stores_.find(lb_id) == assigned_stores_.end());
+ load_key_to_receiving_lb_ids_[load_key].insert(lb_id);
+ std::unique_ptr<PerBalancerStore> per_balancer_store(
+ new PerBalancerStore(lb_id, load_key));
+ assigned_stores_[lb_id] = {per_balancer_store.get()};
+ per_balancer_stores_[lb_id] = std::move(per_balancer_store);
+}
+
+PerBalancerStore* LoadDataStore::FindPerBalancerStore(
+ const string& hostname, const string& lb_id) const {
+ auto it = per_host_stores_.find(hostname);
+ if (it != per_host_stores_.end()) {
+ const PerHostStore& per_host_store = it->second;
+ return per_host_store.FindPerBalancerStore(lb_id);
+ } else {
+ return nullptr;
+ }
+}
+
void LoadDataStore::MergeRow(const TString& hostname,
- const LoadRecordKey& key,
- const LoadRecordValue& value) {
- PerBalancerStore* per_balancer_store =
- FindPerBalancerStore(hostname, key.lb_id());
- if (per_balancer_store != nullptr) {
- per_balancer_store->MergeRow(key, value);
- return;
- }
- // Unknown LB ID. Track it until its number of in-progress calls drops to
- // zero.
- int64_t in_progress_delta = value.GetNumCallsInProgressDelta();
- if (in_progress_delta != 0) {
- auto it_tracker = unknown_balancer_id_trackers_.find(key.lb_id());
- if (it_tracker == unknown_balancer_id_trackers_.end()) {
- gpr_log(
- GPR_DEBUG,
- "[LoadDataStore %p] Start tracking unknown balancer (lb_id_: %s).",
- this, key.lb_id().c_str());
- unknown_balancer_id_trackers_.insert(
- {key.lb_id(), static_cast<uint64_t>(in_progress_delta)});
- } else if ((it_tracker->second += in_progress_delta) == 0) {
- unknown_balancer_id_trackers_.erase(it_tracker);
- gpr_log(GPR_DEBUG,
- "[LoadDataStore %p] Stop tracking unknown balancer (lb_id_: %s).",
- this, key.lb_id().c_str());
- }
- }
-}
-
-const std::set<PerBalancerStore*>* LoadDataStore::GetAssignedStores(
+ const LoadRecordKey& key,
+ const LoadRecordValue& value) {
+ PerBalancerStore* per_balancer_store =
+ FindPerBalancerStore(hostname, key.lb_id());
+ if (per_balancer_store != nullptr) {
+ per_balancer_store->MergeRow(key, value);
+ return;
+ }
+ // Unknown LB ID. Track it until its number of in-progress calls drops to
+ // zero.
+ int64_t in_progress_delta = value.GetNumCallsInProgressDelta();
+ if (in_progress_delta != 0) {
+ auto it_tracker = unknown_balancer_id_trackers_.find(key.lb_id());
+ if (it_tracker == unknown_balancer_id_trackers_.end()) {
+ gpr_log(
+ GPR_DEBUG,
+ "[LoadDataStore %p] Start tracking unknown balancer (lb_id_: %s).",
+ this, key.lb_id().c_str());
+ unknown_balancer_id_trackers_.insert(
+ {key.lb_id(), static_cast<uint64_t>(in_progress_delta)});
+ } else if ((it_tracker->second += in_progress_delta) == 0) {
+ unknown_balancer_id_trackers_.erase(it_tracker);
+ gpr_log(GPR_DEBUG,
+ "[LoadDataStore %p] Stop tracking unknown balancer (lb_id_: %s).",
+ this, key.lb_id().c_str());
+ }
+ }
+}
+
+const std::set<PerBalancerStore*>* LoadDataStore::GetAssignedStores(
const TString& hostname, const TString& lb_id) {
- auto it = per_host_stores_.find(hostname);
- if (it == per_host_stores_.end()) return nullptr;
- return it->second.GetAssignedStores(lb_id);
-}
-
+ auto it = per_host_stores_.find(hostname);
+ if (it == per_host_stores_.end()) return nullptr;
+ return it->second.GetAssignedStores(lb_id);
+}
+
void LoadDataStore::ReportStreamCreated(const TString& hostname,
const TString& lb_id,
const TString& load_key) {
- per_host_stores_[hostname].ReportStreamCreated(lb_id, load_key);
-}
-
+ per_host_stores_[hostname].ReportStreamCreated(lb_id, load_key);
+}
+
void LoadDataStore::ReportStreamClosed(const TString& hostname,
const TString& lb_id) {
- auto it_per_host_store = per_host_stores_.find(hostname);
- GPR_ASSERT(it_per_host_store != per_host_stores_.end());
- it_per_host_store->second.ReportStreamClosed(lb_id);
-}
-
-} // namespace load_reporter
-} // namespace grpc
+ auto it_per_host_store = per_host_stores_.find(hostname);
+ GPR_ASSERT(it_per_host_store != per_host_stores_.end());
+ it_per_host_store->second.ReportStreamClosed(lb_id);
+}
+
+} // namespace load_reporter
+} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h
index 61ba618331a..362dbd66f71 100644
--- a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h
+++ b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h
@@ -1,161 +1,161 @@
-/*
- *
- * 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_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_DATA_STORE_H
-#define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_DATA_STORE_H
-
-#include <grpc/support/port_platform.h>
-
-#include <memory>
-#include <set>
-#include <unordered_map>
-
-#include <grpc/support/log.h>
-#include <grpcpp/impl/codegen/config.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_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_DATA_STORE_H
+#define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_DATA_STORE_H
+
+#include <grpc/support/port_platform.h>
+
+#include <memory>
+#include <set>
+#include <unordered_map>
+
+#include <grpc/support/log.h>
+#include <grpcpp/impl/codegen/config.h>
+
#include "src/cpp/server/load_reporter/constants.h"
#include <util/string/cast.h>
-namespace grpc {
-namespace load_reporter {
-
-// The load data storage is organized in hierarchy. The LoadDataStore is the
-// top-level data store. In LoadDataStore, for each host we keep a
-// PerHostStore, in which for each balancer we keep a PerBalancerStore. Each
-// PerBalancerStore maintains a map of load records, mapping from LoadRecordKey
-// to LoadRecordValue. The LoadRecordValue contains a map of customized call
-// metrics, mapping from a call metric name to the CallMetricValue.
-
-// The value of a customized call metric.
-class CallMetricValue {
- public:
- explicit CallMetricValue(uint64_t num_calls = 0,
- double total_metric_value = 0)
- : num_calls_(num_calls), total_metric_value_(total_metric_value) {}
-
- void MergeFrom(CallMetricValue other) {
- num_calls_ += other.num_calls_;
- total_metric_value_ += other.total_metric_value_;
- }
-
- // Getters.
- uint64_t num_calls() const { return num_calls_; }
- double total_metric_value() const { return total_metric_value_; }
-
- private:
- // The number of calls that finished with this metric.
- uint64_t num_calls_ = 0;
- // The sum of metric values across all the calls that finished with this
- // metric.
- double total_metric_value_ = 0;
-};
-
-// The key of a load record.
-class LoadRecordKey {
- public:
+namespace grpc {
+namespace load_reporter {
+
+// The load data storage is organized in hierarchy. The LoadDataStore is the
+// top-level data store. In LoadDataStore, for each host we keep a
+// PerHostStore, in which for each balancer we keep a PerBalancerStore. Each
+// PerBalancerStore maintains a map of load records, mapping from LoadRecordKey
+// to LoadRecordValue. The LoadRecordValue contains a map of customized call
+// metrics, mapping from a call metric name to the CallMetricValue.
+
+// The value of a customized call metric.
+class CallMetricValue {
+ public:
+ explicit CallMetricValue(uint64_t num_calls = 0,
+ double total_metric_value = 0)
+ : num_calls_(num_calls), total_metric_value_(total_metric_value) {}
+
+ void MergeFrom(CallMetricValue other) {
+ num_calls_ += other.num_calls_;
+ total_metric_value_ += other.total_metric_value_;
+ }
+
+ // Getters.
+ uint64_t num_calls() const { return num_calls_; }
+ double total_metric_value() const { return total_metric_value_; }
+
+ private:
+ // The number of calls that finished with this metric.
+ uint64_t num_calls_ = 0;
+ // The sum of metric values across all the calls that finished with this
+ // metric.
+ double total_metric_value_ = 0;
+};
+
+// The key of a load record.
+class LoadRecordKey {
+ public:
LoadRecordKey(TString lb_id, TString lb_tag, TString user_id,
TString client_ip_hex)
- : lb_id_(std::move(lb_id)),
- lb_tag_(std::move(lb_tag)),
- user_id_(std::move(user_id)),
- client_ip_hex_(std::move(client_ip_hex)) {}
-
+ : lb_id_(std::move(lb_id)),
+ lb_tag_(std::move(lb_tag)),
+ user_id_(std::move(user_id)),
+ client_ip_hex_(std::move(client_ip_hex)) {}
+
// Parses the input client_ip_and_token to set client IP, LB ID, and LB tag.
LoadRecordKey(const TString& client_ip_and_token, TString user_id);
TString ToString() const {
- return "[lb_id_=" + lb_id_ + ", lb_tag_=" + lb_tag_ +
- ", user_id_=" + user_id_ + ", client_ip_hex_=" + client_ip_hex_ +
- "]";
- }
-
- bool operator==(const LoadRecordKey& other) const {
- return lb_id_ == other.lb_id_ && lb_tag_ == other.lb_tag_ &&
- user_id_ == other.user_id_ && client_ip_hex_ == other.client_ip_hex_;
- }
-
+ return "[lb_id_=" + lb_id_ + ", lb_tag_=" + lb_tag_ +
+ ", user_id_=" + user_id_ + ", client_ip_hex_=" + client_ip_hex_ +
+ "]";
+ }
+
+ bool operator==(const LoadRecordKey& other) const {
+ return lb_id_ == other.lb_id_ && lb_tag_ == other.lb_tag_ &&
+ user_id_ == other.user_id_ && client_ip_hex_ == other.client_ip_hex_;
+ }
+
// Gets the client IP bytes in network order (i.e., big-endian).
TString GetClientIpBytes() const;
- // Getters.
+ // Getters.
const TString& lb_id() const { return lb_id_; }
const TString& lb_tag() const { return lb_tag_; }
const TString& user_id() const { return user_id_; }
const TString& client_ip_hex() const { return client_ip_hex_; }
-
- struct Hasher {
+
+ struct Hasher {
void hash_combine(size_t* seed, const TString& k) const {
*seed ^= std::hash<TString>()(k) + 0x9e3779b9 + (*seed << 6) +
- (*seed >> 2);
- }
-
- size_t operator()(const LoadRecordKey& k) const {
- size_t h = 0;
- hash_combine(&h, k.lb_id_);
- hash_combine(&h, k.lb_tag_);
- hash_combine(&h, k.user_id_);
- hash_combine(&h, k.client_ip_hex_);
- return h;
- }
- };
-
- private:
+ (*seed >> 2);
+ }
+
+ size_t operator()(const LoadRecordKey& k) const {
+ size_t h = 0;
+ hash_combine(&h, k.lb_id_);
+ hash_combine(&h, k.lb_tag_);
+ hash_combine(&h, k.user_id_);
+ hash_combine(&h, k.client_ip_hex_);
+ return h;
+ }
+ };
+
+ private:
TString lb_id_;
TString lb_tag_;
TString user_id_;
TString client_ip_hex_;
-};
-
-// The value of a load record.
-class LoadRecordValue {
- public:
- explicit LoadRecordValue(uint64_t start_count = 0, uint64_t ok_count = 0,
+};
+
+// The value of a load record.
+class LoadRecordValue {
+ public:
+ explicit LoadRecordValue(uint64_t start_count = 0, uint64_t ok_count = 0,
uint64_t error_count = 0, uint64_t bytes_sent = 0,
uint64_t bytes_recv = 0, uint64_t latency_ms = 0)
- : start_count_(start_count),
- ok_count_(ok_count),
- error_count_(error_count),
- bytes_sent_(bytes_sent),
- bytes_recv_(bytes_recv),
- latency_ms_(latency_ms) {}
-
+ : start_count_(start_count),
+ ok_count_(ok_count),
+ error_count_(error_count),
+ bytes_sent_(bytes_sent),
+ bytes_recv_(bytes_recv),
+ latency_ms_(latency_ms) {}
+
LoadRecordValue(TString metric_name, uint64_t num_calls,
double total_metric_value);
- void MergeFrom(const LoadRecordValue& other) {
- start_count_ += other.start_count_;
- ok_count_ += other.ok_count_;
- error_count_ += other.error_count_;
- bytes_sent_ += other.bytes_sent_;
- bytes_recv_ += other.bytes_recv_;
- latency_ms_ += other.latency_ms_;
- for (const auto& p : other.call_metrics_) {
+ void MergeFrom(const LoadRecordValue& other) {
+ start_count_ += other.start_count_;
+ ok_count_ += other.ok_count_;
+ error_count_ += other.error_count_;
+ bytes_sent_ += other.bytes_sent_;
+ bytes_recv_ += other.bytes_recv_;
+ latency_ms_ += other.latency_ms_;
+ for (const auto& p : other.call_metrics_) {
const TString& key = p.first;
- const CallMetricValue& value = p.second;
- call_metrics_[key].MergeFrom(value);
- }
- }
-
- int64_t GetNumCallsInProgressDelta() const {
- return static_cast<int64_t>(start_count_ - ok_count_ - error_count_);
- }
-
+ const CallMetricValue& value = p.second;
+ call_metrics_[key].MergeFrom(value);
+ }
+ }
+
+ int64_t GetNumCallsInProgressDelta() const {
+ return static_cast<int64_t>(start_count_ - ok_count_ - error_count_);
+ }
+
TString ToString() const {
return "[start_count_=" + ::ToString(start_count_) +
", ok_count_=" + ::ToString(ok_count_) +
@@ -164,185 +164,185 @@ class LoadRecordValue {
", bytes_recv_=" + ::ToString(bytes_recv_) +
", latency_ms_=" + ::ToString(latency_ms_) + ", " +
::ToString(call_metrics_.size()) + " other call metric(s)]";
- }
-
+ }
+
bool InsertCallMetric(const TString& metric_name,
- const CallMetricValue& metric_value) {
- return call_metrics_.insert({metric_name, metric_value}).second;
- }
-
- // Getters.
- uint64_t start_count() const { return start_count_; }
- uint64_t ok_count() const { return ok_count_; }
- uint64_t error_count() const { return error_count_; }
+ const CallMetricValue& metric_value) {
+ return call_metrics_.insert({metric_name, metric_value}).second;
+ }
+
+ // Getters.
+ uint64_t start_count() const { return start_count_; }
+ uint64_t ok_count() const { return ok_count_; }
+ uint64_t error_count() const { return error_count_; }
uint64_t bytes_sent() const { return bytes_sent_; }
uint64_t bytes_recv() const { return bytes_recv_; }
uint64_t latency_ms() const { return latency_ms_; }
const std::unordered_map<TString, CallMetricValue>& call_metrics() const {
- return call_metrics_;
- }
-
- private:
- uint64_t start_count_ = 0;
- uint64_t ok_count_ = 0;
- uint64_t error_count_ = 0;
+ return call_metrics_;
+ }
+
+ private:
+ uint64_t start_count_ = 0;
+ uint64_t ok_count_ = 0;
+ uint64_t error_count_ = 0;
uint64_t bytes_sent_ = 0;
uint64_t bytes_recv_ = 0;
uint64_t latency_ms_ = 0;
std::unordered_map<TString, CallMetricValue> call_metrics_;
-};
-
-// Stores the data associated with a particular LB ID.
-class PerBalancerStore {
- public:
- using LoadRecordMap =
- std::unordered_map<LoadRecordKey, LoadRecordValue, LoadRecordKey::Hasher>;
-
+};
+
+// Stores the data associated with a particular LB ID.
+class PerBalancerStore {
+ public:
+ using LoadRecordMap =
+ std::unordered_map<LoadRecordKey, LoadRecordValue, LoadRecordKey::Hasher>;
+
PerBalancerStore(TString lb_id, TString load_key)
- : lb_id_(std::move(lb_id)), load_key_(std::move(load_key)) {}
-
- // Merge a load record with the given key and value if the store is not
- // suspended.
- void MergeRow(const LoadRecordKey& key, const LoadRecordValue& value);
-
- // Suspend this store, so that no detailed load data will be recorded.
- void Suspend();
- // Resume this store from suspension.
- void Resume();
- // Is this store suspended or not?
- bool IsSuspended() const { return suspended_; }
-
- bool IsNumCallsInProgressChangedSinceLastReport() const {
- return num_calls_in_progress_ != last_reported_num_calls_in_progress_;
- }
-
- uint64_t GetNumCallsInProgressForReport();
-
+ : lb_id_(std::move(lb_id)), load_key_(std::move(load_key)) {}
+
+ // Merge a load record with the given key and value if the store is not
+ // suspended.
+ void MergeRow(const LoadRecordKey& key, const LoadRecordValue& value);
+
+ // Suspend this store, so that no detailed load data will be recorded.
+ void Suspend();
+ // Resume this store from suspension.
+ void Resume();
+ // Is this store suspended or not?
+ bool IsSuspended() const { return suspended_; }
+
+ bool IsNumCallsInProgressChangedSinceLastReport() const {
+ return num_calls_in_progress_ != last_reported_num_calls_in_progress_;
+ }
+
+ uint64_t GetNumCallsInProgressForReport();
+
TString ToString() {
- return "[PerBalancerStore lb_id_=" + lb_id_ + " load_key_=" + load_key_ +
- "]";
- }
-
- void ClearLoadRecordMap() { load_record_map_.clear(); }
-
- // Getters.
+ return "[PerBalancerStore lb_id_=" + lb_id_ + " load_key_=" + load_key_ +
+ "]";
+ }
+
+ void ClearLoadRecordMap() { load_record_map_.clear(); }
+
+ // Getters.
const TString& lb_id() const { return lb_id_; }
const TString& load_key() const { return load_key_; }
- const LoadRecordMap& load_record_map() const { return load_record_map_; }
-
- private:
+ const LoadRecordMap& load_record_map() const { return load_record_map_; }
+
+ private:
TString lb_id_;
- // TODO(juanlishen): Use bytestring protobuf type?
+ // TODO(juanlishen): Use bytestring protobuf type?
TString load_key_;
- LoadRecordMap load_record_map_;
- uint64_t num_calls_in_progress_ = 0;
- uint64_t last_reported_num_calls_in_progress_ = 0;
- bool suspended_ = false;
-};
-
-// Stores the data associated with a particular host.
-class PerHostStore {
- public:
- // When a report stream is created, a PerBalancerStore is created for the
- // LB ID (guaranteed unique) associated with that stream. If it is the only
- // active store, adopt all the orphaned stores. If it is the first created
- // store, adopt the store of kInvalidLbId.
+ LoadRecordMap load_record_map_;
+ uint64_t num_calls_in_progress_ = 0;
+ uint64_t last_reported_num_calls_in_progress_ = 0;
+ bool suspended_ = false;
+};
+
+// Stores the data associated with a particular host.
+class PerHostStore {
+ public:
+ // When a report stream is created, a PerBalancerStore is created for the
+ // LB ID (guaranteed unique) associated with that stream. If it is the only
+ // active store, adopt all the orphaned stores. If it is the first created
+ // store, adopt the store of kInvalidLbId.
void ReportStreamCreated(const TString& lb_id,
const TString& load_key);
-
- // When a report stream is closed, the PerBalancerStores assigned to the
- // associate LB ID need to be re-assigned to other active balancers,
- // ideally with the same load key. If there is no active balancer, we have
- // to suspend those stores and drop the incoming load data until they are
- // resumed.
+
+ // When a report stream is closed, the PerBalancerStores assigned to the
+ // associate LB ID need to be re-assigned to other active balancers,
+ // ideally with the same load key. If there is no active balancer, we have
+ // to suspend those stores and drop the incoming load data until they are
+ // resumed.
void ReportStreamClosed(const TString& lb_id);
-
- // Returns null if not found. Caller doesn't own the returned store.
+
+ // Returns null if not found. Caller doesn't own the returned store.
PerBalancerStore* FindPerBalancerStore(const TString& lb_id) const;
-
- // Returns null if lb_id is not found. The returned pointer points to the
- // underlying data structure, which is not owned by the caller.
- const std::set<PerBalancerStore*>* GetAssignedStores(
+
+ // Returns null if lb_id is not found. The returned pointer points to the
+ // underlying data structure, which is not owned by the caller.
+ const std::set<PerBalancerStore*>* GetAssignedStores(
const TString& lb_id) const;
-
- private:
- // Creates a PerBalancerStore for the given LB ID, assigns the store to
- // itself, and records the LB ID to the load key.
+
+ private:
+ // Creates a PerBalancerStore for the given LB ID, assigns the store to
+ // itself, and records the LB ID to the load key.
void SetUpForNewLbId(const TString& lb_id, const TString& load_key);
-
- void AssignOrphanedStore(PerBalancerStore* orphaned_store,
+
+ void AssignOrphanedStore(PerBalancerStore* orphaned_store,
const TString& new_receiver);
-
+
std::unordered_map<TString, std::set<TString>>
- load_key_to_receiving_lb_ids_;
-
- // Key: LB ID. The key set includes all the LB IDs that have been
- // allocated for reporting streams so far.
- // Value: the unique pointer to the PerBalancerStore of the LB ID.
+ load_key_to_receiving_lb_ids_;
+
+ // Key: LB ID. The key set includes all the LB IDs that have been
+ // allocated for reporting streams so far.
+ // Value: the unique pointer to the PerBalancerStore of the LB ID.
std::unordered_map<TString, std::unique_ptr<PerBalancerStore>>
- per_balancer_stores_;
-
- // Key: LB ID. The key set includes the LB IDs of the balancers that are
- // currently receiving report.
- // Value: the set of raw pointers to the PerBalancerStores assigned to the LB
- // ID. Note that the sets in assigned_stores_ form a division of the value set
- // of per_balancer_stores_.
+ per_balancer_stores_;
+
+ // Key: LB ID. The key set includes the LB IDs of the balancers that are
+ // currently receiving report.
+ // Value: the set of raw pointers to the PerBalancerStores assigned to the LB
+ // ID. Note that the sets in assigned_stores_ form a division of the value set
+ // of per_balancer_stores_.
std::unordered_map<TString, std::set<PerBalancerStore*>> assigned_stores_;
-};
-
-// Thread-unsafe two-level bookkeeper of all the load data.
-// Note: We never remove any store objects from this class, as per the
-// current spec. That's because premature removal of the store objects
-// may lead to loss of critical information, e.g., mapping from lb_id to
-// load_key, and the number of in-progress calls. Such loss will cause
-// information inconsistency when the balancer is re-connected. Keeping
-// all the stores should be fine for PerHostStore, since we assume there
-// should only be a few hostnames. But it's a potential problem for
-// PerBalancerStore.
-class LoadDataStore {
- public:
- // Returns null if not found. Caller doesn't own the returned store.
+};
+
+// Thread-unsafe two-level bookkeeper of all the load data.
+// Note: We never remove any store objects from this class, as per the
+// current spec. That's because premature removal of the store objects
+// may lead to loss of critical information, e.g., mapping from lb_id to
+// load_key, and the number of in-progress calls. Such loss will cause
+// information inconsistency when the balancer is re-connected. Keeping
+// all the stores should be fine for PerHostStore, since we assume there
+// should only be a few hostnames. But it's a potential problem for
+// PerBalancerStore.
+class LoadDataStore {
+ public:
+ // Returns null if not found. Caller doesn't own the returned store.
PerBalancerStore* FindPerBalancerStore(const TString& hostname,
const TString& lb_id) const;
-
- // Returns null if hostname or lb_id is not found. The returned pointer points
- // to the underlying data structure, which is not owned by the caller.
- const std::set<PerBalancerStore*>* GetAssignedStores(const string& hostname,
- const string& lb_id);
-
- // If a PerBalancerStore can be found by the hostname and LB ID in
- // LoadRecordKey, the load data will be merged to that store. Otherwise,
- // only track the number of the in-progress calls for this unknown LB ID.
+
+ // Returns null if hostname or lb_id is not found. The returned pointer points
+ // to the underlying data structure, which is not owned by the caller.
+ const std::set<PerBalancerStore*>* GetAssignedStores(const string& hostname,
+ const string& lb_id);
+
+ // If a PerBalancerStore can be found by the hostname and LB ID in
+ // LoadRecordKey, the load data will be merged to that store. Otherwise,
+ // only track the number of the in-progress calls for this unknown LB ID.
void MergeRow(const TString& hostname, const LoadRecordKey& key,
- const LoadRecordValue& value);
-
- // Is the given lb_id a tracked unknown LB ID (i.e., the LB ID was associated
- // with some received load data but unknown to this load data store)?
+ const LoadRecordValue& value);
+
+ // Is the given lb_id a tracked unknown LB ID (i.e., the LB ID was associated
+ // with some received load data but unknown to this load data store)?
bool IsTrackedUnknownBalancerId(const TString& lb_id) const {
- return unknown_balancer_id_trackers_.find(lb_id) !=
- unknown_balancer_id_trackers_.end();
- }
-
- // Wrapper around PerHostStore::ReportStreamCreated.
+ return unknown_balancer_id_trackers_.find(lb_id) !=
+ unknown_balancer_id_trackers_.end();
+ }
+
+ // Wrapper around PerHostStore::ReportStreamCreated.
void ReportStreamCreated(const TString& hostname,
const TString& lb_id,
const TString& load_key);
-
- // Wrapper around PerHostStore::ReportStreamClosed.
+
+ // Wrapper around PerHostStore::ReportStreamClosed.
void ReportStreamClosed(const TString& hostname,
const TString& lb_id);
-
- private:
- // Buffered data that was fetched from Census but hasn't been sent to
- // balancer. We need to keep this data ourselves because Census will
- // delete the data once it's returned.
+
+ private:
+ // Buffered data that was fetched from Census but hasn't been sent to
+ // balancer. We need to keep this data ourselves because Census will
+ // delete the data once it's returned.
std::unordered_map<TString, PerHostStore> per_host_stores_;
-
- // Tracks the number of in-progress calls for each unknown LB ID.
+
+ // Tracks the number of in-progress calls for each unknown LB ID.
std::unordered_map<TString, uint64_t> unknown_balancer_id_trackers_;
-};
-
-} // namespace load_reporter
-} // namespace grpc
-
-#endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_DATA_STORE_H
+};
+
+} // namespace load_reporter
+} // namespace grpc
+
+#endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_LOAD_DATA_STORE_H
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 732602bcb70..aba2b139a42 100644
--- a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -20,24 +20,24 @@
#include <map>
#include <memory>
-#include <grpcpp/impl/codegen/slice.h>
+#include <grpcpp/impl/codegen/slice.h>
#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/security/auth_metadata_processor.h>
-
+#include <grpcpp/security/auth_metadata_processor.h>
+
#include "src/cpp/common/secure_auth_context.h"
#include "src/cpp/server/secure_server_credentials.h"
namespace grpc {
void AuthMetadataProcessorAyncWrapper::Destroy(void* wrapper) {
- auto* w = static_cast<AuthMetadataProcessorAyncWrapper*>(wrapper);
+ auto* w = static_cast<AuthMetadataProcessorAyncWrapper*>(wrapper);
delete w;
}
void AuthMetadataProcessorAyncWrapper::Process(
void* wrapper, grpc_auth_context* context, const grpc_metadata* md,
size_t num_md, grpc_process_auth_metadata_done_cb cb, void* user_data) {
- auto* w = static_cast<AuthMetadataProcessorAyncWrapper*>(wrapper);
+ auto* w = static_cast<AuthMetadataProcessorAyncWrapper*>(wrapper);
if (!w->processor_) {
// Early exit.
cb(user_data, nullptr, 0, nullptr, 0, GRPC_STATUS_OK, nullptr);
@@ -59,8 +59,8 @@ void AuthMetadataProcessorAyncWrapper::InvokeProcessor(
grpc_process_auth_metadata_done_cb cb, void* user_data) {
AuthMetadataProcessor::InputMetadata metadata;
for (size_t i = 0; i < num_md; i++) {
- metadata.insert(std::make_pair(StringRefFromSlice(&md[i].key),
- StringRefFromSlice(&md[i].value)));
+ metadata.insert(std::make_pair(StringRefFromSlice(&md[i].key),
+ StringRefFromSlice(&md[i].value)));
}
SecureAuthContext context(ctx);
AuthMetadataProcessor::OutputMetadata consumed_metadata;
@@ -125,19 +125,19 @@ std::shared_ptr<ServerCredentials> SslServerCredentials(
new SecureServerCredentials(c_creds));
}
-namespace experimental {
-
-std::shared_ptr<ServerCredentials> AltsServerCredentials(
+namespace experimental {
+
+std::shared_ptr<ServerCredentials> AltsServerCredentials(
const AltsServerCredentialsOptions& /* options */) {
- grpc_alts_credentials_options* c_options =
- grpc_alts_credentials_server_options_create();
- grpc_server_credentials* c_creds =
- grpc_alts_server_credentials_create(c_options);
- grpc_alts_credentials_options_destroy(c_options);
- return std::shared_ptr<ServerCredentials>(
- new SecureServerCredentials(c_creds));
-}
-
+ grpc_alts_credentials_options* c_options =
+ grpc_alts_credentials_server_options_create();
+ grpc_server_credentials* c_creds =
+ grpc_alts_server_credentials_create(c_options);
+ grpc_alts_credentials_options_destroy(c_options);
+ return std::shared_ptr<ServerCredentials>(
+ new SecureServerCredentials(c_creds));
+}
+
std::shared_ptr<ServerCredentials> LocalServerCredentials(
grpc_local_connect_type type) {
return std::shared_ptr<ServerCredentials>(
@@ -151,5 +151,5 @@ std::shared_ptr<ServerCredentials> TlsServerCredentials(
grpc_tls_server_credentials_create(options.c_credentials_options())));
}
-} // namespace experimental
+} // 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 9e3fb3f9ebf..ec5fbb59edd 100644
--- a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h
+++ b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,7 +21,7 @@
#include <memory>
-#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/security/server_credentials.h>
#include <grpcpp/security/tls_credentials_options.h>
#include <grpc/grpc_security.h>
diff --git a/contrib/libs/grpc/src/cpp/server/server_builder.cc b/contrib/libs/grpc/src/cpp/server/server_builder.cc
index 0cc00b365ff..c3851c279d4 100644
--- a/contrib/libs/grpc/src/cpp/server/server_builder.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_builder.cc
@@ -1,34 +1,34 @@
/*
*
- * Copyright 2015-2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/server_builder.h>
+#include <grpcpp/server_builder.h>
#include <grpc/support/cpu.h>
#include <grpc/support/log.h>
-#include <grpcpp/impl/service_type.h>
-#include <grpcpp/resource_quota.h>
-#include <grpcpp/server.h>
+#include <grpcpp/impl/service_type.h>
+#include <grpcpp/resource_quota.h>
+#include <grpcpp/server.h>
#include <utility>
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
+#include "src/core/lib/gpr/useful.h"
#include "src/cpp/server/external_connection_acceptor_impl.h"
#include "src/cpp/server/thread_pool_interface.h"
@@ -207,11 +207,11 @@ ServerBuilder& ServerBuilder::AddListeningPort(
int* selected_port) {
const TString uri_scheme = "dns:";
TString addr = addr_uri;
- if (addr_uri.compare(0, uri_scheme.size(), uri_scheme) == 0) {
- size_t pos = uri_scheme.size();
- while (addr_uri[pos] == '/') ++pos; // Skip slashes.
- addr = addr_uri.substr(pos);
- }
+ if (addr_uri.compare(0, uri_scheme.size(), uri_scheme) == 0) {
+ size_t pos = uri_scheme.size();
+ while (addr_uri[pos] == '/') ++pos; // Skip slashes.
+ addr = addr_uri.substr(pos);
+ }
Port port = {addr, std::move(creds), selected_port};
ports_.push_back(port);
return *this;
@@ -285,9 +285,9 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
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_) {
@@ -297,12 +297,12 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
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;
+ grpc_cq_polling_type polling_type =
+ is_hybrid_server ? GRPC_CQ_NON_POLLING : GRPC_CQ_DEFAULT_POLLING;
// Create completion queues to listen to incoming rpc requests
for (int i = 0; i < sync_server_settings_.num_cqs; i++) {
@@ -314,16 +314,16 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
// TODO(vjpai): Add a section here for plugins once they can support callback
// methods
- if (has_sync_methods) {
- // This is a Sync server
- gpr_log(GPR_INFO,
- "Synchronous server. Num CQs: %d, Min pollers: %d, Max Pollers: "
- "%d, CQ timeout (msec): %d",
- sync_server_settings_.num_cqs, sync_server_settings_.min_pollers,
- sync_server_settings_.max_pollers,
- sync_server_settings_.cq_timeout_msec);
- }
-
+ if (has_sync_methods) {
+ // This is a Sync server
+ gpr_log(GPR_INFO,
+ "Synchronous server. Num CQs: %d, Min pollers: %d, Max Pollers: "
+ "%d, CQ timeout (msec): %d",
+ sync_server_settings_.num_cqs, sync_server_settings_.min_pollers,
+ sync_server_settings_.max_pollers,
+ sync_server_settings_.cq_timeout_msec);
+ }
+
if (has_callback_methods) {
gpr_log(GPR_INFO, "Callback server.");
}
@@ -396,17 +396,17 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
for (auto& port : ports_) {
int r = server->AddListeningPort(port.addr, port.creds.get());
- if (!r) {
+ if (!r) {
server->Shutdown();
- return nullptr;
- }
+ return nullptr;
+ }
if (port.selected_port != nullptr) {
*port.selected_port = r;
}
}
auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0];
- server->Start(cqs_data, cqs_.size());
+ server->Start(cqs_data, cqs_.size());
for (const auto& value : plugins_) {
value->Finish(initializer);
@@ -421,14 +421,14 @@ void ServerBuilder::InternalAddPluginFactory(
(*g_plugin_factory_list).push_back(CreatePlugin);
}
-ServerBuilder& ServerBuilder::EnableWorkaround(grpc_workaround_list id) {
- switch (id) {
- case GRPC_WORKAROUND_ID_CRONET_COMPRESSION:
- return AddChannelArgument(GRPC_ARG_WORKAROUND_CRONET_COMPRESSION, 1);
- default:
- gpr_log(GPR_ERROR, "Workaround %u does not exist or is obsolete.", id);
- return *this;
- }
-}
-
+ServerBuilder& ServerBuilder::EnableWorkaround(grpc_workaround_list id) {
+ switch (id) {
+ case GRPC_WORKAROUND_ID_CRONET_COMPRESSION:
+ return AddChannelArgument(GRPC_ARG_WORKAROUND_CRONET_COMPRESSION, 1);
+ default:
+ gpr_log(GPR_ERROR, "Workaround %u does not exist or is obsolete.", id);
+ return *this;
+ }
+}
+
} // 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 c2a911c7f7c..06507da0b93 100644
--- a/contrib/libs/grpc/src/cpp/server/server_cc.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_cc.cc
@@ -1,23 +1,23 @@
/*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/server.h>
+#include <grpcpp/server.h>
-#include <cstdlib>
+#include <cstdlib>
#include <sstream>
#include <type_traits>
#include <utility>
@@ -26,37 +26,37 @@
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-#include <grpcpp/completion_queue.h>
-#include <grpcpp/generic/async_generic_service.h>
-#include <grpcpp/impl/codegen/async_unary_call.h>
+#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/call.h>
-#include <grpcpp/impl/codegen/completion_queue_tag.h>
+#include <grpcpp/impl/codegen/completion_queue_tag.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>
-#include <grpcpp/impl/server_initializer.h>
-#include <grpcpp/impl/service_type.h>
-#include <grpcpp/security/server_credentials.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/time.h>
-
-#include "src/core/ext/transport/inproc/inproc_transport.h"
+#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/impl/rpc_service_method.h>
+#include <grpcpp/impl/server_initializer.h>
+#include <grpcpp/impl/service_type.h>
+#include <grpcpp/security/server_credentials.h>
+#include <grpcpp/server_context.h>
+#include <grpcpp/support/time.h>
+
+#include "src/core/ext/transport/inproc/inproc_transport.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/profiling/timers.h"
-#include "src/core/lib/surface/call.h"
+#include "src/core/lib/surface/call.h"
#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/client/create_channel_internal.h"
#include "src/cpp/server/external_connection_acceptor_impl.h"
-#include "src/cpp/server/health/default_health_check_service.h"
+#include "src/cpp/server/health/default_health_check_service.h"
#include "src/cpp/thread_manager/thread_manager.h"
#include <util/stream/str.h>
namespace grpc {
-namespace {
+namespace {
// The default value for maximum number of threads that can be created in the
// sync server. This value of INT_MAX is chosen to match the default behavior if
@@ -72,26 +72,26 @@ class DefaultGlobalCallbacks final : public Server::GlobalCallbacks {
void PostSynchronousRequest(ServerContext* /*context*/) override {}
};
-std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
-gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
+std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
+gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
-void InitGlobalCallbacks() {
+void InitGlobalCallbacks() {
if (!g_callbacks) {
g_callbacks.reset(new DefaultGlobalCallbacks());
}
}
-class ShutdownTag : public internal::CompletionQueueTag {
- public:
+class ShutdownTag : public internal::CompletionQueueTag {
+ public:
bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return false; }
-};
-
-class DummyTag : public internal::CompletionQueueTag {
- public:
+};
+
+class DummyTag : public internal::CompletionQueueTag {
+ public:
bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return true; }
-};
-
-class UnimplementedAsyncRequestContext {
+};
+
+class UnimplementedAsyncRequestContext {
protected:
UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
@@ -108,8 +108,8 @@ using ::grpc::experimental::CallbackServerContext;
using ::grpc::experimental::GenericCallbackServerContext;
#endif
-} // namespace
-
+} // namespace
+
ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
ServerInterface* server, ServerContext* context,
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
@@ -285,10 +285,10 @@ class ShutdownCallback : public grpc_experimental_completion_queue_functor {
};
} // 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.
+/// 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,
public GenericAsyncRequest {
@@ -304,8 +304,8 @@ class Server::UnimplementedAsyncRequest final
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
+/// 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,
@@ -323,7 +323,7 @@ class Server::UnimplementedAsyncResponse final
} else {
// The tag was swallowed due to interception. We will see it again.
}
- return false;
+ return false;
}
private:
@@ -352,7 +352,7 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
grpc_metadata_array_destroy(&request_metadata_);
}
- void SetupRequest() { cq_ = grpc_completion_queue_create_for_pluck(nullptr); }
+ void SetupRequest() { cq_ = grpc_completion_queue_create_for_pluck(nullptr); }
void TeardownRequest() {
grpc_completion_queue_destroy(cq_);
@@ -365,22 +365,22 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
if (method_tag_) {
if (grpc_server_request_registered_call(
server, method_tag_, &call_, &deadline_, &request_metadata_,
- has_request_payload_ ? &request_payload_ : nullptr, cq_,
+ has_request_payload_ ? &request_payload_ : nullptr, cq_,
notify_cq, this) != GRPC_CALL_OK) {
- TeardownRequest();
- return;
- }
+ TeardownRequest();
+ return;
+ }
} else {
if (!call_details_) {
call_details_ = new grpc_call_details;
grpc_call_details_init(call_details_);
}
- if (grpc_server_request_call(server, &call_, call_details_,
- &request_metadata_, cq_, notify_cq,
- this) != GRPC_CALL_OK) {
- TeardownRequest();
- return;
- }
+ if (grpc_server_request_call(server, &call_, call_details_,
+ &request_metadata_, cq_, notify_cq,
+ this) != GRPC_CALL_OK) {
+ TeardownRequest();
+ return;
+ }
}
}
@@ -415,7 +415,7 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
public:
explicit CallData(Server* server, SyncRequest* mrd)
: cq_(mrd->cq_),
- ctx_(mrd->deadline_, &mrd->request_metadata_),
+ ctx_(mrd->deadline_, &mrd->request_metadata_),
has_request_payload_(mrd->has_request_payload_),
request_payload_(has_request_payload_ ? mrd->request_payload_
: nullptr),
@@ -445,7 +445,7 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
bool resources) {
global_callbacks_ = global_callbacks;
resources_ = resources;
-
+
interceptor_methods_.SetCall(&call_);
interceptor_methods_.SetReverse();
// Set interception point for RECV INITIAL METADATA
@@ -453,14 +453,14 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
grpc::experimental::InterceptionHookPoints::
POST_RECV_INITIAL_METADATA);
interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_);
-
+
if (has_request_payload_) {
// Set interception point for RECV MESSAGE
auto* handler = resources_ ? method_->handler()
: server_->resource_exhausted_handler_.get();
request_ = handler->Deserialize(call_.call(), request_payload_,
&request_status_, nullptr);
-
+
request_payload_ = nullptr;
interceptor_methods_.AddInterceptionHookPoint(
grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
@@ -760,11 +760,11 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager {
WorkStatus PollForWork(void** tag, bool* ok) override {
*tag = nullptr;
- // TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working
- // right now
+ // TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working
+ // right now
gpr_timespec deadline =
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
+ gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
+ gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
switch (server_cq_->AsyncNext(tag, ok, deadline)) {
case grpc::CompletionQueue::TIMEOUT:
@@ -792,10 +792,10 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager {
// Calldata takes ownership of the completion queue and interceptors
// inside sync_req
auto* cd = new SyncRequest::CallData(server_, sync_req);
- // Prepare for the next request
- if (!IsShutdown()) {
- sync_req->SetupRequest(); // Create new completion queue for sync_req
- sync_req->Request(server_->c_server(), server_cq_->cq());
+ // Prepare for the next request
+ if (!IsShutdown()) {
+ sync_req->SetupRequest(); // Create new completion queue for sync_req
+ sync_req->Request(server_->c_server(), server_cq_->cq());
}
GPR_TIMER_SCOPE("cd.Run()", 0);
@@ -820,13 +820,13 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager {
}
}
- void Shutdown() override {
- ThreadManager::Shutdown();
+ void Shutdown() override {
+ ThreadManager::Shutdown();
server_cq_->Shutdown();
- }
+ }
- void Wait() override {
- ThreadManager::Wait();
+ void Wait() override {
+ ThreadManager::Wait();
// Drain any pending items from the queue
void* tag;
bool ok;
@@ -886,13 +886,13 @@ Server::Server(
shutdown_notified_(false),
server_(nullptr),
server_initializer_(new ServerInitializer(this)),
- health_check_service_disabled_(false) {
+ health_check_service_disabled_(false) {
g_gli_initializer.summon();
gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks);
global_callbacks_ = grpc::g_callbacks;
global_callbacks_->UpdateArguments(args);
- if (sync_server_cqs_ != nullptr) {
+ if (sync_server_cqs_ != nullptr) {
bool default_rq_created = false;
if (server_rq == nullptr) {
server_rq = grpc_resource_quota_create("SyncServer-default-rq");
@@ -901,11 +901,11 @@ Server::Server(
default_rq_created = true;
}
- for (const auto& it : *sync_server_cqs_) {
- sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
+ for (const auto& it : *sync_server_cqs_) {
+ sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
this, it.get(), global_callbacks_, server_rq, min_pollers,
max_pollers, sync_cq_timeout_msec));
- }
+ }
if (default_rq_created) {
grpc_resource_quota_unref(server_rq);
@@ -919,22 +919,22 @@ Server::Server(
grpc_channel_args channel_args;
args->SetChannelArgs(&channel_args);
- for (size_t i = 0; i < channel_args.num_args; i++) {
+ for (size_t i = 0; i < channel_args.num_args; i++) {
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 {
+ 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));
- }
- }
+ }
+ }
if (0 ==
strcmp(channel_args.args[i].key, GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH)) {
max_receive_message_size_ = channel_args.args[i].value.integer;
}
- }
+ }
server_ = grpc_server_create(&channel_args, nullptr);
}
@@ -972,13 +972,13 @@ grpc_server* Server::c_server() { return server_; }
std::shared_ptr<grpc::Channel> Server::InProcessChannel(
const grpc::ChannelArguments& args) {
- grpc_channel_args channel_args = args.c_channel_args();
+ grpc_channel_args channel_args = args.c_channel_args();
return grpc::CreateChannelInternal(
"inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr),
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>());
-}
-
+}
+
std::shared_ptr<grpc::Channel>
Server::experimental_type::InProcessChannelWithInterceptors(
const grpc::ChannelArguments& args,
@@ -1091,9 +1091,9 @@ void Server::RegisterCallbackGenericService(
int Server::AddListeningPort(const TString& addr,
grpc::ServerCredentials* creds) {
GPR_ASSERT(!started_);
- int port = creds->AddPortToServer(addr, server_);
- global_callbacks_->AddPort(this, addr, creds, port);
- return port;
+ int port = creds->AddPortToServer(addr, server_);
+ global_callbacks_->AddPort(this, addr, creds, port);
+ return port;
}
void Server::Ref() {
@@ -1123,15 +1123,15 @@ void Server::UnrefAndWaitLocked() {
void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
GPR_ASSERT(!started_);
- global_callbacks_->PreServerStart(this);
+ global_callbacks_->PreServerStart(this);
started_ = true;
-
- // Only create default health check service when user did not provide an
- // explicit one.
+
+ // Only create default health check service when user did not provide an
+ // explicit one.
grpc::ServerCompletionQueue* health_check_cq = nullptr;
grpc::DefaultHealthCheckService::HealthCheckServiceImpl*
default_health_check_service_impl = nullptr;
- if (health_check_service_ == nullptr && !health_check_service_disabled_ &&
+ if (health_check_service_ == nullptr && !health_check_service_disabled_ &&
grpc::DefaultHealthCheckServiceEnabled()) {
auto* default_hc_service = new grpc::DefaultHealthCheckService;
health_check_service_.reset(default_hc_service);
@@ -1147,8 +1147,8 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
default_hc_service->GetHealthCheckService(
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_);
}
diff --git a/contrib/libs/grpc/src/cpp/server/server_context.cc b/contrib/libs/grpc/src/cpp/server/server_context.cc
index 458ac20d87c..e81b87723d4 100644
--- a/contrib/libs/grpc/src/cpp/server/server_context.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_context.cc
@@ -1,35 +1,35 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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_context.h>
-#include <algorithm>
-#include <utility>
+#include <algorithm>
+#include <utility>
#include <grpc/compression.h>
#include <grpc/grpc.h>
-#include <grpc/load_reporting.h>
+#include <grpc/load_reporting.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
-#include <grpcpp/impl/call.h>
+#include <grpcpp/impl/call.h>
#include <grpcpp/impl/codegen/completion_queue.h>
#include <grpcpp/support/server_callback.h>
-#include <grpcpp/support/time.h>
+#include <grpcpp/support/time.h>
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/sync.h"
@@ -228,7 +228,7 @@ ServerContextBase::ServerContextBase()
ServerContextBase::ServerContextBase(gpr_timespec deadline,
grpc_metadata_array* arr)
: deadline_(deadline) {
- std::swap(*client_metadata_.arr(), *arr);
+ std::swap(*client_metadata_.arr(), *arr);
}
void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline,
@@ -281,8 +281,8 @@ void ServerContextBase::BeginCompletionOp(
internal::CompletionQueueTag* ServerContextBase::GetCompletionOpTag() {
return static_cast<internal::CompletionQueueTag*>(completion_op_);
-}
-
+}
+
void ServerContextBase::AddInitialMetadata(const TString& key,
const TString& value) {
initial_metadata_.insert(std::make_pair(key, value));
@@ -324,14 +324,14 @@ bool ServerContextBase::IsCancelled() const {
void ServerContextBase::set_compression_algorithm(
grpc_compression_algorithm algorithm) {
- compression_algorithm_ = algorithm;
- const char* algorithm_name = nullptr;
+ compression_algorithm_ = algorithm;
+ const char* algorithm_name = nullptr;
if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) {
gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.",
algorithm);
abort();
}
- GPR_ASSERT(algorithm_name != nullptr);
+ GPR_ASSERT(algorithm_name != nullptr);
AddInitialMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name);
}
@@ -353,9 +353,9 @@ const struct census_context* ServerContextBase::census_context() const {
void ServerContextBase::SetLoadReportingCosts(
const std::vector<TString>& cost_data) {
if (call_.call == nullptr) return;
- for (const auto& cost_datum : cost_data) {
- AddTrailingMetadata(GRPC_LB_COST_MD_KEY, cost_datum);
- }
-}
-
+ for (const auto& cost_datum : cost_data) {
+ AddTrailingMetadata(GRPC_LB_COST_MD_KEY, cost_datum);
+ }
+}
+
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/server/server_credentials.cc b/contrib/libs/grpc/src/cpp/server/server_credentials.cc
index c3b3a8b3793..8197bc22ec3 100644
--- a/contrib/libs/grpc/src/cpp/server/server_credentials.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_credentials.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/cpp/server/server_posix.cc b/contrib/libs/grpc/src/cpp/server/server_posix.cc
index c3d40d4fa2d..f0ca1a60daa 100644
--- a/contrib/libs/grpc/src/cpp/server/server_posix.cc
+++ b/contrib/libs/grpc/src/cpp/server/server_posix.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/server_posix.h>
+#include <grpcpp/server_posix.h>
#include <grpc/grpc_posix.h>
@@ -25,7 +25,7 @@ namespace grpc {
#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
void AddInsecureChannelFromFd(grpc::Server* server, int fd) {
- grpc_server_add_insecure_channel_from_fd(server->c_server(), nullptr, fd);
+ grpc_server_add_insecure_channel_from_fd(server->c_server(), nullptr, fd);
}
#endif // GPR_SUPPORT_CHANNELS_FROM_FD
diff --git a/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h b/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h
index 028842a776f..8c901ce9773 100644
--- a/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h
+++ b/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -32,10 +32,10 @@ class ThreadPoolInterface {
virtual void Add(const std::function<void()>& callback) = 0;
};
-// Allows different codebases to use their own thread pool impls
-typedef ThreadPoolInterface* (*CreateThreadPoolFunc)(void);
-void SetCreateThreadPool(CreateThreadPoolFunc func);
-
+// Allows different codebases to use their own thread pool impls
+typedef ThreadPoolInterface* (*CreateThreadPoolFunc)(void);
+void SetCreateThreadPool(CreateThreadPoolFunc func);
+
ThreadPoolInterface* CreateDefaultThreadPool();
} // namespace grpc
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 c8560aa81dd..db174086fd5 100644
--- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc
+++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -21,33 +21,33 @@
#include <climits>
#include <grpc/support/log.h>
-#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/exec_ctx.h"
-
+
namespace grpc {
ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr)
- : thd_mgr_(thd_mgr) {
- // Make thread creation exclusive with respect to its join happening in
- // ~WorkerThread().
- thd_ = grpc_core::Thread(
- "grpcpp_sync_server",
- [](void* th) { static_cast<ThreadManager::WorkerThread*>(th)->Run(); },
+ : thd_mgr_(thd_mgr) {
+ // Make thread creation exclusive with respect to its join happening in
+ // ~WorkerThread().
+ 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");
}
-}
+}
void ThreadManager::WorkerThread::Run() {
thd_mgr_->MainWorkLoop();
thd_mgr_->MarkAsCompleted(this);
}
-ThreadManager::WorkerThread::~WorkerThread() {
- // Don't join until the thread is fully constructed.
- thd_.Join();
-}
+ThreadManager::WorkerThread::~WorkerThread() {
+ // Don't join until the thread is fully constructed.
+ thd_.Join();
+}
ThreadManager::ThreadManager(const char* name,
grpc_resource_quota* resource_quota,
@@ -113,14 +113,14 @@ void ThreadManager::MarkAsCompleted(WorkerThread* thd) {
}
void ThreadManager::CleanupCompletedThreads() {
- std::list<WorkerThread*> completed_threads;
- {
- // swap out the completed threads list: allows other threads to clean up
- // more quickly
+ std::list<WorkerThread*> completed_threads;
+ {
+ // swap out the completed threads list: allows other threads to clean up
+ // more quickly
grpc_core::MutexLock lock(&list_mu_);
- completed_threads.swap(completed_threads_);
+ completed_threads.swap(completed_threads_);
}
- for (auto thd : completed_threads) delete thd;
+ for (auto thd : completed_threads) delete thd;
}
void ThreadManager::Initialize() {
@@ -132,14 +132,14 @@ void ThreadManager::Initialize() {
abort();
}
- {
+ {
grpc_core::MutexLock lock(&mu_);
- num_pollers_ = min_pollers_;
- num_threads_ = min_pollers_;
+ num_pollers_ = min_pollers_;
+ num_threads_ = min_pollers_;
max_active_threads_sofar_ = min_pollers_;
}
- for (int i = 0; i < min_pollers_; i++) {
+ 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();
@@ -147,30 +147,30 @@ void ThreadManager::Initialize() {
}
void ThreadManager::MainWorkLoop() {
- while (true) {
- void* tag;
- bool ok;
+ while (true) {
+ void* tag;
+ bool ok;
WorkStatus work_status = PollForWork(&tag, &ok);
grpc_core::ReleasableMutexLock lock(&mu_);
- // Reduce the number of pollers by 1 and check what happened with the poll
- num_pollers_--;
- bool done = false;
- switch (work_status) {
- case TIMEOUT:
- // If we timed out and we have more pollers than we need (or we are
- // shutdown), finish this thread
- if (shutdown_ || num_pollers_ > max_pollers_) done = true;
- break;
- case SHUTDOWN:
- // If the thread manager is shutdown, finish this thread
- done = true;
+ // Reduce the number of pollers by 1 and check what happened with the poll
+ num_pollers_--;
+ bool done = false;
+ switch (work_status) {
+ case TIMEOUT:
+ // If we timed out and we have more pollers than we need (or we are
+ // shutdown), finish this thread
+ if (shutdown_ || num_pollers_ > max_pollers_) done = true;
break;
- case WORK_FOUND:
+ case SHUTDOWN:
+ // If the thread manager is shutdown, finish this thread
+ done = true;
+ break;
+ case WORK_FOUND:
// If we got work and there are now insufficient pollers and there is
// quota available to create a new thread, start a new poller thread
bool resource_exhausted = false;
- if (!shutdown_ && num_pollers_ < min_pollers_) {
+ if (!shutdown_ && num_pollers_ < min_pollers_) {
if (grpc_resource_user_allocate_threads(resource_user_, 1)) {
// We can allocate a new poller thread
num_pollers_++;
@@ -202,57 +202,57 @@ void ThreadManager::MainWorkLoop() {
lock.Unlock();
resource_exhausted = true;
}
- } else {
+ } 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 is always released at this point - do the application work
+ }
+ // 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
+ // Take the lock again to check post conditions
lock.Lock();
- // If we're shutdown, we should finish at this point.
- if (shutdown_) done = true;
- break;
+ // If we're shutdown, we should finish at this point.
+ if (shutdown_) done = true;
+ break;
}
- // If we decided to finish the thread, break out of the while loop
- if (done) break;
+ // If we decided to finish the thread, break out of the while loop
+ if (done) break;
- // Otherwise go back to polling as long as it doesn't exceed max_pollers_
- //
- // **WARNING**:
- // There is a possibility of threads thrashing here (i.e excessive thread
- // shutdowns and creations than the ideal case). This happens if max_poller_
- // count is small and the rate of incoming requests is also small. In such
- // scenarios we can possibly configure max_pollers_ to a higher value and/or
- // increase the cq timeout.
- //
- // However, not doing this check here and unconditionally incrementing
- // num_pollers (and hoping that the system will eventually settle down) has
- // far worse consequences i.e huge number of threads getting created to the
- // point of thread-exhaustion. For example: if the incoming request rate is
- // very high, all the polling threads will return very quickly from
- // PollForWork() with WORK_FOUND. They all briefly decrement num_pollers_
- // counter thereby possibly - and briefly - making it go below min_pollers;
- // This will most likely result in the creation of a new poller since
- // num_pollers_ dipped below min_pollers_.
- //
- // Now, If we didn't do the max_poller_ check here, all these threads will
- // go back to doing PollForWork() and the whole cycle repeats (with a new
- // thread being added in each cycle). Once the total number of threads in
- // the system crosses a certain threshold (around ~1500), there is heavy
- // contention on mutexes (the mu_ here or the mutexes in gRPC core like the
- // pollset mutex) that makes DoWork() take longer to finish thereby causing
- // new poller threads to be created even faster. This results in a thread
- // avalanche.
- if (num_pollers_ < max_pollers_) {
- num_pollers_++;
- } else {
- break;
+ // Otherwise go back to polling as long as it doesn't exceed max_pollers_
+ //
+ // **WARNING**:
+ // There is a possibility of threads thrashing here (i.e excessive thread
+ // shutdowns and creations than the ideal case). This happens if max_poller_
+ // count is small and the rate of incoming requests is also small. In such
+ // scenarios we can possibly configure max_pollers_ to a higher value and/or
+ // increase the cq timeout.
+ //
+ // However, not doing this check here and unconditionally incrementing
+ // num_pollers (and hoping that the system will eventually settle down) has
+ // far worse consequences i.e huge number of threads getting created to the
+ // point of thread-exhaustion. For example: if the incoming request rate is
+ // very high, all the polling threads will return very quickly from
+ // PollForWork() with WORK_FOUND. They all briefly decrement num_pollers_
+ // counter thereby possibly - and briefly - making it go below min_pollers;
+ // This will most likely result in the creation of a new poller since
+ // num_pollers_ dipped below min_pollers_.
+ //
+ // Now, If we didn't do the max_poller_ check here, all these threads will
+ // go back to doing PollForWork() and the whole cycle repeats (with a new
+ // thread being added in each cycle). Once the total number of threads in
+ // the system crosses a certain threshold (around ~1500), there is heavy
+ // contention on mutexes (the mu_ here or the mutexes in gRPC core like the
+ // pollset mutex) that makes DoWork() take longer to finish thereby causing
+ // new poller threads to be created even faster. This results in a thread
+ // avalanche.
+ if (num_pollers_ < max_pollers_) {
+ num_pollers_++;
+ } else {
+ break;
}
- };
+ };
// This thread is exiting. Do some cleanup work i.e delete already completed
// worker threads
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 43f1fd5585f..29a3b990275 100644
--- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h
+++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h
@@ -1,18 +1,18 @@
/*
*
- * Copyright 2016 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*
*/
@@ -22,12 +22,12 @@
#include <list>
#include <memory>
-#include <grpcpp/support/config.h>
+#include <grpcpp/support/config.h>
#include "src/core/lib/gprpp/sync.h"
-#include "src/core/lib/gprpp/thd.h"
+#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/resource_quota.h"
-
+
namespace grpc {
class ThreadManager {
@@ -78,14 +78,14 @@ class ThreadManager {
// Mark the ThreadManager as shutdown and begin draining the work. This is a
// non-blocking call and the caller should call Wait(), a blocking call which
// returns only once the shutdown is complete
- virtual void Shutdown();
+ virtual void Shutdown();
// Has Shutdown() been called
bool IsShutdown();
// A blocking call that returns only after the ThreadManager has shutdown and
// all the threads have drained all the outstanding work
- virtual void Wait();
+ virtual void Wait();
// Max number of concurrent threads that were ever active in this thread
// manager so far. This is useful for debugging purposes (and in unit tests)
@@ -93,8 +93,8 @@ class ThreadManager {
int GetMaxActiveThreadsSoFar();
private:
- // Helper wrapper class around grpc_core::Thread. Takes a ThreadManager object
- // and starts a new grpc_core::Thread to calls the Run() function.
+ // Helper wrapper class around grpc_core::Thread. Takes a ThreadManager object
+ // and starts a new grpc_core::Thread to calls the Run() function.
//
// The Run() function calls ThreadManager::MainWorkLoop() function and once
// that completes, it marks the WorkerThread completed by calling
@@ -130,8 +130,8 @@ class ThreadManager {
// thd_mgr_>MarkAsCompleted(this) to mark the thread as completed
void Run();
- ThreadManager* const thd_mgr_;
- grpc_core::Thread thd_;
+ ThreadManager* const thd_mgr_;
+ grpc_core::Thread thd_;
bool created_;
};
diff --git a/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc b/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc
index fb705906455..01fbe33239a 100644
--- a/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc
+++ b/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc
@@ -1,29 +1,29 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/byte_buffer.h>
+#include <grpc/byte_buffer.h>
#include <grpc/byte_buffer_reader.h>
-#include <grpcpp/impl/grpc_library.h>
-#include <grpcpp/support/byte_buffer.h>
+#include <grpcpp/impl/grpc_library.h>
+#include <grpcpp/support/byte_buffer.h>
namespace grpc {
-static internal::GrpcLibraryInitializer g_gli_initializer;
+static internal::GrpcLibraryInitializer g_gli_initializer;
Status ByteBuffer::Dump(std::vector<Slice>* slices) const {
slices->clear();
diff --git a/contrib/libs/grpc/src/cpp/util/error_details.cc b/contrib/libs/grpc/src/cpp/util/error_details.cc
index dfd3351be15..49d60544547 100644
--- a/contrib/libs/grpc/src/cpp/util/error_details.cc
+++ b/contrib/libs/grpc/src/cpp/util/error_details.cc
@@ -1,50 +1,50 @@
-/*
- *
- * 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 <grpcpp/support/error_details.h>
-
-#include "src/proto/grpc/status/status.pb.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.
+ *
+ */
+
+#include <grpcpp/support/error_details.h>
+
+#include "src/proto/grpc/status/status.pb.h"
+
namespace grpc {
-
+
grpc::Status ExtractErrorDetails(const grpc::Status& from,
::google::rpc::Status* to) {
- if (to == nullptr) {
+ if (to == nullptr) {
return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "");
- }
+ }
if (!to->ParseFromString(TProtoStringType(from.error_details()))) {
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "");
- }
+ }
return grpc::Status::OK;
-}
-
+}
+
grpc::Status SetErrorDetails(const ::google::rpc::Status& from,
grpc::Status* to) {
- if (to == nullptr) {
+ if (to == nullptr) {
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());
- }
+ }
*to = grpc::Status(code, from.message(), from.SerializeAsString());
return grpc::Status::OK;
-}
-
+}
+
} // namespace grpc
diff --git a/contrib/libs/grpc/src/cpp/util/status.cc b/contrib/libs/grpc/src/cpp/util/status.cc
index 93696d81268..95c20b21482 100644
--- a/contrib/libs/grpc/src/cpp/util/status.cc
+++ b/contrib/libs/grpc/src/cpp/util/status.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/support/status.h>
+#include <grpcpp/support/status.h>
namespace grpc {
diff --git a/contrib/libs/grpc/src/cpp/util/string_ref.cc b/contrib/libs/grpc/src/cpp/util/string_ref.cc
index 8b09a82a634..6b15c2a53be 100644
--- a/contrib/libs/grpc/src/cpp/util/string_ref.cc
+++ b/contrib/libs/grpc/src/cpp/util/string_ref.cc
@@ -1,22 +1,22 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/support/string_ref.h>
+#include <grpcpp/support/string_ref.h>
namespace grpc {
diff --git a/contrib/libs/grpc/src/cpp/util/time_cc.cc b/contrib/libs/grpc/src/cpp/util/time_cc.cc
index 6c9c228d7cd..2bfe2bd40e8 100644
--- a/contrib/libs/grpc/src/cpp/util/time_cc.cc
+++ b/contrib/libs/grpc/src/cpp/util/time_cc.cc
@@ -1,27 +1,27 @@
/*
*
- * Copyright 2015 gRPC authors.
+ * 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
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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/time.h>
-#include <grpcpp/support/config.h>
-#include <grpcpp/support/time.h>
+#include <grpcpp/support/config.h>
+#include <grpcpp/support/time.h>
using std::chrono::duration_cast;
-using std::chrono::high_resolution_clock;
+using std::chrono::high_resolution_clock;
using std::chrono::nanoseconds;
using std::chrono::seconds;
using std::chrono::system_clock;
@@ -39,8 +39,8 @@ void Timepoint2Timespec(const system_clock::time_point& from,
return;
}
nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs);
- to->tv_sec = static_cast<int64_t>(secs.count());
- to->tv_nsec = static_cast<int32_t>(nsecs.count());
+ to->tv_sec = static_cast<int64_t>(secs.count());
+ to->tv_nsec = static_cast<int32_t>(nsecs.count());
to->clock_type = GPR_CLOCK_REALTIME;
}
@@ -55,8 +55,8 @@ void TimepointHR2Timespec(const high_resolution_clock::time_point& from,
return;
}
nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs);
- to->tv_sec = static_cast<int64_t>(secs.count());
- to->tv_nsec = static_cast<int32_t>(nsecs.count());
+ to->tv_sec = static_cast<int64_t>(secs.count());
+ to->tv_nsec = static_cast<int32_t>(nsecs.count());
to->clock_type = GPR_CLOCK_REALTIME;
}
diff --git a/contrib/libs/grpc/src/proto/grpc/binary_log/v1alpha/log.proto b/contrib/libs/grpc/src/proto/grpc/binary_log/v1alpha/log.proto
index 77100ebbef9..8882c17638a 100644
--- a/contrib/libs/grpc/src/proto/grpc/binary_log/v1alpha/log.proto
+++ b/contrib/libs/grpc/src/proto/grpc/binary_log/v1alpha/log.proto
@@ -1,16 +1,16 @@
-// Copyright 2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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";
diff --git a/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto b/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto
index d0781094ea8..f1779de7123 100644
--- a/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto
+++ b/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto
@@ -1,17 +1,17 @@
// 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.
-
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 defines an interface for exporting monitoring information
// out of gRPC servers. See the full design at
// https://github.com/grpc/proposal/blob/master/A14-channelz.md
@@ -19,312 +19,312 @@
// The canonical version of this proto can be found at
// https://github.com/grpc/grpc-proto/blob/master/grpc/channelz/v1/channelz.proto
-syntax = "proto3";
-
+syntax = "proto3";
+
package grpc.channelz.v1;
-
-import "google/protobuf/any.proto";
-import "google/protobuf/duration.proto";
-import "google/protobuf/timestamp.proto";
-import "google/protobuf/wrappers.proto";
-
+
+import "google/protobuf/any.proto";
+import "google/protobuf/duration.proto";
+import "google/protobuf/timestamp.proto";
+import "google/protobuf/wrappers.proto";
+
option go_package = "google.golang.org/grpc/channelz/grpc_channelz_v1";
option java_multiple_files = true;
option java_package = "io.grpc.channelz.v1";
option java_outer_classname = "ChannelzProto";
-
-// Channel is a logical grouping of channels, subchannels, and sockets.
-message Channel {
+
+// Channel is a logical grouping of channels, subchannels, and sockets.
+message Channel {
// The identifier for this channel. This should be set.
- ChannelRef ref = 1;
- // Data specific to this channel.
- ChannelData data = 2;
- // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
-
- // There are no ordering guarantees on the order of channel refs.
- // There may not be cycles in the ref graph.
- // A channel ref may be present in more than one channel or subchannel.
- repeated ChannelRef channel_ref = 3;
-
- // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
- // There are no ordering guarantees on the order of subchannel refs.
- // There may not be cycles in the ref graph.
- // A sub channel ref may be present in more than one channel or subchannel.
- repeated SubchannelRef subchannel_ref = 4;
-
- // There are no ordering guarantees on the order of sockets.
+ ChannelRef ref = 1;
+ // Data specific to this channel.
+ ChannelData data = 2;
+ // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
+
+ // There are no ordering guarantees on the order of channel refs.
+ // There may not be cycles in the ref graph.
+ // A channel ref may be present in more than one channel or subchannel.
+ repeated ChannelRef channel_ref = 3;
+
+ // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
+ // There are no ordering guarantees on the order of subchannel refs.
+ // There may not be cycles in the ref graph.
+ // A sub channel ref may be present in more than one channel or subchannel.
+ repeated SubchannelRef subchannel_ref = 4;
+
+ // There are no ordering guarantees on the order of sockets.
repeated SocketRef socket_ref = 5;
-}
-
-// Subchannel is a logical grouping of channels, subchannels, and sockets.
-// A subchannel is load balanced over by it's ancestor
-message Subchannel {
- // The identifier for this channel.
- SubchannelRef ref = 1;
- // Data specific to this channel.
- ChannelData data = 2;
- // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
-
- // There are no ordering guarantees on the order of channel refs.
- // There may not be cycles in the ref graph.
- // A channel ref may be present in more than one channel or subchannel.
- repeated ChannelRef channel_ref = 3;
-
- // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
- // There are no ordering guarantees on the order of subchannel refs.
- // There may not be cycles in the ref graph.
- // A sub channel ref may be present in more than one channel or subchannel.
- repeated SubchannelRef subchannel_ref = 4;
-
- // There are no ordering guarantees on the order of sockets.
+}
+
+// Subchannel is a logical grouping of channels, subchannels, and sockets.
+// A subchannel is load balanced over by it's ancestor
+message Subchannel {
+ // The identifier for this channel.
+ SubchannelRef ref = 1;
+ // Data specific to this channel.
+ ChannelData data = 2;
+ // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
+
+ // There are no ordering guarantees on the order of channel refs.
+ // There may not be cycles in the ref graph.
+ // A channel ref may be present in more than one channel or subchannel.
+ repeated ChannelRef channel_ref = 3;
+
+ // At most one of 'channel_ref+subchannel_ref' and 'socket' is set.
+ // There are no ordering guarantees on the order of subchannel refs.
+ // There may not be cycles in the ref graph.
+ // A sub channel ref may be present in more than one channel or subchannel.
+ repeated SubchannelRef subchannel_ref = 4;
+
+ // There are no ordering guarantees on the order of sockets.
repeated SocketRef socket_ref = 5;
-}
-
-// These come from the specified states in this document:
-// https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md
-message ChannelConnectivityState {
- enum State {
- UNKNOWN = 0;
- IDLE = 1;
- CONNECTING = 2;
- READY = 3;
- TRANSIENT_FAILURE = 4;
- SHUTDOWN = 5;
- }
- State state = 1;
-}
-
+}
+
+// These come from the specified states in this document:
+// https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md
+message ChannelConnectivityState {
+ enum State {
+ UNKNOWN = 0;
+ IDLE = 1;
+ CONNECTING = 2;
+ READY = 3;
+ TRANSIENT_FAILURE = 4;
+ SHUTDOWN = 5;
+ }
+ State state = 1;
+}
+
// Channel data is data related to a specific Channel or Subchannel.
-message ChannelData {
+message ChannelData {
// The connectivity state of the channel or subchannel. Implementations
// should always set this.
- ChannelConnectivityState state = 1;
-
- // The target this channel originally tried to connect to. May be absent
- string target = 2;
-
+ ChannelConnectivityState state = 1;
+
+ // The target this channel originally tried to connect to. May be absent
+ string target = 2;
+
// A trace of recent events on the channel. May be absent.
- ChannelTrace trace = 3;
-
- // The number of calls started on the channel
- int64 calls_started = 4;
- // The number of calls that have completed with an OK status
- int64 calls_succeeded = 5;
+ ChannelTrace trace = 3;
+
+ // The number of calls started on the channel
+ int64 calls_started = 4;
+ // The number of calls that have completed with an OK status
+ int64 calls_succeeded = 5;
// The number of calls that have completed with a non-OK status
- int64 calls_failed = 6;
-
- // The last time a call was started on the channel.
- google.protobuf.Timestamp last_call_started_timestamp = 7;
-}
-
-// A trace event is an interesting thing that happened to a channel or
-// subchannel, such as creation, address resolution, subchannel creation, etc.
-message ChannelTraceEvent {
- // High level description of the event.
- string description = 1;
- // The supported severity levels of trace events.
- enum Severity {
- CT_UNKNOWN = 0;
- CT_INFO = 1;
- CT_WARNING = 2;
- CT_ERROR = 3;
- }
- // the severity of the trace event
- Severity severity = 2;
- // When this event occurred.
- google.protobuf.Timestamp timestamp = 3;
- // ref of referenced channel or subchannel.
- // Optional, only present if this event refers to a child object. For example,
- // this field would be filled if this trace event was for a subchannel being
- // created.
- oneof child_ref {
- ChannelRef channel_ref = 4;
- SubchannelRef subchannel_ref = 5;
- }
-}
-
+ int64 calls_failed = 6;
+
+ // The last time a call was started on the channel.
+ google.protobuf.Timestamp last_call_started_timestamp = 7;
+}
+
+// A trace event is an interesting thing that happened to a channel or
+// subchannel, such as creation, address resolution, subchannel creation, etc.
+message ChannelTraceEvent {
+ // High level description of the event.
+ string description = 1;
+ // The supported severity levels of trace events.
+ enum Severity {
+ CT_UNKNOWN = 0;
+ CT_INFO = 1;
+ CT_WARNING = 2;
+ CT_ERROR = 3;
+ }
+ // the severity of the trace event
+ Severity severity = 2;
+ // When this event occurred.
+ google.protobuf.Timestamp timestamp = 3;
+ // ref of referenced channel or subchannel.
+ // Optional, only present if this event refers to a child object. For example,
+ // this field would be filled if this trace event was for a subchannel being
+ // created.
+ oneof child_ref {
+ ChannelRef channel_ref = 4;
+ SubchannelRef subchannel_ref = 5;
+ }
+}
+
// ChannelTrace represents the recent events that have occurred on the channel.
-message ChannelTrace {
- // Number of events ever logged in this tracing object. This can differ from
- // events.size() because events can be overwritten or garbage collected by
- // implementations.
- int64 num_events_logged = 1;
- // Time that this channel was created.
+message ChannelTrace {
+ // Number of events ever logged in this tracing object. This can differ from
+ // events.size() because events can be overwritten or garbage collected by
+ // implementations.
+ int64 num_events_logged = 1;
+ // Time that this channel was created.
google.protobuf.Timestamp creation_timestamp = 2;
- // List of events that have occurred on this channel.
- repeated ChannelTraceEvent events = 3;
-}
-
+ // List of events that have occurred on this channel.
+ repeated ChannelTraceEvent events = 3;
+}
+
// ChannelRef is a reference to a Channel.
-message ChannelRef {
- // The globally unique id for this channel. Must be a positive number.
- int64 channel_id = 1;
- // An optional name associated with the channel.
- string name = 2;
- // Intentionally don't use field numbers from other refs.
+message ChannelRef {
+ // The globally unique id for this channel. Must be a positive number.
+ int64 channel_id = 1;
+ // An optional name associated with the channel.
+ string name = 2;
+ // Intentionally don't use field numbers from other refs.
reserved 3, 4, 5, 6, 7, 8;
-}
-
+}
+
// 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;
- // An optional name associated with the subchannel.
- string name = 8;
- // Intentionally don't use field numbers from other refs.
- reserved 1, 2, 3, 4, 5, 6;
-}
-
+message SubchannelRef {
+ // The globally unique id for this subchannel. Must be a positive number.
+ int64 subchannel_id = 7;
+ // An optional name associated with the subchannel.
+ string name = 8;
+ // Intentionally don't use field numbers from other refs.
+ reserved 1, 2, 3, 4, 5, 6;
+}
+
// SocketRef is a reference to a Socket.
-message SocketRef {
+message SocketRef {
// The globally unique id for this socket. Must be a positive number.
- int64 socket_id = 3;
- // An optional name associated with the socket.
- string name = 4;
- // Intentionally don't use field numbers from other refs.
- reserved 1, 2, 5, 6, 7, 8;
-}
-
+ int64 socket_id = 3;
+ // An optional name associated with the socket.
+ string name = 4;
+ // Intentionally don't use field numbers from other refs.
+ reserved 1, 2, 5, 6, 7, 8;
+}
+
// ServerRef is a reference to a Server.
-message ServerRef {
+message ServerRef {
// A globally unique identifier for this server. Must be a positive number.
- int64 server_id = 5;
- // An optional name associated with the server.
- string name = 6;
- // Intentionally don't use field numbers from other refs.
- reserved 1, 2, 3, 4, 7, 8;
-}
-
+ int64 server_id = 5;
+ // An optional name associated with the server.
+ string name = 6;
+ // Intentionally don't use field numbers from other refs.
+ reserved 1, 2, 3, 4, 7, 8;
+}
+
// Server represents a single server. There may be multiple servers in a single
// program.
-message Server {
+message Server {
// The identifier for a Server. This should be set.
- ServerRef ref = 1;
+ ServerRef ref = 1;
// The associated data of the Server.
- ServerData data = 2;
-
- // The sockets that the server is listening on. There are no ordering
+ ServerData data = 2;
+
+ // The sockets that the server is listening on. There are no ordering
// guarantees. This may be absent.
- repeated SocketRef listen_socket = 3;
-}
-
+ repeated SocketRef listen_socket = 3;
+}
+
// ServerData is data for a specific Server.
-message ServerData {
+message ServerData {
// A trace of recent events on the server. May be absent.
- ChannelTrace trace = 1;
-
- // The number of incoming calls started on the server
- int64 calls_started = 2;
- // The number of incoming calls that have completed with an OK status
- int64 calls_succeeded = 3;
- // The number of incoming calls that have a completed with a non-OK status
- int64 calls_failed = 4;
-
- // The last time a call was started on the server.
- google.protobuf.Timestamp last_call_started_timestamp = 5;
-}
-
-// Information about an actual connection. Pronounced "sock-ay".
-message Socket {
+ ChannelTrace trace = 1;
+
+ // The number of incoming calls started on the server
+ int64 calls_started = 2;
+ // The number of incoming calls that have completed with an OK status
+ int64 calls_succeeded = 3;
+ // The number of incoming calls that have a completed with a non-OK status
+ int64 calls_failed = 4;
+
+ // The last time a call was started on the server.
+ google.protobuf.Timestamp last_call_started_timestamp = 5;
+}
+
+// Information about an actual connection. Pronounced "sock-ay".
+message Socket {
// The identifier for the Socket.
- SocketRef ref = 1;
-
+ SocketRef ref = 1;
+
// Data specific to this Socket.
- SocketData data = 2;
- // The locally bound address.
- Address local = 3;
- // The remote bound address. May be absent.
- Address remote = 4;
+ SocketData data = 2;
+ // The locally bound address.
+ Address local = 3;
+ // The remote bound address. May be absent.
+ Address remote = 4;
// Security details for this socket. May be absent if not available, or
// there is no security on the socket.
- Security security = 5;
-
- // Optional, represents the name of the remote endpoint, if different than
- // the original target name.
- string remote_name = 6;
-}
-
+ Security security = 5;
+
+ // Optional, represents the name of the remote endpoint, if different than
+ // the original target name.
+ string remote_name = 6;
+}
+
// SocketData is data associated for a specific Socket. The fields present
// are specific to the implementation, so there may be minor differences in
// the semantics. (e.g. flow control windows)
-message SocketData {
- // The number of streams that have been started.
- int64 streams_started = 1;
+message SocketData {
+ // The number of streams that have been started.
+ int64 streams_started = 1;
// The number of streams that have ended successfully:
// On client side, received frame with eos bit set;
// On server side, sent frame with eos bit set.
- int64 streams_succeeded = 2;
+ int64 streams_succeeded = 2;
// The number of streams that have ended unsuccessfully:
// On client side, ended without receiving frame with eos bit set;
// On server side, ended without sending frame with eos bit set.
- int64 streams_failed = 3;
+ int64 streams_failed = 3;
// The number of grpc messages successfully sent on this socket.
- int64 messages_sent = 4;
+ int64 messages_sent = 4;
// The number of grpc messages received on this socket.
- int64 messages_received = 5;
-
- // The number of keep alives sent. This is typically implemented with HTTP/2
- // ping messages.
- int64 keep_alives_sent = 6;
-
- // The last time a stream was created by this endpoint. Usually unset for
- // servers.
- google.protobuf.Timestamp last_local_stream_created_timestamp = 7;
- // The last time a stream was created by the remote endpoint. Usually unset
- // for clients.
- google.protobuf.Timestamp last_remote_stream_created_timestamp = 8;
-
- // The last time a message was sent by this endpoint.
- google.protobuf.Timestamp last_message_sent_timestamp = 9;
- // The last time a message was received by this endpoint.
- google.protobuf.Timestamp last_message_received_timestamp = 10;
-
- // The amount of window, granted to the local endpoint by the remote endpoint.
- // This may be slightly out of date due to network latency. This does NOT
- // include stream level or TCP level flow control info.
- google.protobuf.Int64Value local_flow_control_window = 11;
-
- // The amount of window, granted to the remote endpoint by the local endpoint.
- // This may be slightly out of date due to network latency. This does NOT
- // include stream level or TCP level flow control info.
- google.protobuf.Int64Value remote_flow_control_window = 12;
-
+ int64 messages_received = 5;
+
+ // The number of keep alives sent. This is typically implemented with HTTP/2
+ // ping messages.
+ int64 keep_alives_sent = 6;
+
+ // The last time a stream was created by this endpoint. Usually unset for
+ // servers.
+ google.protobuf.Timestamp last_local_stream_created_timestamp = 7;
+ // The last time a stream was created by the remote endpoint. Usually unset
+ // for clients.
+ google.protobuf.Timestamp last_remote_stream_created_timestamp = 8;
+
+ // The last time a message was sent by this endpoint.
+ google.protobuf.Timestamp last_message_sent_timestamp = 9;
+ // The last time a message was received by this endpoint.
+ google.protobuf.Timestamp last_message_received_timestamp = 10;
+
+ // The amount of window, granted to the local endpoint by the remote endpoint.
+ // This may be slightly out of date due to network latency. This does NOT
+ // include stream level or TCP level flow control info.
+ google.protobuf.Int64Value local_flow_control_window = 11;
+
+ // The amount of window, granted to the remote endpoint by the local endpoint.
+ // This may be slightly out of date due to network latency. This does NOT
+ // include stream level or TCP level flow control info.
+ google.protobuf.Int64Value remote_flow_control_window = 12;
+
// Socket options set on this socket. May be absent if 'summary' is set
// on GetSocketRequest.
- repeated SocketOption option = 13;
-}
-
+ repeated SocketOption option = 13;
+}
+
// Address represents the address used to create the socket.
-message Address {
- message TcpIpAddress {
+message Address {
+ message TcpIpAddress {
// Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16
- // bytes in length.
- bytes ip_address = 1;
- // 0-64k, or -1 if not appropriate.
- int32 port = 2;
- }
- // A Unix Domain Socket address.
- message UdsAddress {
- string filename = 1;
- }
- // An address type not included above.
- message OtherAddress {
+ // bytes in length.
+ bytes ip_address = 1;
+ // 0-64k, or -1 if not appropriate.
+ int32 port = 2;
+ }
+ // A Unix Domain Socket address.
+ message UdsAddress {
+ string filename = 1;
+ }
+ // An address type not included above.
+ message OtherAddress {
// The human readable version of the value. This value should be set.
- string name = 1;
- // The actual address message.
- google.protobuf.Any value = 2;
- }
-
- oneof address {
- TcpIpAddress tcpip_address = 1;
- UdsAddress uds_address = 2;
- OtherAddress other_address = 3;
- }
-}
-
+ string name = 1;
+ // The actual address message.
+ google.protobuf.Any value = 2;
+ }
+
+ oneof address {
+ TcpIpAddress tcpip_address = 1;
+ UdsAddress uds_address = 2;
+ OtherAddress other_address = 3;
+ }
+}
+
// Security represents details about how secure the socket is.
-message Security {
- message Tls {
+message Security {
+ message Tls {
oneof cipher_suite {
// The cipher suite name in the RFC 4346 format:
// https://tools.ietf.org/html/rfc4346#appendix-C
@@ -333,111 +333,111 @@ message Security {
// the RFC 4346 name is not available.
string other_name = 2;
}
- // the certificate used by this endpoint.
- bytes local_certificate = 3;
- // the certificate used by the remote endpoint.
- bytes remote_certificate = 4;
- }
- message OtherSecurity {
- // The human readable version of the value.
- string name = 1;
- // The actual security details message.
- google.protobuf.Any value = 2;
- }
- oneof model {
- Tls tls = 1;
- OtherSecurity other = 2;
- }
-}
-
+ // the certificate used by this endpoint.
+ bytes local_certificate = 3;
+ // the certificate used by the remote endpoint.
+ bytes remote_certificate = 4;
+ }
+ message OtherSecurity {
+ // The human readable version of the value.
+ string name = 1;
+ // The actual security details message.
+ google.protobuf.Any value = 2;
+ }
+ oneof model {
+ Tls tls = 1;
+ OtherSecurity other = 2;
+ }
+}
+
// SocketOption represents socket options for a socket. Specifically, these
// are the options returned by getsockopt().
-message SocketOption {
+message SocketOption {
// The full name of the socket option. Typically this will be the upper case
// name, such as "SO_REUSEPORT".
- string name = 1;
- // The human readable value of this socket option. At least one of value or
- // additional will be set.
- string value = 2;
- // Additional data associated with the socket option. At least one of value
- // or additional will be set.
- google.protobuf.Any additional = 3;
-}
-
-// For use with SocketOption's additional field. This is primarily used for
-// SO_RCVTIMEO and SO_SNDTIMEO
-message SocketOptionTimeout {
- google.protobuf.Duration duration = 1;
-}
-
+ string name = 1;
+ // The human readable value of this socket option. At least one of value or
+ // additional will be set.
+ string value = 2;
+ // Additional data associated with the socket option. At least one of value
+ // or additional will be set.
+ google.protobuf.Any additional = 3;
+}
+
+// For use with SocketOption's additional field. This is primarily used for
+// SO_RCVTIMEO and SO_SNDTIMEO
+message SocketOptionTimeout {
+ google.protobuf.Duration duration = 1;
+}
+
// For use with SocketOption's additional field. This is primarily used for
// SO_LINGER.
-message SocketOptionLinger {
+message SocketOptionLinger {
// active maps to `struct linger.l_onoff`
- bool active = 1;
+ bool active = 1;
// duration maps to `struct linger.l_linger`
- google.protobuf.Duration duration = 2;
-}
-
+ google.protobuf.Duration duration = 2;
+}
+
// For use with SocketOption's additional field. Tcp info for
// SOL_TCP and TCP_INFO.
-message SocketOptionTcpInfo {
- uint32 tcpi_state = 1;
-
- uint32 tcpi_ca_state = 2;
- uint32 tcpi_retransmits = 3;
- uint32 tcpi_probes = 4;
- uint32 tcpi_backoff = 5;
- uint32 tcpi_options = 6;
- uint32 tcpi_snd_wscale = 7;
- uint32 tcpi_rcv_wscale = 8;
-
- uint32 tcpi_rto = 9;
- uint32 tcpi_ato = 10;
- uint32 tcpi_snd_mss = 11;
- uint32 tcpi_rcv_mss = 12;
-
- uint32 tcpi_unacked = 13;
- uint32 tcpi_sacked = 14;
- uint32 tcpi_lost = 15;
- uint32 tcpi_retrans = 16;
- uint32 tcpi_fackets = 17;
-
- uint32 tcpi_last_data_sent = 18;
- uint32 tcpi_last_ack_sent = 19;
- uint32 tcpi_last_data_recv = 20;
- uint32 tcpi_last_ack_recv = 21;
-
- uint32 tcpi_pmtu = 22;
- uint32 tcpi_rcv_ssthresh = 23;
- uint32 tcpi_rtt = 24;
- uint32 tcpi_rttvar = 25;
- uint32 tcpi_snd_ssthresh = 26;
- uint32 tcpi_snd_cwnd = 27;
- uint32 tcpi_advmss = 28;
- uint32 tcpi_reordering = 29;
-}
-
+message SocketOptionTcpInfo {
+ uint32 tcpi_state = 1;
+
+ uint32 tcpi_ca_state = 2;
+ uint32 tcpi_retransmits = 3;
+ uint32 tcpi_probes = 4;
+ uint32 tcpi_backoff = 5;
+ uint32 tcpi_options = 6;
+ uint32 tcpi_snd_wscale = 7;
+ uint32 tcpi_rcv_wscale = 8;
+
+ uint32 tcpi_rto = 9;
+ uint32 tcpi_ato = 10;
+ uint32 tcpi_snd_mss = 11;
+ uint32 tcpi_rcv_mss = 12;
+
+ uint32 tcpi_unacked = 13;
+ uint32 tcpi_sacked = 14;
+ uint32 tcpi_lost = 15;
+ uint32 tcpi_retrans = 16;
+ uint32 tcpi_fackets = 17;
+
+ uint32 tcpi_last_data_sent = 18;
+ uint32 tcpi_last_ack_sent = 19;
+ uint32 tcpi_last_data_recv = 20;
+ uint32 tcpi_last_ack_recv = 21;
+
+ uint32 tcpi_pmtu = 22;
+ uint32 tcpi_rcv_ssthresh = 23;
+ uint32 tcpi_rtt = 24;
+ uint32 tcpi_rttvar = 25;
+ uint32 tcpi_snd_ssthresh = 26;
+ uint32 tcpi_snd_cwnd = 27;
+ uint32 tcpi_advmss = 28;
+ uint32 tcpi_reordering = 29;
+}
+
// Channelz is a service exposed by gRPC servers that provides detailed debug
// information.
-service Channelz {
+service Channelz {
// Gets all root channels (i.e. channels the application has directly
- // created). This does not include subchannels nor non-top level channels.
- rpc GetTopChannels(GetTopChannelsRequest) returns (GetTopChannelsResponse);
- // Gets all servers that exist in the process.
- rpc GetServers(GetServersRequest) returns (GetServersResponse);
+ // created). This does not include subchannels nor non-top level channels.
+ rpc GetTopChannels(GetTopChannelsRequest) returns (GetTopChannelsResponse);
+ // Gets all servers that exist in the process.
+ rpc GetServers(GetServersRequest) returns (GetServersResponse);
// Returns a single Server, or else a NOT_FOUND code.
rpc GetServer(GetServerRequest) returns (GetServerResponse);
- // Gets all server sockets that exist in the process.
- rpc GetServerSockets(GetServerSocketsRequest) returns (GetServerSocketsResponse);
- // Returns a single Channel, or else a NOT_FOUND code.
- rpc GetChannel(GetChannelRequest) returns (GetChannelResponse);
- // Returns a single Subchannel, or else a NOT_FOUND code.
- rpc GetSubchannel(GetSubchannelRequest) returns (GetSubchannelResponse);
- // Returns a single Socket or else a NOT_FOUND code.
- rpc GetSocket(GetSocketRequest) returns (GetSocketResponse);
-}
-
+ // Gets all server sockets that exist in the process.
+ rpc GetServerSockets(GetServerSocketsRequest) returns (GetServerSocketsResponse);
+ // Returns a single Channel, or else a NOT_FOUND code.
+ rpc GetChannel(GetChannelRequest) returns (GetChannelResponse);
+ // Returns a single Subchannel, or else a NOT_FOUND code.
+ rpc GetSubchannel(GetSubchannelRequest) returns (GetSubchannelResponse);
+ // Returns a single Socket or else a NOT_FOUND code.
+ rpc GetSocket(GetSocketRequest) returns (GetSocketResponse);
+}
+
message GetTopChannelsRequest {
// start_channel_id indicates that only channels at or above this id should be
// included in the results.
@@ -463,31 +463,31 @@ message GetTopChannelsResponse {
bool end = 2;
}
-message GetServersRequest {
- // start_server_id indicates that only servers at or above this id should be
- // included in the results.
+message GetServersRequest {
+ // start_server_id indicates that only servers at or above this id should be
+ // included in the results.
// To request the first page, this must be set to 0. To request
// subsequent pages, the client generates this value by adding 1 to
// the highest seen result ID.
- int64 start_server_id = 1;
+ int64 start_server_id = 1;
// If non-zero, the server will return a page of results containing
// at most this many items. If zero, the server will choose a
// reasonable page size. Must never be negative.
int64 max_results = 2;
-}
-
-message GetServersResponse {
- // list of servers that the connection detail service knows about. Sorted in
- // ascending server_id order.
+}
+
+message GetServersResponse {
+ // list of servers that the connection detail service knows about. Sorted in
+ // ascending server_id order.
// Must contain at least 1 result, otherwise 'end' must be true.
- repeated Server server = 1;
- // If set, indicates that the list of servers is the final list. Requesting
- // more servers will only return more if they are created after this RPC
- // completes.
- bool end = 2;
-}
-
+ repeated Server server = 1;
+ // If set, indicates that the list of servers is the final list. Requesting
+ // more servers will only return more if they are created after this RPC
+ // completes.
+ bool end = 2;
+}
+
message GetServerRequest {
// server_id is the identifier of the specific server to get.
int64 server_id = 1;
@@ -499,66 +499,66 @@ message GetServerResponse {
Server server = 1;
}
-message GetServerSocketsRequest {
- int64 server_id = 1;
- // start_socket_id indicates that only sockets at or above this id should be
- // included in the results.
+message GetServerSocketsRequest {
+ int64 server_id = 1;
+ // start_socket_id indicates that only sockets at or above this id should be
+ // included in the results.
// To request the first page, this must be set to 0. To request
// subsequent pages, the client generates this value by adding 1 to
// the highest seen result ID.
- int64 start_socket_id = 2;
+ int64 start_socket_id = 2;
// If non-zero, the server will return a page of results containing
// at most this many items. If zero, the server will choose a
// reasonable page size. Must never be negative.
int64 max_results = 3;
-}
-
-message GetServerSocketsResponse {
- // list of socket refs that the connection detail service knows about. Sorted in
- // ascending socket_id order.
+}
+
+message GetServerSocketsResponse {
+ // list of socket refs that the connection detail service knows about. Sorted in
+ // ascending socket_id order.
// Must contain at least 1 result, otherwise 'end' must be true.
- repeated SocketRef socket_ref = 1;
- // If set, indicates that the list of sockets is the final list. Requesting
- // more sockets will only return more if they are created after this RPC
- // completes.
- bool end = 2;
-}
-
-message GetChannelRequest {
+ repeated SocketRef socket_ref = 1;
+ // If set, indicates that the list of sockets is the final list. Requesting
+ // more sockets will only return more if they are created after this RPC
+ // completes.
+ bool end = 2;
+}
+
+message GetChannelRequest {
// channel_id is the identifier of the specific channel to get.
- int64 channel_id = 1;
-}
-
-message GetChannelResponse {
+ int64 channel_id = 1;
+}
+
+message GetChannelResponse {
// The Channel that corresponds to the requested channel_id. This field
// should be set.
- Channel channel = 1;
-}
-
-message GetSubchannelRequest {
+ Channel channel = 1;
+}
+
+message GetSubchannelRequest {
// subchannel_id is the identifier of the specific subchannel to get.
- int64 subchannel_id = 1;
-}
-
-message GetSubchannelResponse {
+ int64 subchannel_id = 1;
+}
+
+message GetSubchannelResponse {
// The Subchannel that corresponds to the requested subchannel_id. This
// field should be set.
- Subchannel subchannel = 1;
-}
-
-message GetSocketRequest {
+ Subchannel subchannel = 1;
+}
+
+message GetSocketRequest {
// socket_id is the identifier of the specific socket to get.
- int64 socket_id = 1;
+ int64 socket_id = 1;
// If true, the response will contain only high level information
// that is inexpensive to obtain. Fields thay may be omitted are
// documented.
bool summary = 2;
-}
-
-message GetSocketResponse {
+}
+
+message GetSocketResponse {
// The Socket that corresponds to the requested socket_id. This field
// should be set.
- Socket socket = 1;
-}
+ Socket socket = 1;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/core/stats.proto b/contrib/libs/grpc/src/proto/grpc/core/stats.proto
index ac181b04397..e09fbedcabe 100644
--- a/contrib/libs/grpc/src/proto/grpc/core/stats.proto
+++ b/contrib/libs/grpc/src/proto/grpc/core/stats.proto
@@ -1,38 +1,38 @@
-// 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.
-
-syntax = "proto3";
-
-package grpc.core;
-
-message Bucket {
- double start = 1;
- uint64 count = 2;
-}
-
-message Histogram {
- repeated Bucket buckets = 1;
-}
-
-message Metric {
- string name = 1;
- oneof value {
- uint64 count = 10;
- Histogram histogram = 11;
- }
-}
-
-message Stats {
- repeated Metric metrics = 1;
-}
+// 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.
+
+syntax = "proto3";
+
+package grpc.core;
+
+message Bucket {
+ double start = 1;
+ uint64 count = 2;
+}
+
+message Histogram {
+ repeated Bucket buckets = 1;
+}
+
+message Metric {
+ string name = 1;
+ oneof value {
+ uint64 count = 10;
+ Histogram histogram = 11;
+ }
+}
+
+message Stats {
+ repeated Metric metrics = 1;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/health/v1/health.options b/contrib/libs/grpc/src/proto/grpc/health/v1/health.options
index 240b498b580..95e4f034e24 100644
--- a/contrib/libs/grpc/src/proto/grpc/health/v1/health.options
+++ b/contrib/libs/grpc/src/proto/grpc/health/v1/health.options
@@ -1 +1 @@
-grpc.health.v1.HealthCheckRequest.service max_size:200
+grpc.health.v1.HealthCheckRequest.service max_size:200
diff --git a/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto b/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto
index 38843ff1e73..26092bc16d9 100644
--- a/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto
+++ b/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto
@@ -1,16 +1,16 @@
// Copyright 2015 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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/health/v1/health.proto
diff --git a/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto b/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto
index ccf2efd629e..ad7bd645836 100644
--- a/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto
+++ b/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto
@@ -1,16 +1,16 @@
// Copyright 2015 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 defines the GRPCLB LoadBalancing protocol.
//
@@ -52,38 +52,38 @@ message InitialLoadBalanceRequest {
string name = 1;
}
-// Contains the number of calls finished for a particular load balance token.
-message ClientStatsPerToken {
- // See Server.load_balance_token.
- string load_balance_token = 1;
-
- // The total number of RPCs that finished associated with the token.
- int64 num_calls = 2;
-}
-
+// Contains the number of calls finished for a particular load balance token.
+message ClientStatsPerToken {
+ // See Server.load_balance_token.
+ string load_balance_token = 1;
+
+ // The total number of RPCs that finished associated with the token.
+ int64 num_calls = 2;
+}
+
// Contains client level statistics that are useful to load balancing. Each
-// count except the timestamp should be reset to zero after reporting the stats.
+// count except the timestamp should be reset to zero after reporting the stats.
message ClientStats {
- // The timestamp of generating the report.
+ // The timestamp of generating the report.
google.protobuf.Timestamp timestamp = 1;
- // The total number of RPCs that started.
- int64 num_calls_started = 2;
-
- // The total number of RPCs that finished.
- int64 num_calls_finished = 3;
-
- // The total number of RPCs that failed to reach a server except dropped RPCs.
- int64 num_calls_finished_with_client_failed_to_send = 6;
-
- // The total number of RPCs that finished and are known to have been received
- // by a server.
- int64 num_calls_finished_known_received = 7;
-
- // The list of dropped calls.
- repeated ClientStatsPerToken calls_finished_with_drop = 8;
-
- reserved 4, 5;
+ // The total number of RPCs that started.
+ int64 num_calls_started = 2;
+
+ // The total number of RPCs that finished.
+ int64 num_calls_finished = 3;
+
+ // The total number of RPCs that failed to reach a server except dropped RPCs.
+ int64 num_calls_finished_with_client_failed_to_send = 6;
+
+ // The total number of RPCs that finished and are known to have been received
+ // by a server.
+ int64 num_calls_finished_known_received = 7;
+
+ // The list of dropped calls.
+ repeated ClientStatsPerToken calls_finished_with_drop = 8;
+
+ reserved 4, 5;
}
message LoadBalanceResponse {
@@ -123,12 +123,12 @@ message ServerList {
// unless instructed otherwise via the client_config.
repeated Server servers = 1;
- // Was google.protobuf.Duration expiration_interval.
- reserved 3;
+ // Was google.protobuf.Duration expiration_interval.
+ reserved 3;
}
-// Contains server information. When the drop field is not true, use the other
-// fields.
+// Contains server information. When the drop field is not true, use the other
+// fields.
message Server {
// A resolved address for the server, serialized in network-byte-order. It may
// either be an IPv4 or IPv6 address.
@@ -146,12 +146,12 @@ message Server {
// Its length can be variable but must be less than 50 bytes.
string load_balance_token = 3;
- // Indicates whether this particular request should be dropped by the client.
- // If the request is dropped, there will be a corresponding entry in
- // ClientStats.calls_finished_with_drop.
- bool drop = 4;
-
- reserved 5;
+ // Indicates whether this particular request should be dropped by the client.
+ // If the request is dropped, there will be a corresponding entry in
+ // ClientStats.calls_finished_with_drop.
+ bool drop = 4;
+
+ reserved 5;
}
message FallbackResponse {}
diff --git a/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/reflection.proto b/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/reflection.proto
index 816852f8253..289a71788ad 100644
--- a/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/reflection.proto
+++ b/contrib/libs/grpc/src/proto/grpc/reflection/v1alpha/reflection.proto
@@ -1,16 +1,16 @@
-// Copyright 2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
// Service exported by server reflection
diff --git a/contrib/libs/grpc/src/proto/grpc/status/README b/contrib/libs/grpc/src/proto/grpc/status/README
index 34e588efac9..d52924fd795 100644
--- a/contrib/libs/grpc/src/proto/grpc/status/README
+++ b/contrib/libs/grpc/src/proto/grpc/status/README
@@ -1,2 +1,2 @@
-The status.proto file is copied from
-https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto.
+The status.proto file is copied from
+https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto.
diff --git a/contrib/libs/grpc/src/proto/grpc/status/status.proto b/contrib/libs/grpc/src/proto/grpc/status/status.proto
index bc6097b29fb..493aaed7c7c 100644
--- a/contrib/libs/grpc/src/proto/grpc/status/status.proto
+++ b/contrib/libs/grpc/src/proto/grpc/status/status.proto
@@ -1,92 +1,92 @@
-// Copyright 2016 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT 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 google.rpc;
-
-import "google/protobuf/any.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/rpc/status;status";
-option java_multiple_files = true;
-option java_outer_classname = "StatusProto";
-option java_package = "com.google.rpc";
-option objc_class_prefix = "RPC";
-
-
-// The `Status` type defines a logical error model that is suitable for different
-// programming environments, including REST APIs and RPC APIs. It is used by
-// [gRPC](https://github.com/grpc). The error model is designed to be:
-//
-// - Simple to use and understand for most users
-// - Flexible enough to meet unexpected needs
-//
-// # Overview
-//
-// The `Status` message contains three pieces of data: error code, error message,
-// and error details. The error code should be an enum value of
-// [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The
-// error message should be a developer-facing English message that helps
-// developers *understand* and *resolve* the error. If a localized user-facing
-// error message is needed, put the localized message in the error details or
-// localize it in the client. The optional error details may contain arbitrary
-// information about the error. There is a predefined set of error detail types
-// in the package `google.rpc` which can be used for common error conditions.
-//
-// # Language mapping
-//
-// The `Status` message is the logical representation of the error model, but it
-// is not necessarily the actual wire format. When the `Status` message is
-// exposed in different client libraries and different wire protocols, it can be
-// mapped differently. For example, it will likely be mapped to some exceptions
-// in Java, but more likely mapped to some error codes in C.
-//
-// # Other uses
-//
-// The error model and the `Status` message can be used in a variety of
-// environments, either with or without APIs, to provide a
-// consistent developer experience across different environments.
-//
-// Example uses of this error model include:
-//
-// - Partial errors. If a service needs to return partial errors to the client,
-// it may embed the `Status` in the normal response to indicate the partial
-// errors.
-//
-// - Workflow errors. A typical workflow has multiple steps. Each step may
-// have a `Status` message for error reporting purpose.
-//
-// - Batch operations. If a client uses batch request and batch response, the
-// `Status` message should be used directly inside batch response, one for
-// each error sub-response.
-//
-// - Asynchronous operations. If an API call embeds asynchronous operation
-// results in its response, the status of those operations should be
-// represented directly using the `Status` message.
-//
-// - Logging. If some API errors are stored in logs, the message `Status` could
-// be used directly after any stripping needed for security/privacy reasons.
-message Status {
- // The status code, which should be an enum value of [google.rpc.Code][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][google.rpc.Status.details] field, or localized by the client.
- string message = 2;
-
- // A list of messages that carry the error details. There will be a
- // common set of message types for APIs to use.
- repeated google.protobuf.Any details = 3;
-}
+// Copyright 2016 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 google.rpc;
+
+import "google/protobuf/any.proto";
+
+option go_package = "google.golang.org/genproto/googleapis/rpc/status;status";
+option java_multiple_files = true;
+option java_outer_classname = "StatusProto";
+option java_package = "com.google.rpc";
+option objc_class_prefix = "RPC";
+
+
+// The `Status` type defines a logical error model that is suitable for different
+// programming environments, including REST APIs and RPC APIs. It is used by
+// [gRPC](https://github.com/grpc). The error model is designed to be:
+//
+// - Simple to use and understand for most users
+// - Flexible enough to meet unexpected needs
+//
+// # Overview
+//
+// The `Status` message contains three pieces of data: error code, error message,
+// and error details. The error code should be an enum value of
+// [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The
+// error message should be a developer-facing English message that helps
+// developers *understand* and *resolve* the error. If a localized user-facing
+// error message is needed, put the localized message in the error details or
+// localize it in the client. The optional error details may contain arbitrary
+// information about the error. There is a predefined set of error detail types
+// in the package `google.rpc` which can be used for common error conditions.
+//
+// # Language mapping
+//
+// The `Status` message is the logical representation of the error model, but it
+// is not necessarily the actual wire format. When the `Status` message is
+// exposed in different client libraries and different wire protocols, it can be
+// mapped differently. For example, it will likely be mapped to some exceptions
+// in Java, but more likely mapped to some error codes in C.
+//
+// # Other uses
+//
+// The error model and the `Status` message can be used in a variety of
+// environments, either with or without APIs, to provide a
+// consistent developer experience across different environments.
+//
+// Example uses of this error model include:
+//
+// - Partial errors. If a service needs to return partial errors to the client,
+// it may embed the `Status` in the normal response to indicate the partial
+// errors.
+//
+// - Workflow errors. A typical workflow has multiple steps. Each step may
+// have a `Status` message for error reporting purpose.
+//
+// - Batch operations. If a client uses batch request and batch response, the
+// `Status` message should be used directly inside batch response, one for
+// each error sub-response.
+//
+// - Asynchronous operations. If an API call embeds asynchronous operation
+// results in its response, the status of those operations should be
+// represented directly using the `Status` message.
+//
+// - Logging. If some API errors are stored in logs, the message `Status` could
+// be used directly after any stripping needed for security/privacy reasons.
+message Status {
+ // The status code, which should be an enum value of [google.rpc.Code][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][google.rpc.Status.details] field, or localized by the client.
+ string message = 2;
+
+ // A list of messages that carry the error details. There will be a
+ // common set of message types for APIs to use.
+ repeated google.protobuf.Any details = 3;
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto
index 63167a8cee6..55cea139e0c 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto
@@ -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.
-
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto3";
-
-import "src/proto/grpc/testing/messages.proto";
-
-package grpc.testing;
-
-service BenchmarkService {
- // One request followed by one response.
- // The server returns the client payload as-is.
- rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // Repeated sequence of one request followed by one response.
- // Should be called streaming ping-pong
- // The server returns the client payload as-is on each response
- rpc StreamingCall(stream SimpleRequest) returns (stream SimpleResponse);
-
- // Single-sided unbounded streaming from client to server
- // The server returns the client payload as-is once the client does WritesDone
- rpc StreamingFromClient(stream SimpleRequest) returns (SimpleResponse);
-
- // Single-sided unbounded streaming from server to client
- // The server repeatedly returns the client payload as-is
- rpc StreamingFromServer(SimpleRequest) returns (stream SimpleResponse);
-
- // Two-sided unbounded streaming between server to client
- // Both sides send the content of their own choice to the other
- rpc StreamingBothWays(stream SimpleRequest) returns (stream SimpleResponse);
-}
+// 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.
+
+// An integration test service that covers all the method signature permutations
+// of unary/streaming requests/responses.
+syntax = "proto3";
+
+import "src/proto/grpc/testing/messages.proto";
+
+package grpc.testing;
+
+service BenchmarkService {
+ // One request followed by one response.
+ // The server returns the client payload as-is.
+ rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
+
+ // Repeated sequence of one request followed by one response.
+ // Should be called streaming ping-pong
+ // The server returns the client payload as-is on each response
+ rpc StreamingCall(stream SimpleRequest) returns (stream SimpleResponse);
+
+ // Single-sided unbounded streaming from client to server
+ // The server returns the client payload as-is once the client does WritesDone
+ rpc StreamingFromClient(stream SimpleRequest) returns (SimpleResponse);
+
+ // Single-sided unbounded streaming from server to client
+ // The server repeatedly returns the client payload as-is
+ rpc StreamingFromServer(SimpleRequest) returns (stream SimpleResponse);
+
+ // Two-sided unbounded streaming between server to client
+ // Both sides send the content of their own choice to the other
+ rpc StreamingBothWays(stream SimpleRequest) returns (stream SimpleResponse);
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto
index 9fa5590a594..39fdee14989 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto
@@ -1,16 +1,16 @@
-// Copyright 2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 detached comment 1
@@ -47,14 +47,14 @@ service ServiceA {
// Method A2 leading comment 2
rpc MethodA2(stream Request) returns (Response);
// MethodA2 trailing comment 1
-
- // Method A3 leading comment 1
- rpc MethodA3(Request) returns (stream Response);
- // Method A3 trailing comment 1
-
- // Method A4 leading comment 1
- rpc MethodA4(stream Request) returns (stream Response);
- // Method A4 trailing comment 1
+
+ // Method A3 leading comment 1
+ rpc MethodA3(Request) returns (stream Response);
+ // Method A3 trailing comment 1
+
+ // Method A4 leading comment 1
+ rpc MethodA4(stream Request) returns (stream Response);
+ // Method A4 trailing comment 1
}
// Ignored ServiceA trailing comment 1
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/control.proto b/contrib/libs/grpc/src/proto/grpc/testing/control.proto
index 742b21926e7..f19c4f9769b 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/control.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/control.proto
@@ -1,16 +1,16 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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";
@@ -39,9 +39,9 @@ enum ServerType {
enum RpcType {
UNARY = 0;
STREAMING = 1;
- STREAMING_FROM_CLIENT = 2;
- STREAMING_FROM_SERVER = 3;
- STREAMING_BOTH_WAYS = 4;
+ STREAMING_FROM_CLIENT = 2;
+ STREAMING_FROM_SERVER = 3;
+ STREAMING_BOTH_WAYS = 4;
}
// Parameters of poisson process distribution, which is a good representation
@@ -66,7 +66,7 @@ message LoadParams {
message SecurityParams {
bool use_test_ca = 1;
string server_host_override = 2;
- string cred_type = 3;
+ string cred_type = 3;
}
message ChannelArg {
@@ -104,15 +104,15 @@ message ClientConfig {
string other_client_api = 15;
repeated ChannelArg channel_args = 16;
-
- // Number of threads that share each completion queue
- int32 threads_per_cq = 17;
-
- // Number of messages on a stream before it gets finished/restarted
- int32 messages_per_stream = 18;
-
- // Use coalescing API when possible.
- bool use_coalesce_api = 19;
+
+ // Number of threads that share each completion queue
+ int32 threads_per_cq = 17;
+
+ // Number of messages on a stream before it gets finished/restarted
+ int32 messages_per_stream = 18;
+
+ // Use coalescing API when possible.
+ bool use_coalesce_api = 19;
// If 0, disabled. Else, specifies the period between gathering latency
// medians in milliseconds.
@@ -146,10 +146,10 @@ message ServerConfig {
int32 async_server_threads = 7;
// Specify the number of cores to limit server to, if desired
int32 core_limit = 8;
- // payload config, used in generic server.
- // Note this must NOT be used in proto (non-generic) servers. For proto servers,
- // 'response sizes' must be configured from the 'response_size' field of the
- // 'SimpleRequest' objects in RPC requests.
+ // payload config, used in generic server.
+ // Note this must NOT be used in proto (non-generic) servers. For proto servers,
+ // 'response sizes' must be configured from the 'response_size' field of the
+ // 'SimpleRequest' objects in RPC requests.
PayloadConfig payload_config = 9;
// Specify the cores we should run the server on, if desired
@@ -158,14 +158,14 @@ message ServerConfig {
// If we use an OTHER_SERVER client_type, this string gives more detail
string other_server_api = 11;
- // Number of threads that share each completion queue
- int32 threads_per_cq = 12;
-
+ // Number of threads that share each completion queue
+ int32 threads_per_cq = 12;
+
// c++-only options (for now) --------------------------------
// Buffer pool size (no buffer pool specified if unset)
int32 resource_quota_size = 1001;
- repeated ChannelArg channel_args = 1002;
+ repeated ChannelArg channel_args = 1002;
// Number of server processes. 0 indicates no restriction.
int32 server_processes = 21;
@@ -257,14 +257,14 @@ message ScenarioResultSummary
// Number of requests that succeeded/failed
double successful_requests_per_second = 13;
double failed_requests_per_second = 14;
-
- // Number of polls called inside completion queue per request
- double client_polls_per_request = 15;
- double server_polls_per_request = 16;
-
- // Queries per CPU-sec over all servers or clients
- double server_queries_per_cpu_sec = 17;
- double client_queries_per_cpu_sec = 18;
+
+ // Number of polls called inside completion queue per request
+ double client_polls_per_request = 15;
+ double server_polls_per_request = 16;
+
+ // Queries per CPU-sec over all servers or clients
+ double server_queries_per_cpu_sec = 17;
+ double client_queries_per_cpu_sec = 18;
}
// Results of a single benchmark scenario.
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto b/contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto
index 24b7ee0a246..4c2bf9c0f7f 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto
@@ -1,17 +1,17 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 a partial copy of echo.proto with a different package name.
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/echo.proto b/contrib/libs/grpc/src/proto/grpc/testing/echo.proto
index 33db1118648..8a56b53e2d3 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/echo.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/echo.proto
@@ -1,17 +1,17 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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";
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 6f1e5f34046..344ae1e0050 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto
@@ -1,17 +1,17 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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";
@@ -25,13 +25,13 @@ message DebugInfo {
string detail = 2;
}
-// Error status client expects to see.
-message ErrorStatus {
- int32 code = 1;
- string error_message = 2;
- string binary_error_details = 3;
-}
-
+// Error status client expects to see.
+message ErrorStatus {
+ int32 code = 1;
+ string error_message = 2;
+ string binary_error_details = 3;
+}
+
message RequestParams {
bool echo_deadline = 1;
int32 client_cancel_after_us = 2;
@@ -44,9 +44,9 @@ message RequestParams {
bool skip_cancelled_check = 9;
string expected_transport_security_type = 10;
DebugInfo debug_info = 11;
- bool server_die = 12; // Server should not see a request with this set.
- string binary_error_details = 13;
- ErrorStatus expected_error = 14;
+ bool server_die = 12; // Server should not see a request with this set.
+ string binary_error_details = 13;
+ 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;
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/empty.proto b/contrib/libs/grpc/src/proto/grpc/testing/empty.proto
index 6a0aa88dfde..018fedb8081 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/empty.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/empty.proto
@@ -1,17 +1,17 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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";
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
index 70e34277607..a4fef6f99a8 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
@@ -1,17 +1,17 @@
-// Copyright 2015-2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
// Message definitions to be used by integration test service definitions.
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto b/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
index 69504006431..bf32bb73215 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
@@ -1,16 +1,16 @@
-// Copyright 2015-2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
// Contains the definitions for a metrics service and the type of metrics
// exposed by the service.
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/payloads.proto b/contrib/libs/grpc/src/proto/grpc/testing/payloads.proto
index 4feab92eab6..d68a2c636f3 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/payloads.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/payloads.proto
@@ -1,16 +1,16 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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";
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2.proto b/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2.proto
index 666862e6c2d..b0ed58d2405 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2.proto
@@ -1,17 +1,17 @@
-// Copyright 2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 = "proto2";
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2_extensions.proto b/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2_extensions.proto
index fca59f68c96..51124e76252 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2_extensions.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/proto2/empty2_extensions.proto
@@ -1,16 +1,16 @@
-// Copyright 2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 = "proto2";
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto b/contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto
index deaabd13651..df6bbc451a8 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto
@@ -1,31 +1,31 @@
-// 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.
-
-syntax = "proto3";
-
-import "src/proto/grpc/testing/control.proto";
-import "src/proto/grpc/testing/stats.proto";
-
-package grpc.testing;
-
-message ProxyStat {
- double latency = 1;
-}
-
-service ProxyClientService {
- rpc GetConfig(Void) returns (ClientConfig);
- rpc ReportTime(stream ProxyStat) returns (Void);
- rpc ReportHist(stream HistogramData) returns (Void);
-}
-
+// 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.
+
+syntax = "proto3";
+
+import "src/proto/grpc/testing/control.proto";
+import "src/proto/grpc/testing/stats.proto";
+
+package grpc.testing;
+
+message ProxyStat {
+ double latency = 1;
+}
+
+service ProxyClientService {
+ rpc GetConfig(Void) returns (ClientConfig);
+ rpc ReportTime(stream ProxyStat) returns (Void);
+ rpc ReportHist(stream HistogramData) returns (Void);
+}
+
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto
index f4e5c36254c..303e60ca364 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto
@@ -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.
-
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto3";
-
-import "src/proto/grpc/testing/control.proto";
-
-package grpc.testing;
-
-service ReportQpsScenarioService {
- // Report results of a QPS test benchmark scenario.
- rpc ReportScenario(ScenarioResult) returns (Void);
-}
+// 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.
+
+// An integration test service that covers all the method signature permutations
+// of unary/streaming requests/responses.
+syntax = "proto3";
+
+import "src/proto/grpc/testing/control.proto";
+
+package grpc.testing;
+
+service ReportQpsScenarioService {
+ // Report results of a QPS test benchmark scenario.
+ rpc ReportScenario(ScenarioResult) returns (Void);
+}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/stats.proto b/contrib/libs/grpc/src/proto/grpc/testing/stats.proto
index a0f84ddbcee..9415eba96bf 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/stats.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/stats.proto
@@ -1,23 +1,23 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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.testing;
-import "src/proto/grpc/core/stats.proto";
-
+import "src/proto/grpc/core/stats.proto";
+
message ServerStats {
// wall clock time change in seconds since last reset
double time_elapsed = 1;
@@ -34,12 +34,12 @@ message ServerStats {
// change in idle time of the server (data from proc/stat)
uint64 idle_cpu_time = 5;
-
- // Number of polls called inside completion queue
- uint64 cq_poll_count = 6;
-
- // Core library stats
- grpc.core.Stats core_stats = 7;
+
+ // Number of polls called inside completion queue
+ uint64 cq_poll_count = 6;
+
+ // Core library stats
+ grpc.core.Stats core_stats = 7;
}
// Histogram params based on grpc/support/histogram.c
@@ -74,10 +74,10 @@ message ClientStats {
// Number of failed requests (one row per status code seen)
repeated RequestResultCount request_results = 5;
-
- // Number of polls called inside completion queue
- uint64 cq_poll_count = 6;
-
- // Core library stats
- grpc.core.Stats core_stats = 7;
+
+ // Number of polls called inside completion queue
+ uint64 cq_poll_count = 6;
+
+ // Core library stats
+ grpc.core.Stats core_stats = 7;
}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/test.proto b/contrib/libs/grpc/src/proto/grpc/testing/test.proto
index 1da43f48989..a6e57517230 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/test.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/test.proto
@@ -1,17 +1,17 @@
-// Copyright 2015-2016 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 integration test service that covers all the method signature permutations
// of unary/streaming requests/responses.
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto
index a4cde944b07..a47ac07ef0a 100644
--- a/contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto
+++ b/contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto
@@ -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.
-
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto3";
-
-import "src/proto/grpc/testing/control.proto";
-
-package grpc.testing;
-
-service WorkerService {
- // Start server with specified workload.
- // First request sent specifies the ServerConfig followed by ServerStatus
- // response. After that, a "Mark" can be sent anytime to request the latest
- // stats. Closing the stream will initiate shutdown of the test server
- // and once the shutdown has finished, the OK status is sent to terminate
- // this RPC.
- rpc RunServer(stream ServerArgs) returns (stream ServerStatus);
-
- // Start client with specified workload.
- // First request sent specifies the ClientConfig followed by ClientStatus
- // response. After that, a "Mark" can be sent anytime to request the latest
- // stats. Closing the stream will initiate shutdown of the test client
- // and once the shutdown has finished, the OK status is sent to terminate
- // this RPC.
- rpc RunClient(stream ClientArgs) returns (stream ClientStatus);
-
- // Just return the core count - unary call
- rpc CoreCount(CoreRequest) returns (CoreResponse);
-
- // Quit this worker
- rpc QuitWorker(Void) returns (Void);
-}
+// 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.
+
+// An integration test service that covers all the method signature permutations
+// of unary/streaming requests/responses.
+syntax = "proto3";
+
+import "src/proto/grpc/testing/control.proto";
+
+package grpc.testing;
+
+service WorkerService {
+ // Start server with specified workload.
+ // First request sent specifies the ServerConfig followed by ServerStatus
+ // response. After that, a "Mark" can be sent anytime to request the latest
+ // stats. Closing the stream will initiate shutdown of the test server
+ // and once the shutdown has finished, the OK status is sent to terminate
+ // this RPC.
+ rpc RunServer(stream ServerArgs) returns (stream ServerStatus);
+
+ // Start client with specified workload.
+ // First request sent specifies the ClientConfig followed by ClientStatus
+ // response. After that, a "Mark" can be sent anytime to request the latest
+ // stats. Closing the stream will initiate shutdown of the test client
+ // and once the shutdown has finished, the OK status is sent to terminate
+ // this RPC.
+ rpc RunClient(stream ClientArgs) returns (stream ClientStatus);
+
+ // Just return the core count - unary call
+ rpc CoreCount(CoreRequest) returns (CoreResponse);
+
+ // Quit this worker
+ rpc QuitWorker(Void) returns (Void);
+}
diff --git a/contrib/libs/grpc/src/proto/math/math.proto b/contrib/libs/grpc/src/proto/math/math.proto
index e60ba0d7cdc..570be59dd23 100644
--- a/contrib/libs/grpc/src/proto/math/math.proto
+++ b/contrib/libs/grpc/src/proto/math/math.proto
@@ -1,17 +1,17 @@
-// Copyright 2015 gRPC authors.
+// 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
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
//
-// http://www.apache.org/licenses/LICENSE-2.0
+// http://www.apache.org/licenses/LICENSE-2.0
//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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";
diff --git a/contrib/libs/grpc/src/python/grpcio/README.rst b/contrib/libs/grpc/src/python/grpcio/README.rst
index fe34ad5adfe..63651c15486 100644
--- a/contrib/libs/grpc/src/python/grpcio/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio/README.rst
@@ -15,7 +15,7 @@ Python >= 3.5
Installation
------------
-gRPC Python is available for Linux, macOS, and Windows.
+gRPC Python is available for Linux, macOS, and Windows.
Installing From PyPI
~~~~~~~~~~~~~~~~~~~~
diff --git a/contrib/libs/grpc/src/python/grpcio/_spawn_patch.py b/contrib/libs/grpc/src/python/grpcio/_spawn_patch.py
index 377cc7a9f37..a7f79f1e1e7 100644
--- a/contrib/libs/grpc/src/python/grpcio/_spawn_patch.py
+++ b/contrib/libs/grpc/src/python/grpcio/_spawn_patch.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Patches the spawn() command for windows compilers.
Windows has an 8191 character command line limit, but some compilers
diff --git a/contrib/libs/grpc/src/python/grpcio/commands.py b/contrib/libs/grpc/src/python/grpcio/commands.py
index 8240beb2958..ef660a74583 100644
--- a/contrib/libs/grpc/src/python/grpcio/commands.py
+++ b/contrib/libs/grpc/src/python/grpcio/commands.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 __future__ import print_function
@@ -76,8 +76,8 @@ def _get_grpc_custom_bdist(decorated_basename, target_bdist_basename):
with open(bdist_path, 'w') as bdist_file:
bdist_file.write(bdist_data)
except IOError as error:
- raise CommandError('{}\n\nCould not write grpcio bdist: {}'.format(
- traceback.format_exc(), error.message))
+ raise CommandError('{}\n\nCould not write grpcio bdist: {}'.format(
+ traceback.format_exc(), error.message))
return bdist_path
@@ -206,7 +206,7 @@ class BuildExt(build_ext.build_ext):
"""Custom build_ext command to enable compiler-specific flags."""
C_OPTIONS = {
- 'unix': ('-pthread',),
+ 'unix': ('-pthread',),
'msvc': (),
}
LINK_OPTIONS = {}
@@ -238,7 +238,7 @@ class BuildExt(build_ext.build_ext):
# 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 = [
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py
index abe87458c4f..8e15f3ac51c 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py
@@ -1,16 +1,16 @@
-# Copyright 2015-2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""gRPC's Python API."""
import abc
@@ -44,160 +44,160 @@ class FutureCancelledError(Exception):
class Future(six.with_metaclass(abc.ABCMeta)):
"""A representation of a computation in another control flow.
- Computations represented by a Future may be yet to be begun,
- may be ongoing, or may have already completed.
- """
+ Computations represented by a Future may be yet to be begun,
+ may be ongoing, or may have already completed.
+ """
@abc.abstractmethod
def cancel(self):
"""Attempts to cancel the computation.
- This method does not block.
+ This method does not block.
- Returns:
- bool:
- Returns True if the computation was canceled.
+ Returns:
+ bool:
+ Returns True if the computation was canceled.
- Returns False under all other circumstances, for example:
+ Returns False under all other circumstances, for example:
- 1. computation has begun and could not be canceled.
- 2. computation has finished
- 3. computation is scheduled for execution and it is impossible
+ 1. computation has begun and could not be canceled.
+ 2. computation has finished
+ 3. computation is scheduled for execution and it is impossible
to determine its state without blocking.
- """
+ """
raise NotImplementedError()
@abc.abstractmethod
def cancelled(self):
"""Describes whether the computation was cancelled.
- This method does not block.
+ This method does not block.
- Returns:
- bool:
- Returns True if the computation was cancelled before its result became
- available.
+ Returns:
+ bool:
+ Returns True if the computation was cancelled before its result became
+ available.
Returns False under all other circumstances, for example:
- 1. computation was not cancelled.
- 2. computation's result is available.
- """
+ 1. computation was not cancelled.
+ 2. computation's result is available.
+ """
raise NotImplementedError()
@abc.abstractmethod
def running(self):
"""Describes whether the computation is taking place.
- This method does not block.
+ This method does not block.
- Returns:
- Returns True if the computation is scheduled for execution or
- currently executing.
+ Returns:
+ Returns True if the computation is scheduled for execution or
+ currently executing.
- Returns False if the computation already executed or was cancelled.
- """
+ Returns False if the computation already executed or was cancelled.
+ """
raise NotImplementedError()
@abc.abstractmethod
def done(self):
"""Describes whether the computation has taken place.
- This method does not block.
+ This method does not block.
- Returns:
- bool:
- Returns True if the computation already executed or was cancelled.
- Returns False if the computation is scheduled for execution or
- currently executing.
- This is exactly opposite of the running() method's result.
- """
+ Returns:
+ bool:
+ Returns True if the computation already executed or was cancelled.
+ Returns False if the computation is scheduled for execution or
+ currently executing.
+ This is exactly opposite of the running() method's result.
+ """
raise NotImplementedError()
@abc.abstractmethod
def result(self, timeout=None):
- """Returns the result of the computation or raises its exception.
+ """Returns the result of the computation or raises its exception.
- This method may return immediately or may block.
+ This method may return immediately or may block.
- Args:
- timeout: The length of time in seconds to wait for the computation to
- finish or be cancelled. If None, the call will block until the
- computations's termination.
+ Args:
+ timeout: The length of time in seconds to wait for the computation to
+ finish or be cancelled. If None, the call will block until the
+ computations's termination.
- Returns:
- The return value of the computation.
+ Returns:
+ The return value of the computation.
- Raises:
- FutureTimeoutError: If a timeout value is passed and the computation
- does not terminate within the allotted time.
- FutureCancelledError: If the computation was cancelled.
- Exception: If the computation raised an exception, this call will
- raise the same exception.
- """
+ Raises:
+ FutureTimeoutError: If a timeout value is passed and the computation
+ does not terminate within the allotted time.
+ FutureCancelledError: If the computation was cancelled.
+ Exception: If the computation raised an exception, this call will
+ raise the same exception.
+ """
raise NotImplementedError()
@abc.abstractmethod
def exception(self, timeout=None):
"""Return the exception raised by the computation.
- This method may return immediately or may block.
+ This method may return immediately or may block.
- Args:
- timeout: The length of time in seconds to wait for the computation to
- terminate or be cancelled. If None, the call will block until the
- computations's termination.
+ Args:
+ timeout: The length of time in seconds to wait for the computation to
+ terminate or be cancelled. If None, the call will block until the
+ computations's termination.
- Returns:
- The exception raised by the computation, or None if the computation
- did not raise an exception.
+ Returns:
+ The exception raised by the computation, or None if the computation
+ did not raise an exception.
- Raises:
- FutureTimeoutError: If a timeout value is passed and the computation
- does not terminate within the allotted time.
- FutureCancelledError: If the computation was cancelled.
- """
+ Raises:
+ FutureTimeoutError: If a timeout value is passed and the computation
+ does not terminate within the allotted time.
+ FutureCancelledError: If the computation was cancelled.
+ """
raise NotImplementedError()
@abc.abstractmethod
def traceback(self, timeout=None):
"""Access the traceback of the exception raised by the computation.
- This method may return immediately or may block.
+ This method may return immediately or may block.
- Args:
- timeout: The length of time in seconds to wait for the computation
- to terminate or be cancelled. If None, the call will block until
- the computation's termination.
+ Args:
+ timeout: The length of time in seconds to wait for the computation
+ to terminate or be cancelled. If None, the call will block until
+ the computation's termination.
- Returns:
- The traceback of the exception raised by the computation, or None
- if the computation did not raise an exception.
+ Returns:
+ The traceback of the exception raised by the computation, or None
+ if the computation did not raise an exception.
- Raises:
- FutureTimeoutError: If a timeout value is passed and the computation
- does not terminate within the allotted time.
- FutureCancelledError: If the computation was cancelled.
- """
+ Raises:
+ FutureTimeoutError: If a timeout value is passed and the computation
+ does not terminate within the allotted time.
+ FutureCancelledError: If the computation was cancelled.
+ """
raise NotImplementedError()
@abc.abstractmethod
def add_done_callback(self, fn):
"""Adds a function to be called at completion of the computation.
- The callback will be passed this Future object describing the outcome
- of the computation. Callbacks will be invoked after the future is
+ The callback will be passed this Future object describing the outcome
+ of the computation. Callbacks will be invoked after the future is
terminated, whether successfully or not.
- If the computation has already completed, the callback will be called
- immediately.
+ 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.
- Args:
- fn: A callable taking this Future object as its single parameter.
- """
+ Args:
+ fn: A callable taking this Future object as its single parameter.
+ """
raise NotImplementedError()
@@ -208,14 +208,14 @@ class Future(six.with_metaclass(abc.ABCMeta)):
class ChannelConnectivity(enum.Enum):
"""Mirrors grpc_connectivity_state in the gRPC Core.
- Attributes:
- IDLE: The channel is idle.
- CONNECTING: The channel is connecting.
- READY: The channel is ready to conduct RPCs.
- TRANSIENT_FAILURE: The channel has seen a failure from which it expects
- to recover.
- SHUTDOWN: The channel has seen a failure from which it cannot recover.
- """
+ Attributes:
+ IDLE: The channel is idle.
+ CONNECTING: The channel is connecting.
+ READY: The channel is ready to conduct RPCs.
+ TRANSIENT_FAILURE: The channel has seen a failure from which it expects
+ to recover.
+ SHUTDOWN: The channel has seen a failure from which it cannot recover.
+ """
IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
READY = (_cygrpc.ConnectivityState.ready, 'ready')
@@ -307,45 +307,45 @@ class RpcContext(six.with_metaclass(abc.ABCMeta)):
@abc.abstractmethod
def is_active(self):
- """Describes whether the RPC is active or has terminated.
-
- Returns:
- bool:
- True if RPC is active, False otherwise.
- """
+ """Describes whether the RPC is active or has terminated.
+
+ Returns:
+ bool:
+ True if RPC is active, False otherwise.
+ """
raise NotImplementedError()
@abc.abstractmethod
def time_remaining(self):
"""Describes the length of allowed time remaining for the RPC.
- Returns:
- A nonnegative float indicating the length of allowed time in seconds
- remaining for the RPC to complete before it is considered to have
- timed out, or None if no deadline was specified for the RPC.
- """
+ Returns:
+ A nonnegative float indicating the length of allowed time in seconds
+ remaining for the RPC to complete before it is considered to have
+ timed out, or None if no deadline was specified for the RPC.
+ """
raise NotImplementedError()
@abc.abstractmethod
def cancel(self):
"""Cancels the RPC.
- Idempotent and has no effect if the RPC has already terminated.
- """
+ Idempotent and has no effect if the RPC has already terminated.
+ """
raise NotImplementedError()
@abc.abstractmethod
def add_callback(self, callback):
"""Registers a callback to be called on RPC termination.
- Args:
- callback: A no-parameter callable to be called on RPC termination.
+ Args:
+ callback: A no-parameter callable to be called on RPC termination.
- Returns:
+ Returns:
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).
- """
+ the callback was not added and will not be called (because the RPC
+ already terminated or some other reason).
+ """
raise NotImplementedError()
@@ -357,244 +357,244 @@ class Call(six.with_metaclass(abc.ABCMeta, RpcContext)):
@abc.abstractmethod
def initial_metadata(self):
- """Accesses the initial metadata sent by the server.
+ """Accesses the initial metadata sent by the server.
- This method blocks until the value is available.
+ This method blocks until the value is available.
- Returns:
- The initial :term:`metadata`.
- """
+ Returns:
+ The initial :term:`metadata`.
+ """
raise NotImplementedError()
@abc.abstractmethod
def trailing_metadata(self):
- """Accesses the trailing metadata sent by the server.
+ """Accesses the trailing metadata sent by the server.
- This method blocks until the value is available.
+ This method blocks until the value is available.
- Returns:
- The trailing :term:`metadata`.
- """
+ Returns:
+ The trailing :term:`metadata`.
+ """
raise NotImplementedError()
@abc.abstractmethod
def code(self):
- """Accesses the status code sent by the server.
+ """Accesses the status code sent by the server.
- This method blocks until the value is available.
+ This method blocks until the value is available.
- Returns:
- The StatusCode value for the RPC.
- """
+ Returns:
+ The StatusCode value for the RPC.
+ """
raise NotImplementedError()
@abc.abstractmethod
def details(self):
- """Accesses the details sent by the server.
-
- This method blocks until the value is available.
-
- Returns:
- The details string of the RPC.
- """
- raise NotImplementedError()
-
-
-############## Invocation-Side Interceptor Interfaces & Classes ##############
-
-
-class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
- """Describes an RPC to be invoked.
-
- This is an EXPERIMENTAL API.
-
- Attributes:
- method: The method name of the RPC.
- timeout: An optional duration of time in seconds to allow for the RPC.
- metadata: Optional :term:`metadata` to be transmitted to
- the service-side of the RPC.
- credentials: An optional CallCredentials for the RPC.
+ """Accesses the details sent by the server.
+
+ This method blocks until the value is available.
+
+ Returns:
+ The details string of the RPC.
+ """
+ raise NotImplementedError()
+
+
+############## Invocation-Side Interceptor Interfaces & Classes ##############
+
+
+class ClientCallDetails(six.with_metaclass(abc.ABCMeta)):
+ """Describes an RPC to be invoked.
+
+ This is an EXPERIMENTAL API.
+
+ Attributes:
+ method: The method name of the RPC.
+ timeout: An optional duration of time in seconds to allow for the RPC.
+ metadata: Optional :term:`metadata` to be transmitted to
+ the service-side of the RPC.
+ 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.
"""
-
-
-class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
- """Affords intercepting unary-unary invocations.
-
- This is an EXPERIMENTAL API.
- """
-
- @abc.abstractmethod
- def intercept_unary_unary(self, continuation, client_call_details, request):
- """Intercepts a unary-unary invocation asynchronously.
-
- Args:
- continuation: A function that proceeds with the invocation by
- executing the next interceptor in chain or invoking the
- actual RPC on the underlying Channel. It is the interceptor's
- responsibility to call it if it decides to move the RPC forward.
- The interceptor can use
- `response_future = continuation(client_call_details, request)`
- to continue with the RPC. `continuation` returns an object that is
- both a Call for the RPC and a Future. In the event of RPC
- completion, the return Call-Future's result value will be
- the response message of the RPC. Should the event terminate
- with non-OK status, the returned Call-Future's exception value
- will be an RpcError.
- client_call_details: A ClientCallDetails object describing the
- outgoing RPC.
- request: The request value for the RPC.
-
- Returns:
- An object that is both a Call for the RPC and a Future.
- In the event of RPC completion, the return Call-Future's
- result value will be the response message of the RPC.
- Should the event terminate with non-OK status, the returned
- Call-Future's exception value will be an RpcError.
- """
- raise NotImplementedError()
-
-
-class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
- """Affords intercepting unary-stream invocations.
-
- This is an EXPERIMENTAL API.
- """
-
- @abc.abstractmethod
- def intercept_unary_stream(self, continuation, client_call_details,
- request):
- """Intercepts a unary-stream invocation.
-
- Args:
- continuation: A function that proceeds with the invocation by
- executing the next interceptor in chain or invoking the
- actual RPC on the underlying Channel. It is the interceptor's
- responsibility to call it if it decides to move the RPC forward.
- The interceptor can use
- `response_iterator = continuation(client_call_details, request)`
- to continue with the RPC. `continuation` returns an object that is
- both a Call for the RPC and an iterator for response values.
- Drawing response values from the returned Call-iterator may
- raise RpcError indicating termination of the RPC with non-OK
- status.
- client_call_details: A ClientCallDetails object describing the
- outgoing RPC.
- request: The request value for the RPC.
-
- Returns:
- An object that is both a Call for the RPC and an iterator of
- response values. Drawing response values from the returned
- Call-iterator may raise RpcError indicating termination of
- the RPC with non-OK status.
- """
+
+
+class UnaryUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
+ """Affords intercepting unary-unary invocations.
+
+ This is an EXPERIMENTAL API.
+ """
+
+ @abc.abstractmethod
+ def intercept_unary_unary(self, continuation, client_call_details, request):
+ """Intercepts a unary-unary invocation asynchronously.
+
+ Args:
+ continuation: A function that proceeds with the invocation by
+ executing the next interceptor in chain or invoking the
+ actual RPC on the underlying Channel. It is the interceptor's
+ responsibility to call it if it decides to move the RPC forward.
+ The interceptor can use
+ `response_future = continuation(client_call_details, request)`
+ to continue with the RPC. `continuation` returns an object that is
+ both a Call for the RPC and a Future. In the event of RPC
+ completion, the return Call-Future's result value will be
+ the response message of the RPC. Should the event terminate
+ with non-OK status, the returned Call-Future's exception value
+ will be an RpcError.
+ client_call_details: A ClientCallDetails object describing the
+ outgoing RPC.
+ request: The request value for the RPC.
+
+ Returns:
+ An object that is both a Call for the RPC and a Future.
+ In the event of RPC completion, the return Call-Future's
+ result value will be the response message of the RPC.
+ Should the event terminate with non-OK status, the returned
+ Call-Future's exception value will be an RpcError.
+ """
raise NotImplementedError()
-class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
- """Affords intercepting stream-unary invocations.
-
- This is an EXPERIMENTAL API.
- """
-
- @abc.abstractmethod
- def intercept_stream_unary(self, continuation, client_call_details,
- request_iterator):
- """Intercepts a stream-unary invocation asynchronously.
-
- Args:
- continuation: A function that proceeds with the invocation by
- executing the next interceptor in chain or invoking the
- actual RPC on the underlying Channel. It is the interceptor's
- responsibility to call it if it decides to move the RPC forward.
- The interceptor can use
+class UnaryStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
+ """Affords intercepting unary-stream invocations.
+
+ This is an EXPERIMENTAL API.
+ """
+
+ @abc.abstractmethod
+ def intercept_unary_stream(self, continuation, client_call_details,
+ request):
+ """Intercepts a unary-stream invocation.
+
+ Args:
+ continuation: A function that proceeds with the invocation by
+ executing the next interceptor in chain or invoking the
+ actual RPC on the underlying Channel. It is the interceptor's
+ responsibility to call it if it decides to move the RPC forward.
+ The interceptor can use
+ `response_iterator = continuation(client_call_details, request)`
+ to continue with the RPC. `continuation` returns an object that is
+ both a Call for the RPC and an iterator for response values.
+ Drawing response values from the returned Call-iterator may
+ raise RpcError indicating termination of the RPC with non-OK
+ status.
+ client_call_details: A ClientCallDetails object describing the
+ outgoing RPC.
+ request: The request value for the RPC.
+
+ Returns:
+ An object that is both a Call for the RPC and an iterator of
+ response values. Drawing response values from the returned
+ Call-iterator may raise RpcError indicating termination of
+ the RPC with non-OK status.
+ """
+ raise NotImplementedError()
+
+
+class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)):
+ """Affords intercepting stream-unary invocations.
+
+ This is an EXPERIMENTAL API.
+ """
+
+ @abc.abstractmethod
+ def intercept_stream_unary(self, continuation, client_call_details,
+ request_iterator):
+ """Intercepts a stream-unary invocation asynchronously.
+
+ Args:
+ continuation: A function that proceeds with the invocation by
+ executing the next interceptor in chain or invoking the
+ actual RPC on the underlying Channel. It is the interceptor's
+ responsibility to call it if it decides to move the RPC forward.
+ The interceptor can use
`response_future = continuation(client_call_details, request_iterator)`
- to continue with the RPC. `continuation` returns an object that is
- both a Call for the RPC and a Future. In the event of RPC completion,
- the return Call-Future's result value will be the response message
- of the RPC. Should the event terminate with non-OK status, the
- returned Call-Future's exception value will be an RpcError.
- client_call_details: A ClientCallDetails object describing the
- outgoing RPC.
- request_iterator: An iterator that yields request values for the RPC.
-
- Returns:
+ to continue with the RPC. `continuation` returns an object that is
+ both a Call for the RPC and a Future. In the event of RPC completion,
+ the return Call-Future's result value will be the response message
+ of the RPC. Should the event terminate with non-OK status, the
+ returned Call-Future's exception value will be an RpcError.
+ client_call_details: A ClientCallDetails object describing the
+ outgoing RPC.
+ request_iterator: An iterator that yields request values for the RPC.
+
+ Returns:
An object that is both a Call for the RPC and a Future.
In the event of RPC completion, the return Call-Future's
result value will be the response message of the RPC.
Should the event terminate with non-OK status, the returned
Call-Future's exception value will be an RpcError.
- """
- raise NotImplementedError()
-
-
-class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
- """Affords intercepting stream-stream invocations.
-
- This is an EXPERIMENTAL API.
- """
-
- @abc.abstractmethod
- def intercept_stream_stream(self, continuation, client_call_details,
- request_iterator):
- """Intercepts a stream-stream invocation.
-
+ """
+ raise NotImplementedError()
+
+
+class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)):
+ """Affords intercepting stream-stream invocations.
+
+ This is an EXPERIMENTAL API.
+ """
+
+ @abc.abstractmethod
+ def intercept_stream_stream(self, continuation, client_call_details,
+ request_iterator):
+ """Intercepts a stream-stream invocation.
+
Args:
- continuation: A function that proceeds with the invocation by
- executing the next interceptor in chain or invoking the
- actual RPC on the underlying Channel. It is the interceptor's
- responsibility to call it if it decides to move the RPC forward.
- The interceptor can use
+ continuation: A function that proceeds with the invocation by
+ executing the next interceptor in chain or invoking the
+ actual RPC on the underlying Channel. It is the interceptor's
+ responsibility to call it if it decides to move the RPC forward.
+ The interceptor can use
`response_iterator = continuation(client_call_details, request_iterator)`
- to continue with the RPC. `continuation` returns an object that is
- both a Call for the RPC and an iterator for response values.
- Drawing response values from the returned Call-iterator may
- raise RpcError indicating termination of the RPC with non-OK
- status.
- client_call_details: A ClientCallDetails object describing the
- outgoing RPC.
- request_iterator: An iterator that yields request values for the RPC.
-
- Returns:
+ to continue with the RPC. `continuation` returns an object that is
+ both a Call for the RPC and an iterator for response values.
+ Drawing response values from the returned Call-iterator may
+ raise RpcError indicating termination of the RPC with non-OK
+ status.
+ client_call_details: A ClientCallDetails object describing the
+ outgoing RPC.
+ request_iterator: An iterator that yields request values for the RPC.
+
+ Returns:
An object that is both a Call for the RPC and an iterator of
response values. Drawing response values from the returned
Call-iterator may raise RpcError indicating termination of
the RPC with non-OK status.
- """
- raise NotImplementedError()
-
-
+ """
+ raise NotImplementedError()
+
+
############ Authentication & Authorization Interfaces & Classes #############
class ChannelCredentials(object):
- """An encapsulation of the data required to create a secure Channel.
+ """An encapsulation of the data required to create a secure Channel.
- This class has no supported interface - it exists to define the type of its
- instances and its instances exist to be passed to other functions. For
- example, ssl_channel_credentials returns an instance of this class and
- secure_channel requires an instance of this class.
- """
+ This class has no supported interface - it exists to define the type of its
+ instances and its instances exist to be passed to other functions. For
+ example, ssl_channel_credentials returns an instance of this class and
+ secure_channel requires an instance of this class.
+ """
def __init__(self, credentials):
self._credentials = credentials
class CallCredentials(object):
- """An encapsulation of the data required to assert an identity over a call.
+ """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 may be composed with ChannelCredentials to always assert
- identity for every call over that Channel.
+ A CallCredentials may be composed with ChannelCredentials to always assert
+ identity for every call over that Channel.
- This class has no supported interface - it exists to define the type of its
- instances and its instances exist to be passed to other functions.
- """
+ This class has no supported interface - it exists to define the type of its
+ instances and its instances exist to be passed to other functions.
+ """
def __init__(self, credentials):
self._credentials = credentials
@@ -603,22 +603,22 @@ class CallCredentials(object):
class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)):
"""Provides information to call credentials metadata plugins.
- Attributes:
- service_url: A string URL of the service being called into.
- method_name: A string of the fully qualified method name being called.
- """
+ Attributes:
+ service_url: A string URL of the service being called into.
+ method_name: A string of the fully qualified method name being called.
+ """
class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)):
"""Callback object received by a metadata plugin."""
def __call__(self, metadata, error):
- """Passes to the gRPC runtime authentication metadata for an RPC.
+ """Passes to the gRPC runtime authentication metadata for an RPC.
- Args:
- metadata: The :term:`metadata` used to construct the CallCredentials.
- error: An Exception to indicate error or None to indicate success.
- """
+ Args:
+ metadata: The :term:`metadata` used to construct the CallCredentials.
+ error: An Exception to indicate error or None to indicate success.
+ """
raise NotImplementedError()
@@ -630,46 +630,46 @@ class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)):
This method will be invoked asynchronously in a separate thread.
- Args:
- context: An AuthMetadataContext providing information on the RPC that
- the plugin is being called to authenticate.
- callback: An AuthMetadataPluginCallback to be invoked either
- synchronously or asynchronously.
- """
+ Args:
+ context: An AuthMetadataContext providing information on the RPC that
+ the plugin is being called to authenticate.
+ callback: An AuthMetadataPluginCallback to be invoked either
+ synchronously or asynchronously.
+ """
raise NotImplementedError()
class ServerCredentials(object):
- """An encapsulation of the data required to open a secure port on a Server.
+ """An encapsulation of the data required to open a secure port on a Server.
- This class has no supported interface - it exists to define the type of its
- instances and its instances exist to be passed to other functions.
- """
+ This class has no supported interface - it exists to define the type of its
+ instances and its instances exist to be passed to other functions.
+ """
def __init__(self, credentials):
self._credentials = credentials
-class ServerCertificateConfiguration(object):
- """A certificate configuration for use with an SSL-enabled Server.
-
- Instances of this class can be returned in the certificate configuration
- fetching callback.
-
- This class has no supported interface -- it exists to define the
- type of its instances and its instances exist to be passed to
- other functions.
- """
-
- def __init__(self, certificate_configuration):
- self._certificate_configuration = certificate_configuration
-
-
+class ServerCertificateConfiguration(object):
+ """A certificate configuration for use with an SSL-enabled Server.
+
+ Instances of this class can be returned in the certificate configuration
+ fetching callback.
+
+ This class has no supported interface -- it exists to define the
+ type of its instances and its instances exist to be passed to
+ other functions.
+ """
+
+ def __init__(self, certificate_configuration):
+ self._certificate_configuration = certificate_configuration
+
+
######################## Multi-Callable Interfaces ###########################
class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a unary-unary RPC from client-side."""
+ """Affords invoking a unary-unary RPC from client-side."""
@abc.abstractmethod
def __call__(self,
@@ -681,12 +681,12 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
compression=None):
"""Synchronously invokes the underlying RPC.
- Args:
- request: The request value for the RPC.
- timeout: An optional duration of time in seconds to allow
- for the RPC.
- metadata: Optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ Args:
+ request: The request value for the RPC.
+ timeout: An optional duration of time in seconds to allow
+ 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -694,14 +694,14 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
compression: An element of grpc.compression, e.g.
grpc.compression.Gzip. This is an EXPERIMENTAL option.
- Returns:
- The response value for the RPC.
+ Returns:
+ The response value for the RPC.
- Raises:
- RpcError: Indicating that the RPC terminated with non-OK status. The
- raised RpcError will also be a Call for the RPC affording the RPC's
- metadata, status code, and details.
- """
+ Raises:
+ RpcError: Indicating that the RPC terminated with non-OK status. The
+ raised RpcError will also be a Call for the RPC affording the RPC's
+ metadata, status code, and details.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -714,12 +714,12 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
compression=None):
"""Synchronously invokes the underlying RPC.
- Args:
- request: The request value for the RPC.
- timeout: An optional durating of time in seconds to allow for
- the RPC.
- metadata: Optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ Args:
+ request: The request value for the RPC.
+ timeout: An optional durating of time in seconds to allow 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -727,14 +727,14 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
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.
+ Returns:
+ The response value for the RPC and a Call value for the RPC.
- Raises:
- RpcError: Indicating that the RPC terminated with non-OK status. The
- raised RpcError will also be a Call for the RPC affording the RPC's
- metadata, status code, and details.
- """
+ Raises:
+ RpcError: Indicating that the RPC terminated with non-OK status. The
+ raised RpcError will also be a Call for the RPC affording the RPC's
+ metadata, status code, and details.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -747,12 +747,12 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
compression=None):
"""Asynchronously invokes the underlying RPC.
- Args:
- request: The request value for the RPC.
- timeout: An optional duration of time in seconds to allow for
- the RPC.
- metadata: Optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ Args:
+ request: The request value for the RPC.
+ timeout: An optional duration of time in seconds to allow 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -760,18 +760,18 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
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.
- In the event of RPC completion, the return Call-Future's result
- value will be the response message of the RPC.
- Should the event terminate with non-OK status,
- the returned Call-Future's exception value will be an RpcError.
- """
+ Returns:
+ An object that is both a Call for the RPC and a Future.
+ In the event of RPC completion, the return Call-Future's result
+ value will be the response message of the RPC.
+ Should the event terminate with non-OK status,
+ the returned Call-Future's exception value will be an RpcError.
+ """
raise NotImplementedError()
class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a unary-stream RPC from client-side."""
+ """Affords invoking a unary-stream RPC from client-side."""
@abc.abstractmethod
def __call__(self,
@@ -783,12 +783,12 @@ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
compression=None):
"""Invokes the underlying RPC.
- Args:
- request: The request value for the RPC.
- timeout: An optional duration of time in seconds to allow for
- the RPC. If None, the timeout is considered infinite.
- metadata: An optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ Args:
+ request: The request value for the RPC.
+ timeout: An optional duration of time in seconds to allow for
+ 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -796,17 +796,17 @@ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
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
- response values. Drawing response values from the returned
- Call-iterator may raise RpcError indicating termination of the
- RPC with non-OK status.
- """
+ Returns:
+ An object that is both a Call for the RPC and an iterator of
+ response values. Drawing response values from the returned
+ Call-iterator may raise RpcError indicating termination of the
+ RPC with non-OK status.
+ """
raise NotImplementedError()
class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a stream-unary RPC from client-side."""
+ """Affords invoking a stream-unary RPC from client-side."""
@abc.abstractmethod
def __call__(self,
@@ -818,13 +818,13 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
compression=None):
"""Synchronously invokes the underlying RPC.
- Args:
- request_iterator: An iterator that yields request values for
- the RPC.
- timeout: An optional duration of time in seconds to allow for
- the RPC. If None, the timeout is considered infinite.
- metadata: Optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ Args:
+ request_iterator: An iterator that yields request values for
+ the RPC.
+ timeout: An optional duration of time in seconds to allow for
+ 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -832,14 +832,14 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
compression: An element of grpc.compression, e.g.
grpc.compression.Gzip. This is an EXPERIMENTAL option.
- Returns:
- The response value for the RPC.
+ Returns:
+ The response value for the RPC.
- Raises:
- RpcError: Indicating that the RPC terminated with non-OK status. The
- raised RpcError will also implement grpc.Call, affording methods
- such as metadata, code, and details.
- """
+ Raises:
+ RpcError: Indicating that the RPC terminated with non-OK status. The
+ raised RpcError will also implement grpc.Call, affording methods
+ such as metadata, code, and details.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -850,15 +850,15 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
credentials=None,
wait_for_ready=None,
compression=None):
- """Synchronously invokes the underlying RPC on the client.
-
- Args:
- request_iterator: An iterator that yields request values for
- the RPC.
- timeout: An optional duration of time in seconds to allow for
- the RPC. If None, the timeout is considered infinite.
- metadata: Optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ """Synchronously invokes the underlying RPC on the client.
+
+ Args:
+ request_iterator: An iterator that yields request values for
+ the RPC.
+ timeout: An optional duration of time in seconds to allow for
+ 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -866,14 +866,14 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
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.
+ Returns:
+ The response value for the RPC and a Call object for the RPC.
- Raises:
- RpcError: Indicating that the RPC terminated with non-OK status. The
- raised RpcError will also be a Call for the RPC affording the RPC's
- metadata, status code, and details.
- """
+ Raises:
+ RpcError: Indicating that the RPC terminated with non-OK status. The
+ raised RpcError will also be a Call for the RPC affording the RPC's
+ metadata, status code, and details.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -884,14 +884,14 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
credentials=None,
wait_for_ready=None,
compression=None):
- """Asynchronously invokes the underlying RPC on the client.
-
- Args:
- request_iterator: An iterator that yields request values for the RPC.
- timeout: An optional duration of time in seconds to allow for
- the RPC. If None, the timeout is considered infinite.
- metadata: Optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ """Asynchronously invokes the underlying RPC on the client.
+
+ Args:
+ request_iterator: An iterator that yields request values for the RPC.
+ timeout: An optional duration of time in seconds to allow for
+ 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -899,18 +899,18 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)):
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.
- In the event of RPC completion, the return Call-Future's result value
- will be the response message of the RPC. Should the event terminate
- with non-OK status, the returned Call-Future's exception value will
- be an RpcError.
- """
+ Returns:
+ An object that is both a Call for the RPC and a Future.
+ In the event of RPC completion, the return Call-Future's result value
+ will be the response message of the RPC. Should the event terminate
+ with non-OK status, the returned Call-Future's exception value will
+ be an RpcError.
+ """
raise NotImplementedError()
class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
- """Affords invoking a stream-stream RPC on client-side."""
+ """Affords invoking a stream-stream RPC on client-side."""
@abc.abstractmethod
def __call__(self,
@@ -920,14 +920,14 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
credentials=None,
wait_for_ready=None,
compression=None):
- """Invokes the underlying RPC on the client.
-
- Args:
- request_iterator: An iterator that yields request values for the RPC.
- timeout: An optional duration of time in seconds to allow for
- the RPC. If not specified, the timeout is considered infinite.
- metadata: Optional :term:`metadata` to be transmitted to the
- service-side of the RPC.
+ """Invokes the underlying RPC on the client.
+
+ Args:
+ request_iterator: An iterator that yields request values for the RPC.
+ timeout: An optional duration of time in seconds to allow for
+ 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.
wait_for_ready: This is an EXPERIMENTAL argument. An optional
@@ -935,12 +935,12 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
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
- response values. Drawing response values from the returned
- Call-iterator may raise RpcError indicating termination of the
- RPC with non-OK status.
- """
+ Returns:
+ An object that is both a Call for the RPC and an iterator of
+ response values. Drawing response values from the returned
+ Call-iterator may raise RpcError indicating termination of the
+ RPC with non-OK status.
+ """
raise NotImplementedError()
@@ -948,41 +948,41 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)):
class Channel(six.with_metaclass(abc.ABCMeta)):
- """Affords RPC invocation via generic methods on client-side.
-
- Channel objects implement the Context Manager type, although they need not
- support being entered and exited multiple times.
- """
+ """Affords RPC invocation via generic methods on client-side.
+ Channel objects implement the Context Manager type, although they need not
+ support being entered and exited multiple times.
+ """
+
@abc.abstractmethod
def subscribe(self, callback, try_to_connect=False):
- """Subscribe to this Channel's connectivity state machine.
-
- A Channel may be in any of the states described by ChannelConnectivity.
- This method allows application to monitor the state transitions.
- The typical use case is to debug or gain better visibility into gRPC
- runtime's state.
-
- Args:
- callback: A callable to be invoked with ChannelConnectivity argument.
- ChannelConnectivity describes current state of the channel.
- The callable will be invoked immediately upon subscription
- and again for every change to ChannelConnectivity until it
- is unsubscribed or this Channel object goes out of scope.
- try_to_connect: A boolean indicating whether or not this Channel
- should attempt to connect immediately. If set to False, gRPC
- runtime decides when to connect.
- """
+ """Subscribe to this Channel's connectivity state machine.
+
+ A Channel may be in any of the states described by ChannelConnectivity.
+ This method allows application to monitor the state transitions.
+ The typical use case is to debug or gain better visibility into gRPC
+ runtime's state.
+
+ Args:
+ callback: A callable to be invoked with ChannelConnectivity argument.
+ ChannelConnectivity describes current state of the channel.
+ The callable will be invoked immediately upon subscription
+ and again for every change to ChannelConnectivity until it
+ is unsubscribed or this Channel object goes out of scope.
+ try_to_connect: A boolean indicating whether or not this Channel
+ should attempt to connect immediately. If set to False, gRPC
+ runtime decides when to connect.
+ """
raise NotImplementedError()
@abc.abstractmethod
def unsubscribe(self, callback):
- """Unsubscribes a subscribed callback from this Channel's connectivity.
+ """Unsubscribes a subscribed callback from this Channel's connectivity.
- Args:
- callback: A callable previously registered with this Channel from
- having been passed to its "subscribe" method.
- """
+ Args:
+ callback: A callable previously registered with this Channel from
+ having been passed to its "subscribe" method.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -992,17 +992,17 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
response_deserializer=None):
"""Creates a UnaryUnaryMultiCallable for a unary-unary method.
- Args:
- method: The name of the RPC method.
+ Args:
+ method: The name of the RPC method.
request_serializer: Optional :term:`serializer` for serializing the request
- message. Request goes unserialized in case None is passed.
+ message. Request goes unserialized in case None is passed.
response_deserializer: Optional :term:`deserializer` for deserializing the
- response message. Response goes undeserialized in case None
- is passed.
+ response message. Response goes undeserialized in case None
+ is passed.
- Returns:
- A UnaryUnaryMultiCallable value for the named unary-unary method.
- """
+ Returns:
+ A UnaryUnaryMultiCallable value for the named unary-unary method.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -1012,17 +1012,17 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
response_deserializer=None):
"""Creates a UnaryStreamMultiCallable for a unary-stream method.
- Args:
- method: The name of the RPC method.
+ Args:
+ method: The name of the RPC method.
request_serializer: Optional :term:`serializer` for serializing the request
- message. Request goes unserialized in case None is passed.
+ message. Request goes unserialized in case None is passed.
response_deserializer: Optional :term:`deserializer` for deserializing the
- response message. Response goes undeserialized in case None is
- passed.
+ response message. Response goes undeserialized in case None is
+ passed.
- Returns:
- A UnaryStreamMultiCallable value for the name unary-stream method.
- """
+ Returns:
+ A UnaryStreamMultiCallable value for the name unary-stream method.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -1032,17 +1032,17 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
response_deserializer=None):
"""Creates a StreamUnaryMultiCallable for a stream-unary method.
- Args:
- method: The name of the RPC method.
+ Args:
+ method: The name of the RPC method.
request_serializer: Optional :term:`serializer` for serializing the request
- message. Request goes unserialized in case None is passed.
+ message. Request goes unserialized in case None is passed.
response_deserializer: Optional :term:`deserializer` for deserializing the
- response message. Response goes undeserialized in case None is
- passed.
+ response message. Response goes undeserialized in case None is
+ passed.
- Returns:
- A StreamUnaryMultiCallable value for the named stream-unary method.
- """
+ Returns:
+ A StreamUnaryMultiCallable value for the named stream-unary method.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -1052,34 +1052,34 @@ class Channel(six.with_metaclass(abc.ABCMeta)):
response_deserializer=None):
"""Creates a StreamStreamMultiCallable for a stream-stream method.
- Args:
- method: The name of the RPC method.
+ Args:
+ method: The name of the RPC method.
request_serializer: Optional :term:`serializer` for serializing the request
- message. Request goes unserialized in case None is passed.
+ message. Request goes unserialized in case None is passed.
response_deserializer: Optional :term:`deserializer` for deserializing the
- response message. Response goes undeserialized in case None
- is passed.
+ response message. Response goes undeserialized in case None
+ is passed.
- Returns:
- A StreamStreamMultiCallable value for the named stream-stream method.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def close(self):
- """Closes this Channel and releases all resources held by it.
-
- Closing the Channel will immediately terminate all RPCs active with the
- Channel and it is not valid to invoke new RPCs with the Channel.
-
- This method is idempotent.
- """
+ Returns:
+ A StreamStreamMultiCallable value for the named stream-stream method.
+ """
raise NotImplementedError()
+ @abc.abstractmethod
+ def close(self):
+ """Closes this Channel and releases all resources held by it.
+
+ Closing the Channel will immediately terminate all RPCs active with the
+ Channel and it is not valid to invoke new RPCs with the Channel.
+
+ This method is idempotent.
+ """
+ raise NotImplementedError()
+
def __enter__(self):
"""Enters the runtime context related to the channel object."""
raise NotImplementedError()
-
+
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exits the runtime context related to the channel object."""
raise NotImplementedError()
@@ -1093,58 +1093,58 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
@abc.abstractmethod
def invocation_metadata(self):
- """Accesses the metadata from the sent by the client.
+ """Accesses the metadata from the sent by the client.
- Returns:
- The invocation :term:`metadata`.
- """
+ Returns:
+ The invocation :term:`metadata`.
+ """
raise NotImplementedError()
@abc.abstractmethod
def peer(self):
"""Identifies the peer that invoked the RPC being serviced.
- Returns:
- A string identifying the peer that invoked the RPC being serviced.
- The string format is determined by gRPC runtime.
- """
+ Returns:
+ A string identifying the peer that invoked the RPC being serviced.
+ The string format is determined by gRPC runtime.
+ """
raise NotImplementedError()
@abc.abstractmethod
- def peer_identities(self):
- """Gets one or more peer identity(s).
-
- Equivalent to
+ def peer_identities(self):
+ """Gets one or more peer identity(s).
+
+ Equivalent to
servicer_context.auth_context().get(servicer_context.peer_identity_key())
-
- Returns:
- An iterable of the identities, or None if the call is not
- authenticated. Each identity is returned as a raw bytes type.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def peer_identity_key(self):
- """The auth property used to identify the peer.
-
- For example, "x509_common_name" or "x509_subject_alternative_name" are
- used to identify an SSL peer.
-
- Returns:
- The auth property (string) that indicates the
- peer identity, or None if the call is not authenticated.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def auth_context(self):
- """Gets the auth context for the call.
-
- Returns:
- A map of strings to an iterable of bytes for each auth property.
- """
- raise NotImplementedError()
-
+
+ Returns:
+ An iterable of the identities, or None if the call is not
+ authenticated. Each identity is returned as a raw bytes type.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def peer_identity_key(self):
+ """The auth property used to identify the peer.
+
+ For example, "x509_common_name" or "x509_subject_alternative_name" are
+ used to identify an SSL peer.
+
+ Returns:
+ The auth property (string) that indicates the
+ peer identity, or None if the call is not authenticated.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def auth_context(self):
+ """Gets the auth context for the call.
+
+ Returns:
+ A map of strings to an iterable of bytes for each auth property.
+ """
+ raise NotImplementedError()
+
def set_compression(self, compression):
"""Set the compression algorithm to be used for the entire call.
@@ -1156,16 +1156,16 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
"""
raise NotImplementedError()
- @abc.abstractmethod
+ @abc.abstractmethod
def send_initial_metadata(self, initial_metadata):
- """Sends the initial metadata value to the client.
+ """Sends the initial metadata value to the client.
- This method need not be called by implementations if they have no
- metadata to add to what the gRPC runtime will transmit.
+ This method need not be called by implementations if they have no
+ metadata to add to what the gRPC runtime will transmit.
- Args:
- initial_metadata: The initial :term:`metadata`.
- """
+ Args:
+ initial_metadata: The initial :term:`metadata`.
+ """
raise NotImplementedError()
@abc.abstractmethod
@@ -1178,34 +1178,34 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
RPC, the value supplied in the final invocation will be the value sent
over the wire.
- This method need not be called by implementations if they have no
- metadata to add to what the gRPC runtime will transmit.
+ This method need not be called by implementations if they have no
+ metadata to add to what the gRPC runtime will transmit.
- Args:
- trailing_metadata: The trailing :term:`metadata`.
- """
+ Args:
+ trailing_metadata: The trailing :term:`metadata`.
+ """
raise NotImplementedError()
@abc.abstractmethod
- def abort(self, code, details):
- """Raises an exception to terminate the RPC with a non-OK status.
-
- The code and details passed as arguments will supercede any existing
- ones.
-
- Args:
- code: A StatusCode object to be sent to the client.
- It must not be StatusCode.OK.
+ def abort(self, code, details):
+ """Raises an exception to terminate the RPC with a non-OK status.
+
+ The code and details passed as arguments will supercede any existing
+ ones.
+
+ 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
- termination of the RPC.
-
- Raises:
- Exception: An exception is always raised to signal the abortion the
- RPC to the gRPC runtime.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
+ termination of the RPC.
+
+ Raises:
+ Exception: An exception is always raised to signal the abortion the
+ RPC to the gRPC runtime.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
def abort_with_status(self, status):
"""Raises an exception to terminate the RPC with a non-OK status.
@@ -1226,27 +1226,27 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
@abc.abstractmethod
def set_code(self, code):
- """Sets the value to be used as status code upon RPC completion.
+ """Sets the value to be used as status code upon RPC completion.
- This method need not be called by method implementations if they wish
- the gRPC runtime to determine the status code of the RPC.
+ This method need not be called by method implementations if they wish
+ the gRPC runtime to determine the status code of the RPC.
- Args:
- code: A StatusCode object to be sent to the client.
- """
+ Args:
+ code: A StatusCode object to be sent to the client.
+ """
raise NotImplementedError()
@abc.abstractmethod
def set_details(self, details):
- """Sets the value to be used as detail string upon RPC completion.
+ """Sets the value to be used as detail string upon RPC completion.
- This method need not be called by method implementations if they have
- no details to transmit.
+ This method need not be called by method implementations if they have
+ no details to transmit.
- Args:
+ Args:
details: A UTF-8-encodable string to be sent to the client upon
- termination of the RPC.
- """
+ termination of the RPC.
+ """
raise NotImplementedError()
def disable_next_message_compression(self):
@@ -1266,46 +1266,46 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)):
class RpcMethodHandler(six.with_metaclass(abc.ABCMeta)):
"""An implementation of a single RPC method.
- Attributes:
- request_streaming: Whether the RPC supports exactly one request message
- or any arbitrary number of request messages.
- response_streaming: Whether the RPC supports exactly one response message
- or any arbitrary number of response messages.
+ Attributes:
+ request_streaming: Whether the RPC supports exactly one request message
+ or any arbitrary number of request messages.
+ response_streaming: Whether the RPC supports exactly one response message
+ or any arbitrary number of response messages.
request_deserializer: A callable :term:`deserializer` that accepts a byte string and
- returns an object suitable to be passed to this object's business
- logic, or None to indicate that this object's business logic should be
- passed the raw request bytes.
+ returns an object suitable to be passed to this object's business
+ logic, or None to indicate that this object's business logic should be
+ passed the raw request bytes.
response_serializer: A callable :term:`serializer` that accepts an object produced
- by this object's business logic and returns a byte string, or None to
- indicate that the byte strings produced by this object's business logic
- should be transmitted on the wire as they are.
- unary_unary: This object's application-specific business logic as a
- callable value that takes a request value and a ServicerContext object
- and returns a response value. Only non-None if both request_streaming
- and response_streaming are False.
- unary_stream: This object's application-specific business logic as a
- callable value that takes a request value and a ServicerContext object
- and returns an iterator of response values. Only non-None if
- request_streaming is False and response_streaming is True.
- stream_unary: This object's application-specific business logic as a
- callable value that takes an iterator of request values and a
- ServicerContext object and returns a response value. Only non-None if
- request_streaming is True and response_streaming is False.
- stream_stream: This object's application-specific business logic as a
- callable value that takes an iterator of request values and a
- ServicerContext object and returns an iterator of response values.
- Only non-None if request_streaming and response_streaming are both
- True.
- """
+ by this object's business logic and returns a byte string, or None to
+ indicate that the byte strings produced by this object's business logic
+ should be transmitted on the wire as they are.
+ unary_unary: This object's application-specific business logic as a
+ callable value that takes a request value and a ServicerContext object
+ and returns a response value. Only non-None if both request_streaming
+ and response_streaming are False.
+ unary_stream: This object's application-specific business logic as a
+ callable value that takes a request value and a ServicerContext object
+ and returns an iterator of response values. Only non-None if
+ request_streaming is False and response_streaming is True.
+ stream_unary: This object's application-specific business logic as a
+ callable value that takes an iterator of request values and a
+ ServicerContext object and returns a response value. Only non-None if
+ request_streaming is True and response_streaming is False.
+ stream_stream: This object's application-specific business logic as a
+ callable value that takes an iterator of request values and a
+ ServicerContext object and returns an iterator of response values.
+ Only non-None if request_streaming and response_streaming are both
+ True.
+ """
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.
- """
+ Attributes:
+ method: The method name of the RPC.
+ invocation_metadata: The :term:`metadata` sent by the client.
+ """
class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
@@ -1313,63 +1313,63 @@ class GenericRpcHandler(six.with_metaclass(abc.ABCMeta)):
@abc.abstractmethod
def service(self, handler_call_details):
- """Returns the handler for servicing the RPC.
+ """Returns the handler for servicing the RPC.
- Args:
- handler_call_details: A HandlerCallDetails describing the RPC.
+ Args:
+ handler_call_details: A HandlerCallDetails describing the RPC.
- Returns:
- An RpcMethodHandler with which the RPC may be serviced if the
- implementation chooses to service this RPC, or None otherwise.
- """
+ Returns:
+ An RpcMethodHandler with which the RPC may be serviced if the
+ implementation chooses to service this RPC, or None otherwise.
+ """
raise NotImplementedError()
class ServiceRpcHandler(six.with_metaclass(abc.ABCMeta, GenericRpcHandler)):
"""An implementation of RPC methods belonging to a service.
- A service handles RPC methods with structured names of the form
- '/Service.Name/Service.Method', where 'Service.Name' is the value
- returned by service_name(), and 'Service.Method' is the method
- name. A service can have multiple method names, but only a single
- service name.
- """
+ A service handles RPC methods with structured names of the form
+ '/Service.Name/Service.Method', where 'Service.Name' is the value
+ returned by service_name(), and 'Service.Method' is the method
+ name. A service can have multiple method names, but only a single
+ service name.
+ """
@abc.abstractmethod
def service_name(self):
- """Returns this service's name.
-
- Returns:
- The service name.
- """
- raise NotImplementedError()
-
-
-#################### Service-Side Interceptor Interfaces #####################
-
-
-class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
- """Affords intercepting incoming RPCs on the service-side.
-
- This is an EXPERIMENTAL API.
+ """Returns this service's name.
+
+ Returns:
+ The service name.
+ """
+ raise NotImplementedError()
+
+
+#################### Service-Side Interceptor Interfaces #####################
+
+
+class ServerInterceptor(six.with_metaclass(abc.ABCMeta)):
+ """Affords intercepting incoming RPCs on the service-side.
+
+ This is an EXPERIMENTAL API.
"""
-
- @abc.abstractmethod
- def intercept_service(self, continuation, handler_call_details):
- """Intercepts incoming RPCs before handing them over to a handler.
-
- Args:
- continuation: A function that takes a HandlerCallDetails and
- proceeds to invoke the next interceptor in the chain, if any,
- or the RPC handler lookup logic, with the call details passed
- as an argument, and returns an RpcMethodHandler instance if
- the RPC is considered serviced, or None otherwise.
- handler_call_details: A HandlerCallDetails describing the RPC.
-
- Returns:
- An RpcMethodHandler with which the RPC may be serviced if the
- interceptor chooses to service this RPC, or None otherwise.
- """
+
+ @abc.abstractmethod
+ def intercept_service(self, continuation, handler_call_details):
+ """Intercepts incoming RPCs before handing them over to a handler.
+
+ Args:
+ continuation: A function that takes a HandlerCallDetails and
+ proceeds to invoke the next interceptor in the chain, if any,
+ or the RPC handler lookup logic, with the call details passed
+ as an argument, and returns an RpcMethodHandler instance if
+ the RPC is considered serviced, or None otherwise.
+ handler_call_details: A HandlerCallDetails describing the RPC.
+
+ Returns:
+ An RpcMethodHandler with which the RPC may be serviced if the
+ interceptor chooses to service this RPC, or None otherwise.
+ """
raise NotImplementedError()
@@ -1383,67 +1383,67 @@ class Server(six.with_metaclass(abc.ABCMeta)):
def add_generic_rpc_handlers(self, generic_rpc_handlers):
"""Registers GenericRpcHandlers with this Server.
- This method is only safe to call before the server is started.
+ This method is only safe to call before the server is started.
- Args:
- generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
- used to service RPCs.
- """
+ Args:
+ generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
+ used to service RPCs.
+ """
raise NotImplementedError()
@abc.abstractmethod
def add_insecure_port(self, address):
- """Opens an insecure port for accepting RPCs.
+ """Opens an insecure port for accepting RPCs.
- This method may only be called before starting the server.
+ This method may only be called before starting the server.
- Args:
+ 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.
- Returns:
- An integer port on which server will accept RPC requests.
- """
+ Returns:
+ An integer port on which server will accept RPC requests.
+ """
raise NotImplementedError()
@abc.abstractmethod
def add_secure_port(self, address, server_credentials):
- """Opens a secure port for accepting RPCs.
+ """Opens a secure port for accepting RPCs.
- This method may only be called before starting the server.
+ 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.
- server_credentials: A ServerCredentials object.
+ 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.
+ server_credentials: A ServerCredentials object.
- Returns:
- An integer port on which server will accept RPC requests.
- """
+ Returns:
+ An integer port on which server will accept RPC requests.
+ """
raise NotImplementedError()
@abc.abstractmethod
def start(self):
- """Starts this Server.
+ """Starts this Server.
- This method may only be called once. (i.e. it is not idempotent).
- """
+ This method may only be called once. (i.e. it is not idempotent).
+ """
raise NotImplementedError()
@abc.abstractmethod
def stop(self, grace):
- """Stops this Server.
+ """Stops this Server.
- This method immediately stop service of new RPCs in all cases.
+ This method immediately stop service of new RPCs in all cases.
- If a grace period is specified, this method returns immediately
- and all RPCs active at the end of the grace period are aborted.
+ If a grace period is specified, this method returns immediately
+ and all RPCs active at the end of the grace period are aborted.
If a grace period is not specified (by passing None for `grace`),
all existing RPCs are aborted immediately and this method
blocks until the last RPC handler terminates.
- This method is idempotent and may be called at any time.
+ This method is idempotent and may be called at any time.
Passing a smaller grace value in a subsequent call will have
the effect of stopping the Server sooner (passing None will
have the effect of stopping the server immediately). Passing
@@ -1451,14 +1451,14 @@ class Server(six.with_metaclass(abc.ABCMeta)):
effect of stopping the server later (i.e. the most restrictive
grace value is used).
- Args:
- grace: A duration of time in seconds or None.
+ Args:
+ grace: A duration of time in seconds or None.
- Returns:
- A threading.Event that will be set when this Server has completely
- stopped, i.e. when running RPCs either complete or are aborted and
- all handlers have terminated.
- """
+ Returns:
+ A threading.Event that will be set when this Server has completely
+ stopped, i.e. when running RPCs either complete or are aborted and
+ all handlers have terminated.
+ """
raise NotImplementedError()
def wait_for_termination(self, timeout=None):
@@ -1493,16 +1493,16 @@ def unary_unary_rpc_method_handler(behavior,
response_serializer=None):
"""Creates an RpcMethodHandler for a unary-unary RPC method.
- Args:
- behavior: The implementation of an RPC that accepts one request
- and returns one response.
+ Args:
+ behavior: The implementation of an RPC that accepts one request
+ and returns one response.
request_deserializer: An optional :term:`deserializer` for request deserialization.
response_serializer: An optional :term:`serializer` for response serialization.
- Returns:
- An RpcMethodHandler object that is typically used by grpc.Server.
- """
- from grpc import _utilities # pylint: disable=cyclic-import
+ Returns:
+ An RpcMethodHandler object that is typically used by grpc.Server.
+ """
+ from grpc import _utilities # pylint: disable=cyclic-import
return _utilities.RpcMethodHandler(False, False, request_deserializer,
response_serializer, behavior, None,
None, None)
@@ -1513,16 +1513,16 @@ def unary_stream_rpc_method_handler(behavior,
response_serializer=None):
"""Creates an RpcMethodHandler for a unary-stream RPC method.
- Args:
- behavior: The implementation of an RPC that accepts one request
- and returns an iterator of response values.
+ Args:
+ behavior: The implementation of an RPC that accepts one request
+ and returns an iterator of response values.
request_deserializer: An optional :term:`deserializer` for request deserialization.
response_serializer: An optional :term:`serializer` for response serialization.
- Returns:
- An RpcMethodHandler object that is typically used by grpc.Server.
- """
- from grpc import _utilities # pylint: disable=cyclic-import
+ Returns:
+ An RpcMethodHandler object that is typically used by grpc.Server.
+ """
+ from grpc import _utilities # pylint: disable=cyclic-import
return _utilities.RpcMethodHandler(False, True, request_deserializer,
response_serializer, None, behavior,
None, None)
@@ -1533,16 +1533,16 @@ def stream_unary_rpc_method_handler(behavior,
response_serializer=None):
"""Creates an RpcMethodHandler for a stream-unary RPC method.
- Args:
- behavior: The implementation of an RPC that accepts an iterator of
- request values and returns a single response value.
+ Args:
+ behavior: The implementation of an RPC that accepts an iterator of
+ request values and returns a single response value.
request_deserializer: An optional :term:`deserializer` for request deserialization.
response_serializer: An optional :term:`serializer` for response serialization.
- Returns:
- An RpcMethodHandler object that is typically used by grpc.Server.
- """
- from grpc import _utilities # pylint: disable=cyclic-import
+ Returns:
+ An RpcMethodHandler object that is typically used by grpc.Server.
+ """
+ from grpc import _utilities # pylint: disable=cyclic-import
return _utilities.RpcMethodHandler(True, False, request_deserializer,
response_serializer, None, None,
behavior, None)
@@ -1553,35 +1553,35 @@ def stream_stream_rpc_method_handler(behavior,
response_serializer=None):
"""Creates an RpcMethodHandler for a stream-stream RPC method.
- Args:
- behavior: The implementation of an RPC that accepts an iterator of
- request values and returns an iterator of response values.
+ Args:
+ behavior: The implementation of an RPC that accepts an iterator of
+ request values and returns an iterator of response values.
request_deserializer: An optional :term:`deserializer` for request deserialization.
response_serializer: An optional :term:`serializer` for response serialization.
- Returns:
- An RpcMethodHandler object that is typically used by grpc.Server.
- """
- from grpc import _utilities # pylint: disable=cyclic-import
+ Returns:
+ An RpcMethodHandler object that is typically used by grpc.Server.
+ """
+ from grpc import _utilities # pylint: disable=cyclic-import
return _utilities.RpcMethodHandler(True, True, request_deserializer,
response_serializer, None, None, None,
behavior)
def method_handlers_generic_handler(service, method_handlers):
- """Creates a GenericRpcHandler from RpcMethodHandlers.
-
- Args:
- service: The name of the service that is implemented by the
- method_handlers.
- method_handlers: A dictionary that maps method names to corresponding
- RpcMethodHandler.
-
- Returns:
- A GenericRpcHandler. This is typically added to the grpc.Server object
- with add_generic_rpc_handlers() before starting the server.
- """
- from grpc import _utilities # pylint: disable=cyclic-import
+ """Creates a GenericRpcHandler from RpcMethodHandlers.
+
+ Args:
+ service: The name of the service that is implemented by the
+ method_handlers.
+ method_handlers: A dictionary that maps method names to corresponding
+ RpcMethodHandler.
+
+ Returns:
+ A GenericRpcHandler. This is typically added to the grpc.Server object
+ with add_generic_rpc_handlers() before starting the server.
+ """
+ from grpc import _utilities # pylint: disable=cyclic-import
return _utilities.DictionaryGenericHandler(service, method_handlers)
@@ -1590,86 +1590,86 @@ def ssl_channel_credentials(root_certificates=None,
certificate_chain=None):
"""Creates a ChannelCredentials for use with an SSL-enabled Channel.
- Args:
- root_certificates: The PEM-encoded root certificates as a byte string,
- or None to retrieve them from a default location chosen by gRPC
- runtime.
- private_key: The PEM-encoded private key as a byte string, or None if no
- private key should be used.
- certificate_chain: The PEM-encoded certificate chain as a byte string
+ Args:
+ root_certificates: The PEM-encoded root certificates as a byte string,
+ or None to retrieve them from a default location chosen by gRPC
+ runtime.
+ private_key: The PEM-encoded private key as a byte string, or None if no
+ private key should be used.
+ certificate_chain: The PEM-encoded certificate chain as a byte string
to use or None if no certificate chain should be used.
- Returns:
- A ChannelCredentials for use with an SSL-enabled Channel.
- """
+ Returns:
+ A ChannelCredentials for use with an SSL-enabled Channel.
+ """
return ChannelCredentials(
- _cygrpc.SSLChannelCredentials(root_certificates, private_key,
- certificate_chain))
+ _cygrpc.SSLChannelCredentials(root_certificates, private_key,
+ certificate_chain))
def metadata_call_credentials(metadata_plugin, name=None):
"""Construct CallCredentials from an AuthMetadataPlugin.
- Args:
- metadata_plugin: An AuthMetadataPlugin to use for authentication.
- name: An optional name for the plugin.
+ Args:
+ metadata_plugin: An AuthMetadataPlugin to use for authentication.
+ name: An optional name for the plugin.
- Returns:
- A CallCredentials.
- """
- from grpc import _plugin_wrapping # pylint: disable=cyclic-import
- return _plugin_wrapping.metadata_plugin_call_credentials(
- metadata_plugin, name)
+ Returns:
+ A CallCredentials.
+ """
+ from grpc import _plugin_wrapping # pylint: disable=cyclic-import
+ return _plugin_wrapping.metadata_plugin_call_credentials(
+ metadata_plugin, name)
def access_token_call_credentials(access_token):
"""Construct CallCredentials from an access token.
- Args:
- access_token: A string to place directly in the http request
- authorization header, for example
- "authorization: Bearer <access_token>".
+ Args:
+ access_token: A string to place directly in the http request
+ authorization header, for example
+ "authorization: Bearer <access_token>".
- Returns:
- A CallCredentials.
- """
- from grpc import _auth # pylint: disable=cyclic-import
- from grpc import _plugin_wrapping # pylint: disable=cyclic-import
- return _plugin_wrapping.metadata_plugin_call_credentials(
- _auth.AccessTokenAuthMetadataPlugin(access_token), None)
+ Returns:
+ A CallCredentials.
+ """
+ from grpc import _auth # pylint: disable=cyclic-import
+ from grpc import _plugin_wrapping # pylint: disable=cyclic-import
+ return _plugin_wrapping.metadata_plugin_call_credentials(
+ _auth.AccessTokenAuthMetadataPlugin(access_token), None)
def composite_call_credentials(*call_credentials):
"""Compose multiple CallCredentials to make a new CallCredentials.
- Args:
- *call_credentials: At least two CallCredentials objects.
+ Args:
+ *call_credentials: At least two CallCredentials objects.
- Returns:
- A CallCredentials object composed of the given CallCredentials objects.
- """
+ Returns:
+ A CallCredentials object composed of the given CallCredentials objects.
+ """
return CallCredentials(
- _cygrpc.CompositeCallCredentials(
- tuple(single_call_credentials._credentials
- for single_call_credentials in call_credentials)))
+ _cygrpc.CompositeCallCredentials(
+ tuple(single_call_credentials._credentials
+ for single_call_credentials in call_credentials)))
def composite_channel_credentials(channel_credentials, *call_credentials):
"""Compose a ChannelCredentials and one or more CallCredentials objects.
- Args:
- channel_credentials: A ChannelCredentials object.
- *call_credentials: One or more CallCredentials objects.
+ Args:
+ channel_credentials: A ChannelCredentials object.
+ *call_credentials: One or more CallCredentials objects.
- Returns:
- A ChannelCredentials composed of the given ChannelCredentials and
- CallCredentials objects.
- """
+ Returns:
+ A ChannelCredentials composed of the given ChannelCredentials and
+ CallCredentials objects.
+ """
return ChannelCredentials(
- _cygrpc.CompositeChannelCredentials(
- tuple(single_call_credentials._credentials
- for single_call_credentials in call_credentials),
- channel_credentials._credentials))
+ _cygrpc.CompositeChannelCredentials(
+ tuple(single_call_credentials._credentials
+ for single_call_credentials in call_credentials),
+ channel_credentials._credentials))
def ssl_server_credentials(private_key_certificate_chain_pairs,
@@ -1677,20 +1677,20 @@ def ssl_server_credentials(private_key_certificate_chain_pairs,
require_client_auth=False):
"""Creates a ServerCredentials for use with an SSL-enabled Server.
- Args:
- private_key_certificate_chain_pairs: A list of pairs of the form
- [PEM-encoded private key, PEM-encoded certificate chain].
- root_certificates: An optional byte string of PEM-encoded client root
- certificates that the server will use to verify client authentication.
- If omitted, require_client_auth must also be False.
- require_client_auth: A boolean indicating whether or not to require
- clients to be authenticated. May only be True if root_certificates
- is not None.
-
- Returns:
- A ServerCredentials for use with an SSL-enabled Server. Typically, this
- object is an argument to add_secure_port() method during server setup.
- """
+ Args:
+ private_key_certificate_chain_pairs: A list of pairs of the form
+ [PEM-encoded private key, PEM-encoded certificate chain].
+ root_certificates: An optional byte string of PEM-encoded client root
+ certificates that the server will use to verify client authentication.
+ If omitted, require_client_auth must also be False.
+ require_client_auth: A boolean indicating whether or not to require
+ clients to be authenticated. May only be True if root_certificates
+ is not None.
+
+ Returns:
+ A ServerCredentials for use with an SSL-enabled Server. Typically, this
+ object is an argument to add_secure_port() method during server setup.
+ """
if not private_key_certificate_chain_pairs:
raise ValueError(
'At least one private key-certificate chain pair is required!')
@@ -1706,61 +1706,61 @@ def ssl_server_credentials(private_key_certificate_chain_pairs,
], require_client_auth))
-def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
- root_certificates=None):
- """Creates a ServerCertificateConfiguration for use with a Server.
-
- Args:
- private_key_certificate_chain_pairs: A collection of pairs of
- the form [PEM-encoded private key, PEM-encoded certificate
- chain].
- root_certificates: An optional byte string of PEM-encoded client root
- certificates that the server will use to verify client authentication.
-
- Returns:
- A ServerCertificateConfiguration that can be returned in the certificate
- configuration fetching callback.
- """
+def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
+ root_certificates=None):
+ """Creates a ServerCertificateConfiguration for use with a Server.
+
+ Args:
+ private_key_certificate_chain_pairs: A collection of pairs of
+ the form [PEM-encoded private key, PEM-encoded certificate
+ chain].
+ root_certificates: An optional byte string of PEM-encoded client root
+ certificates that the server will use to verify client authentication.
+
+ Returns:
+ A ServerCertificateConfiguration that can be returned in the certificate
+ configuration fetching callback.
+ """
if private_key_certificate_chain_pairs:
- return ServerCertificateConfiguration(
- _cygrpc.server_certificate_config_ssl(root_certificates, [
- _cygrpc.SslPemKeyCertPair(key, pem)
- for key, pem in private_key_certificate_chain_pairs
- ]))
+ return ServerCertificateConfiguration(
+ _cygrpc.server_certificate_config_ssl(root_certificates, [
+ _cygrpc.SslPemKeyCertPair(key, pem)
+ for key, pem in private_key_certificate_chain_pairs
+ ]))
else:
raise ValueError(
'At least one private key-certificate chain pair is required!')
-
-
-def dynamic_ssl_server_credentials(initial_certificate_configuration,
- certificate_configuration_fetcher,
- require_client_authentication=False):
- """Creates a ServerCredentials for use with an SSL-enabled Server.
-
- Args:
- initial_certificate_configuration (ServerCertificateConfiguration): The
- certificate configuration with which the server will be initialized.
- certificate_configuration_fetcher (callable): A callable that takes no
- arguments and should return a ServerCertificateConfiguration to
- replace the server's current certificate, or None for no change
- (i.e., the server will continue its current certificate
- config). The library will call this callback on *every* new
- client connection before starting the TLS handshake with the
- client, thus allowing the user application to optionally
- return a new ServerCertificateConfiguration that the server will then
- use for the handshake.
- require_client_authentication: A boolean indicating whether or not to
- require clients to be authenticated.
-
- Returns:
- A ServerCredentials.
- """
- return ServerCredentials(
- _cygrpc.server_credentials_ssl_dynamic_cert_config(
- initial_certificate_configuration,
- certificate_configuration_fetcher, require_client_authentication))
-
-
+
+
+def dynamic_ssl_server_credentials(initial_certificate_configuration,
+ certificate_configuration_fetcher,
+ require_client_authentication=False):
+ """Creates a ServerCredentials for use with an SSL-enabled Server.
+
+ Args:
+ initial_certificate_configuration (ServerCertificateConfiguration): The
+ certificate configuration with which the server will be initialized.
+ certificate_configuration_fetcher (callable): A callable that takes no
+ arguments and should return a ServerCertificateConfiguration to
+ replace the server's current certificate, or None for no change
+ (i.e., the server will continue its current certificate
+ config). The library will call this callback on *every* new
+ client connection before starting the TLS handshake with the
+ client, thus allowing the user application to optionally
+ return a new ServerCertificateConfiguration that the server will then
+ use for the handshake.
+ require_client_authentication: A boolean indicating whether or not to
+ require clients to be authenticated.
+
+ Returns:
+ A ServerCredentials.
+ """
+ return ServerCredentials(
+ _cygrpc.server_credentials_ssl_dynamic_cert_config(
+ initial_certificate_configuration,
+ certificate_configuration_fetcher, require_client_authentication))
+
+
@enum.unique
class LocalConnectionType(enum.Enum):
"""Types of local connection for local credential creation.
@@ -1886,19 +1886,19 @@ def compute_engine_channel_credentials(call_credentials):
def channel_ready_future(channel):
- """Creates a Future that tracks when a Channel is ready.
+ """Creates a Future that tracks when a Channel is ready.
- Cancelling the Future does not affect the channel's state machine.
- It merely decouples the Future from channel state machine.
+ Cancelling the Future does not affect the channel's state machine.
+ It merely decouples the Future from channel state machine.
- Args:
- channel: A Channel object.
+ Args:
+ channel: A Channel object.
- Returns:
- A Future object that matures when the channel connectivity is
+ Returns:
+ A Future object that matures when the channel connectivity is
ChannelConnectivity.READY.
- """
- from grpc import _utilities # pylint: disable=cyclic-import
+ """
+ from grpc import _utilities # pylint: disable=cyclic-import
return _utilities.channel_ready_future(channel)
@@ -1907,17 +1907,17 @@ def insecure_channel(target, options=None, compression=None):
The returned Channel is thread-safe.
- Args:
- target: The server address
+ Args:
+ target: The server address
options: An optional list of key-value pairs (:term:`channel_arguments`
- in gRPC Core runtime) to configure the channel.
+ 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.
- Returns:
+ Returns:
A Channel.
- """
- from grpc import _channel # pylint: disable=cyclic-import
+ """
+ from grpc import _channel # pylint: disable=cyclic-import
return _channel.Channel(target, () if options is None else options, None,
compression)
@@ -1927,18 +1927,18 @@ def secure_channel(target, credentials, options=None, compression=None):
The returned Channel is thread-safe.
- Args:
- target: The server address.
- credentials: A ChannelCredentials instance.
+ Args:
+ target: The server address.
+ credentials: A ChannelCredentials instance.
options: An optional list of key-value pairs (:term:`channel_arguments`
- in gRPC Core runtime) to configure the channel.
+ 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.
- Returns:
+ Returns:
A Channel.
- """
- from grpc import _channel # pylint: disable=cyclic-import
+ """
+ from grpc import _channel # pylint: disable=cyclic-import
from grpc.experimental import _insecure_channel_credentials
if credentials._credentials is _insecure_channel_credentials:
raise ValueError(
@@ -1948,65 +1948,65 @@ def secure_channel(target, credentials, options=None, compression=None):
credentials._credentials, compression)
-def intercept_channel(channel, *interceptors):
- """Intercepts a channel through a set of interceptors.
-
- This is an EXPERIMENTAL API.
-
- Args:
- channel: A Channel.
- interceptors: Zero or more objects of type
- UnaryUnaryClientInterceptor,
- UnaryStreamClientInterceptor,
- StreamUnaryClientInterceptor, or
- StreamStreamClientInterceptor.
- Interceptors are given control in the order they are listed.
-
- Returns:
- A Channel that intercepts each invocation via the provided interceptors.
-
- Raises:
- TypeError: If interceptor does not derive from any of
- UnaryUnaryClientInterceptor,
- UnaryStreamClientInterceptor,
- StreamUnaryClientInterceptor, or
- StreamStreamClientInterceptor.
- """
- from grpc import _interceptor # pylint: disable=cyclic-import
- return _interceptor.intercept_channel(channel, *interceptors)
-
-
-def server(thread_pool,
- handlers=None,
- interceptors=None,
- options=None,
+def intercept_channel(channel, *interceptors):
+ """Intercepts a channel through a set of interceptors.
+
+ This is an EXPERIMENTAL API.
+
+ Args:
+ channel: A Channel.
+ interceptors: Zero or more objects of type
+ UnaryUnaryClientInterceptor,
+ UnaryStreamClientInterceptor,
+ StreamUnaryClientInterceptor, or
+ StreamStreamClientInterceptor.
+ Interceptors are given control in the order they are listed.
+
+ Returns:
+ A Channel that intercepts each invocation via the provided interceptors.
+
+ Raises:
+ TypeError: If interceptor does not derive from any of
+ UnaryUnaryClientInterceptor,
+ UnaryStreamClientInterceptor,
+ StreamUnaryClientInterceptor, or
+ StreamStreamClientInterceptor.
+ """
+ from grpc import _interceptor # pylint: disable=cyclic-import
+ return _interceptor.intercept_channel(channel, *interceptors)
+
+
+def server(thread_pool,
+ handlers=None,
+ interceptors=None,
+ options=None,
maximum_concurrent_rpcs=None,
compression=None):
"""Creates a Server with which RPCs can be serviced.
- Args:
- thread_pool: A futures.ThreadPoolExecutor to be used by the Server
- to execute RPC handlers.
- handlers: An optional list of GenericRpcHandlers used for executing RPCs.
- More handlers may be added by calling add_generic_rpc_handlers any time
- before the server is started.
- interceptors: An optional list of ServerInterceptor objects that observe
- and optionally manipulate the incoming RPCs before handing them over to
- handlers. The interceptors are given control in the order they are
- specified. This is an EXPERIMENTAL API.
+ Args:
+ thread_pool: A futures.ThreadPoolExecutor to be used by the Server
+ to execute RPC handlers.
+ handlers: An optional list of GenericRpcHandlers used for executing RPCs.
+ More handlers may be added by calling add_generic_rpc_handlers any time
+ before the server is started.
+ interceptors: An optional list of ServerInterceptor objects that observe
+ and optionally manipulate the incoming RPCs before handing them over to
+ handlers. The interceptors are given control in the order they are
+ specified. This is an EXPERIMENTAL API.
options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
to configure the channel.
- maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
- will service before returning RESOURCE_EXHAUSTED status, or None to
- indicate no limit.
+ 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.
- Returns:
- A Server object.
- """
- from grpc import _server # pylint: disable=cyclic-import
+ Returns:
+ A Server object.
+ """
+ from grpc import _server # pylint: disable=cyclic-import
return _server.create_server(thread_pool,
() if handlers is None else handlers,
() if interceptors is None else interceptors,
@@ -2042,68 +2042,68 @@ from grpc._runtime_protos import protos, services, protos_and_services # pylint
################################### __all__ #################################
-__all__ = (
- 'FutureTimeoutError',
- 'FutureCancelledError',
- 'Future',
- 'ChannelConnectivity',
- 'StatusCode',
+__all__ = (
+ 'FutureTimeoutError',
+ 'FutureCancelledError',
+ 'Future',
+ 'ChannelConnectivity',
+ 'StatusCode',
'Status',
- 'RpcError',
- 'RpcContext',
- 'Call',
- 'ChannelCredentials',
- 'CallCredentials',
- 'AuthMetadataContext',
- 'AuthMetadataPluginCallback',
- 'AuthMetadataPlugin',
+ 'RpcError',
+ 'RpcContext',
+ 'Call',
+ 'ChannelCredentials',
+ 'CallCredentials',
+ 'AuthMetadataContext',
+ 'AuthMetadataPluginCallback',
+ 'AuthMetadataPlugin',
'Compression',
- 'ClientCallDetails',
- 'ServerCertificateConfiguration',
- 'ServerCredentials',
+ 'ClientCallDetails',
+ 'ServerCertificateConfiguration',
+ 'ServerCredentials',
'LocalConnectionType',
- 'UnaryUnaryMultiCallable',
- 'UnaryStreamMultiCallable',
- 'StreamUnaryMultiCallable',
- 'StreamStreamMultiCallable',
- 'UnaryUnaryClientInterceptor',
- 'UnaryStreamClientInterceptor',
- 'StreamUnaryClientInterceptor',
- 'StreamStreamClientInterceptor',
- 'Channel',
- 'ServicerContext',
- 'RpcMethodHandler',
- 'HandlerCallDetails',
- 'GenericRpcHandler',
- 'ServiceRpcHandler',
- 'Server',
- 'ServerInterceptor',
- 'unary_unary_rpc_method_handler',
- 'unary_stream_rpc_method_handler',
- 'stream_unary_rpc_method_handler',
- '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',
+ 'UnaryUnaryMultiCallable',
+ 'UnaryStreamMultiCallable',
+ 'StreamUnaryMultiCallable',
+ 'StreamStreamMultiCallable',
+ 'UnaryUnaryClientInterceptor',
+ 'UnaryStreamClientInterceptor',
+ 'StreamUnaryClientInterceptor',
+ 'StreamStreamClientInterceptor',
+ 'Channel',
+ 'ServicerContext',
+ 'RpcMethodHandler',
+ 'HandlerCallDetails',
+ 'GenericRpcHandler',
+ 'ServiceRpcHandler',
+ 'Server',
+ 'ServerInterceptor',
+ 'unary_unary_rpc_method_handler',
+ 'unary_stream_rpc_method_handler',
+ 'stream_unary_rpc_method_handler',
+ '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',
'local_channel_credentials',
'local_server_credentials',
'alts_channel_credentials',
'alts_server_credentials',
- 'ssl_server_credentials',
- 'ssl_server_certificate_configuration',
- 'dynamic_ssl_server_credentials',
- 'channel_ready_future',
- 'insecure_channel',
- 'secure_channel',
- 'intercept_channel',
- 'server',
+ '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',
-)
+)
############################### Extension Shims ################################
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py b/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py
index 2d38320afff..e5f3296bede 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""GRPCAuthMetadataPlugins for standard authentication."""
import inspect
@@ -31,7 +31,7 @@ class GoogleCallCredentials(grpc.AuthMetadataPlugin):
# Hack to determine if these are JWT creds and we need to pass
# additional_claims when getting a token
self._is_jwt = 'additional_claims' in inspect.getargspec( # pylint: disable=deprecated-method
- credentials.get_access_token).args
+ credentials.get_access_token).args
def __call__(self, context, callback):
try:
@@ -48,7 +48,7 @@ class GoogleCallCredentials(grpc.AuthMetadataPlugin):
_sign_request(callback, access_token, None)
-class AccessTokenAuthMetadataPlugin(grpc.AuthMetadataPlugin):
+class AccessTokenAuthMetadataPlugin(grpc.AuthMetadataPlugin):
"""Metadata wrapper for raw access token credentials."""
def __init__(self, access_token):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py b/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py
index 11921d78838..e256d67e68a 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py
@@ -1,21 +1,21 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Invocation-side implementation of gRPC Python."""
import copy
import functools
-import logging
+import logging
import os
import sys
import threading
@@ -39,32 +39,32 @@ _EMPTY_FLAGS = 0
_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,
- cygrpc.OperationType.send_close_from_client,
- cygrpc.OperationType.receive_initial_metadata,
- cygrpc.OperationType.receive_message,
- cygrpc.OperationType.receive_status_on_client,
-)
-_UNARY_STREAM_INITIAL_DUE = (
- cygrpc.OperationType.send_initial_metadata,
- cygrpc.OperationType.send_message,
- cygrpc.OperationType.send_close_from_client,
- cygrpc.OperationType.receive_initial_metadata,
- cygrpc.OperationType.receive_status_on_client,
-)
-_STREAM_UNARY_INITIAL_DUE = (
- cygrpc.OperationType.send_initial_metadata,
- cygrpc.OperationType.receive_initial_metadata,
- cygrpc.OperationType.receive_message,
- cygrpc.OperationType.receive_status_on_client,
-)
-_STREAM_STREAM_INITIAL_DUE = (
- cygrpc.OperationType.send_initial_metadata,
- cygrpc.OperationType.receive_initial_metadata,
- cygrpc.OperationType.receive_status_on_client,
-)
+_UNARY_UNARY_INITIAL_DUE = (
+ 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,
+)
+_UNARY_STREAM_INITIAL_DUE = (
+ cygrpc.OperationType.send_initial_metadata,
+ cygrpc.OperationType.send_message,
+ cygrpc.OperationType.send_close_from_client,
+ cygrpc.OperationType.receive_initial_metadata,
+ cygrpc.OperationType.receive_status_on_client,
+)
+_STREAM_UNARY_INITIAL_DUE = (
+ cygrpc.OperationType.send_initial_metadata,
+ cygrpc.OperationType.receive_initial_metadata,
+ cygrpc.OperationType.receive_message,
+ cygrpc.OperationType.receive_status_on_client,
+)
+_STREAM_STREAM_INITIAL_DUE = (
+ cygrpc.OperationType.send_initial_metadata,
+ cygrpc.OperationType.receive_initial_metadata,
+ cygrpc.OperationType.receive_status_on_client,
+)
_CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = (
'Exception calling channel subscription callback!')
@@ -82,7 +82,7 @@ _NON_OK_RENDEZVOUS_REPR_FORMAT = ('<{} of RPC that terminated with:\n'
def _deadline(timeout):
- return None if timeout is None else time.time() + timeout
+ return None if timeout is None else time.time() + timeout
def _unknown_code_details(unknown_cygrpc_code, details):
@@ -120,19 +120,19 @@ def _abort(state, code, details):
state.code = code
state.details = details
if state.initial_metadata is None:
- state.initial_metadata = ()
- state.trailing_metadata = ()
+ state.initial_metadata = ()
+ state.trailing_metadata = ()
def _handle_event(event, state, response_deserializer):
callbacks = []
for batch_operation in event.batch_operations:
- operation_type = batch_operation.type()
+ operation_type = batch_operation.type()
state.due.remove(operation_type)
if operation_type == cygrpc.OperationType.receive_initial_metadata:
- state.initial_metadata = batch_operation.initial_metadata()
+ state.initial_metadata = batch_operation.initial_metadata()
elif operation_type == cygrpc.OperationType.receive_message:
- serialized_response = batch_operation.message()
+ serialized_response = batch_operation.message()
if serialized_response is not None:
response = _common.deserialize(serialized_response,
response_deserializer)
@@ -142,24 +142,24 @@ def _handle_event(event, state, response_deserializer):
else:
state.response = response
elif operation_type == cygrpc.OperationType.receive_status_on_client:
- state.trailing_metadata = batch_operation.trailing_metadata()
+ state.trailing_metadata = batch_operation.trailing_metadata()
if state.code is None:
code = _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE.get(
- batch_operation.code())
+ batch_operation.code())
if code is None:
state.code = grpc.StatusCode.UNKNOWN
state.details = _unknown_code_details(
- code, batch_operation.details())
+ code, batch_operation.details())
else:
state.code = code
- state.details = batch_operation.details()
+ state.details = batch_operation.details()
state.debug_error_string = batch_operation.error_string()
callbacks.extend(state.callbacks)
state.callbacks = None
return callbacks
-def _event_handler(state, response_deserializer):
+def _event_handler(state, response_deserializer):
def handle_event(event):
with state.condition:
@@ -180,11 +180,11 @@ def _event_handler(state, response_deserializer):
#pylint: disable=too-many-statements
-def _consume_request_iterator(request_iterator, state, call, request_serializer,
- event_handler):
+def _consume_request_iterator(request_iterator, state, call, request_serializer,
+ event_handler):
"""Consume a request iterator supplied by the user."""
- def consume_request_iterator(): # pylint: disable=too-many-branches
+ def consume_request_iterator(): # pylint: disable=too-many-branches
# Iterate over the request iterator until it is exhausted or an error
# condition is encountered.
while True:
@@ -195,15 +195,15 @@ def _consume_request_iterator(request_iterator, state, call, request_serializer,
request = next(request_iterator)
except StopIteration:
break
- except Exception: # pylint: disable=broad-except
+ except Exception: # pylint: disable=broad-except
cygrpc.return_from_user_request_generator()
return_from_user_request_generator_invoked = True
- code = grpc.StatusCode.UNKNOWN
- details = 'Exception iterating requests!'
+ code = grpc.StatusCode.UNKNOWN
+ details = 'Exception iterating requests!'
_LOGGER.exception(details)
- call.cancel(_common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code],
- details)
- _abort(state, code, details)
+ call.cancel(_common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code],
+ details)
+ _abort(state, code, details)
return
finally:
if not return_from_user_request_generator_invoked:
@@ -214,19 +214,19 @@ def _consume_request_iterator(request_iterator, state, call, request_serializer,
if serialized_request is None:
code = grpc.StatusCode.INTERNAL
details = 'Exception serializing request!'
- call.cancel(
- _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code],
- details)
- _abort(state, code, details)
+ call.cancel(
+ _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code],
+ details)
+ _abort(state, code, details)
return
else:
- operations = (cygrpc.SendMessageOperation(
+ operations = (cygrpc.SendMessageOperation(
serialized_request, _EMPTY_FLAGS),)
- operating = call.operate(operations, event_handler)
- if operating:
- state.due.add(cygrpc.OperationType.send_message)
- else:
- return
+ operating = call.operate(operations, event_handler)
+ if operating:
+ state.due.add(cygrpc.OperationType.send_message)
+ else:
+ return
def _done():
return (state.code is not None or
@@ -245,10 +245,10 @@ def _consume_request_iterator(request_iterator, state, call, request_serializer,
with state.condition:
if state.code is None:
operations = (
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),)
- operating = call.operate(operations, event_handler)
- if operating:
- state.due.add(cygrpc.OperationType.send_close_from_client)
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),)
+ operating = call.operate(operations, event_handler)
+ if operating:
+ state.due.add(cygrpc.OperationType.send_close_from_client)
consumption_thread = cygrpc.ForkManagedThread(
target=consume_request_iterator)
@@ -386,12 +386,12 @@ class _Rendezvous(grpc.RpcError, grpc.RpcContext):
"""See grpc.RpcContext.cancel"""
with self._state.condition:
if self._state.code is None:
- code = grpc.StatusCode.CANCELLED
- details = 'Locally cancelled by application!'
- self._call.cancel(
- _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details)
+ code = grpc.StatusCode.CANCELLED
+ details = 'Locally cancelled by application!'
+ self._call.cancel(
+ _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details)
self._state.cancelled = True
- _abort(self._state, code, details)
+ _abort(self._state, code, details)
self._state.condition.notify_all()
return True
else:
@@ -773,13 +773,13 @@ class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
def _next(self):
with self._state.condition:
if self._state.code is None:
- event_handler = _event_handler(self._state,
+ event_handler = _event_handler(self._state,
self._response_deserializer)
- operating = self._call.operate(
- (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
+ operating = self._call.operate(
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
event_handler)
- if operating:
- self._state.due.add(cygrpc.OperationType.receive_message)
+ if operating:
+ self._state.due.add(cygrpc.OperationType.receive_message)
elif self._state.code is grpc.StatusCode.OK:
raise StopIteration()
else:
@@ -804,18 +804,18 @@ class _MultiThreadedRendezvous(_Rendezvous, grpc.Call, grpc.Future): # pylint:
def _start_unary_request(request, timeout, request_serializer):
- deadline = _deadline(timeout)
+ deadline = _deadline(timeout)
serialized_request = _common.serialize(request, request_serializer)
if serialized_request is None:
- state = _RPCState((), (), (), grpc.StatusCode.INTERNAL,
+ state = _RPCState((), (), (), grpc.StatusCode.INTERNAL,
'Exception serializing request!')
error = _InactiveRpcError(state)
return deadline, None, error
else:
- return deadline, serialized_request, None
+ return deadline, serialized_request, None
-def _end_unary_response_blocking(state, call, with_call, deadline):
+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)
@@ -827,26 +827,26 @@ def _end_unary_response_blocking(state, call, with_call, deadline):
def _stream_unary_invocation_operationses(metadata, initial_metadata_flags):
- return (
- (
+ return (
+ (
cygrpc.SendInitialMetadataOperation(metadata,
initial_metadata_flags),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ),
- (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
- )
-
-
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+ ),
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+ )
+
+
def _stream_unary_invocation_operationses_and_tags(metadata,
initial_metadata_flags):
- return tuple((
- operations,
- None,
+ return tuple((
+ operations,
+ None,
) for operations in _stream_unary_invocation_operationses(
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:
@@ -872,43 +872,43 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
self._context = cygrpc.build_census_context()
def _prepare(self, request, timeout, metadata, wait_for_ready, compression):
- deadline, serialized_request, rendezvous = _start_unary_request(
- request, timeout, self._request_serializer)
+ 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)
if serialized_request is None:
- return None, None, None, rendezvous
+ return None, None, None, rendezvous
else:
state = _RPCState(_UNARY_UNARY_INITIAL_DUE, None, None, None, None)
operations = (
cygrpc.SendInitialMetadataOperation(augmented_metadata,
initial_metadata_flags),
- cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- )
- return state, operations, deadline, None
+ cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+ )
+ return state, operations, deadline, None
def _blocking(self, request, timeout, metadata, credentials, wait_for_ready,
compression):
- state, operations, deadline, rendezvous = self._prepare(
+ state, operations, deadline, rendezvous = self._prepare(
request, timeout, metadata, wait_for_ready, compression)
- if state is None:
+ if state is None:
raise rendezvous # pylint: disable-msg=raising-bad-type
else:
- call = self._channel.segregated_call(
+ 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, ((
- operations,
- None,
+ operations,
+ None,
),), self._context)
- event = call.next_event()
- _handle_event(event, state, self._response_deserializer)
+ event = call.next_event()
+ _handle_event(event, state, self._response_deserializer)
return state, call
def __call__(self,
@@ -920,7 +920,7 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
compression=None):
state, call, = self._blocking(request, timeout, metadata, credentials,
wait_for_ready, compression)
- return _end_unary_response_blocking(state, call, False, None)
+ return _end_unary_response_blocking(state, call, False, None)
def with_call(self,
request,
@@ -931,7 +931,7 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
compression=None):
state, call, = self._blocking(request, timeout, metadata, credentials,
wait_for_ready, compression)
- return _end_unary_response_blocking(state, call, True, None)
+ return _end_unary_response_blocking(state, call, True, None)
def future(self,
request,
@@ -940,13 +940,13 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
credentials=None,
wait_for_ready=None,
compression=None):
- state, operations, deadline, rendezvous = self._prepare(
+ state, operations, deadline, rendezvous = self._prepare(
request, timeout, metadata, wait_for_ready, compression)
- if state is None:
+ if state is None:
raise rendezvous # pylint: disable-msg=raising-bad-type
else:
- event_handler = _event_handler(state, self._response_deserializer)
- call = self._managed_call(
+ event_handler = _event_handler(state, self._response_deserializer)
+ call = self._managed_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
self._method, None, deadline, metadata,
None if credentials is None else credentials._credentials,
@@ -1026,8 +1026,8 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
credentials=None,
wait_for_ready=None,
compression=None):
- deadline, serialized_request, rendezvous = _start_unary_request(
- request, timeout, self._request_serializer)
+ deadline, serialized_request, rendezvous = _start_unary_request(
+ request, timeout, self._request_serializer)
initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
wait_for_ready)
if serialized_request is None:
@@ -1036,18 +1036,18 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
augmented_metadata = _compression.augment_metadata(
metadata, compression)
state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
- operationses = (
- (
+ operationses = (
+ (
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),),
- )
- call = self._managed_call(
+ cygrpc.SendMessageOperation(serialized_request,
+ _EMPTY_FLAGS),
+ cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+ ),
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+ )
+ call = self._managed_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
self._method, None, _determine_deadline(deadline), metadata,
None if credentials is None else credentials._credentials,
@@ -1073,22 +1073,22 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
def _blocking(self, request_iterator, timeout, metadata, credentials,
wait_for_ready, compression):
- deadline = _deadline(timeout)
+ 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)
- call = self._channel.segregated_call(
+ 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)
- _consume_request_iterator(request_iterator, state, call,
- self._request_serializer, None)
+ _consume_request_iterator(request_iterator, state, call,
+ self._request_serializer, None)
while True:
- event = call.next_event()
+ event = call.next_event()
with state.condition:
_handle_event(event, state, self._response_deserializer)
state.condition.notify_all()
@@ -1103,9 +1103,9 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
credentials=None,
wait_for_ready=None,
compression=None):
- state, call, = self._blocking(request_iterator, timeout, metadata,
+ state, call, = self._blocking(request_iterator, timeout, metadata,
credentials, wait_for_ready, compression)
- return _end_unary_response_blocking(state, call, False, None)
+ return _end_unary_response_blocking(state, call, False, None)
def with_call(self,
request_iterator,
@@ -1114,9 +1114,9 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
credentials=None,
wait_for_ready=None,
compression=None):
- state, call, = self._blocking(request_iterator, timeout, metadata,
+ state, call, = self._blocking(request_iterator, timeout, metadata,
credentials, wait_for_ready, compression)
- return _end_unary_response_blocking(state, call, True, None)
+ return _end_unary_response_blocking(state, call, True, None)
def future(self,
request_iterator,
@@ -1125,22 +1125,22 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
credentials=None,
wait_for_ready=None,
compression=None):
- deadline = _deadline(timeout)
+ deadline = _deadline(timeout)
state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None)
- event_handler = _event_handler(state, self._response_deserializer)
+ 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)
- call = self._managed_call(
+ call = self._managed_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method,
None, deadline, augmented_metadata,
None if credentials is None else credentials._credentials,
_stream_unary_invocation_operationses(metadata,
initial_metadata_flags),
event_handler, self._context)
- _consume_request_iterator(request_iterator, state, call,
- self._request_serializer, event_handler)
+ _consume_request_iterator(request_iterator, state, call,
+ self._request_serializer, event_handler)
return _MultiThreadedRendezvous(state, call,
self._response_deserializer, deadline)
@@ -1164,28 +1164,28 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
credentials=None,
wait_for_ready=None,
compression=None):
- deadline = _deadline(timeout)
+ 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)
- operationses = (
- (
+ operationses = (
+ (
cygrpc.SendInitialMetadataOperation(augmented_metadata,
initial_metadata_flags),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ),
- (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
- )
- event_handler = _event_handler(state, self._response_deserializer)
- call = self._managed_call(
+ cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+ ),
+ (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+ )
+ event_handler = _event_handler(state, self._response_deserializer)
+ call = self._managed_call(
cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method,
None, _determine_deadline(deadline), augmented_metadata,
None if credentials is None else credentials._credentials,
operationses, event_handler, self._context)
- _consume_request_iterator(request_iterator, state, call,
- self._request_serializer, event_handler)
+ _consume_request_iterator(request_iterator, state, call,
+ self._request_serializer, event_handler)
return _MultiThreadedRendezvous(state, call,
self._response_deserializer, deadline)
@@ -1213,7 +1213,7 @@ class _ChannelCallState(object):
def __init__(self, channel):
self.lock = threading.Lock()
self.channel = channel
- self.managed_calls = 0
+ self.managed_calls = 0
self.threading = False
def reset_postfork_child(self):
@@ -1232,14 +1232,14 @@ def _run_channel_spin_thread(state):
def channel_spin():
while True:
cygrpc.block_if_fork_in_progress(state)
- event = state.channel.next_call_event()
+ event = state.channel.next_call_event()
if event.completion_type == cygrpc.CompletionType.queue_timeout:
continue
- call_completed = event.tag(event)
- if call_completed:
+ call_completed = event.tag(event)
+ if call_completed:
with state.lock:
- state.managed_calls -= 1
- if state.managed_calls == 0:
+ state.managed_calls -= 1
+ if state.managed_calls == 0:
return
channel_spin_thread = cygrpc.ForkManagedThread(target=channel_spin)
@@ -1249,41 +1249,41 @@ def _run_channel_spin_thread(state):
def _channel_managed_call_management(state):
- # pylint: disable=too-many-arguments
- def create(flags, method, host, deadline, metadata, credentials,
+ # pylint: disable=too-many-arguments
+ def create(flags, method, host, deadline, metadata, credentials,
operationses, event_handler, context):
- """Creates a cygrpc.IntegratedCall.
-
- Args:
- flags: An integer bitfield of call flags.
- method: The RPC method.
- host: A host string for the created call.
- deadline: A float to be the deadline of the created call or None if
- the call is to have an infinite deadline.
- metadata: The metadata for the call or None.
- credentials: A cygrpc.CallCredentials or None.
- operationses: An iterable of iterables of cygrpc.Operations to be
- started on the call.
- event_handler: A behavior to call to handle the events resultant from
- the operations on the call.
+ """Creates a cygrpc.IntegratedCall.
+
+ Args:
+ flags: An integer bitfield of call flags.
+ method: The RPC method.
+ host: A host string for the created call.
+ deadline: A float to be the deadline of the created call or None if
+ the call is to have an infinite deadline.
+ metadata: The metadata for the call or None.
+ credentials: A cygrpc.CallCredentials or None.
+ operationses: An iterable of iterables of cygrpc.Operations to be
+ started on the call.
+ event_handler: A behavior to call to handle the events resultant from
+ the operations on the call.
context: Context object for distributed tracing.
- Returns:
- A cygrpc.IntegratedCall with which to conduct an RPC.
- """
- operationses_and_tags = tuple((
- operations,
- event_handler,
- ) for operations in operationses)
- with state.lock:
- call = state.channel.integrated_call(flags, method, host, deadline,
- metadata, credentials,
+ Returns:
+ A cygrpc.IntegratedCall with which to conduct an RPC.
+ """
+ operationses_and_tags = tuple((
+ operations,
+ event_handler,
+ ) for operations in operationses)
+ with state.lock:
+ call = state.channel.integrated_call(flags, method, host, deadline,
+ metadata, credentials,
operationses_and_tags, context)
- if state.managed_calls == 0:
- state.managed_calls = 1
- _run_channel_spin_thread(state)
- else:
- state.managed_calls += 1
- return call
+ if state.managed_calls == 0:
+ state.managed_calls = 1
+ _run_channel_spin_thread(state)
+ else:
+ state.managed_calls += 1
+ return call
return create
@@ -1365,8 +1365,8 @@ def _poll_connectivity(state, channel, initial_try_to_connect):
if callbacks:
_spawn_delivery(state, callbacks)
while True:
- event = channel.watch_connectivity_state(connectivity,
- time.time() + 0.2)
+ event = channel.watch_connectivity_state(connectivity,
+ time.time() + 0.2)
cygrpc.block_if_fork_in_progress(state)
with state.lock:
if not state.callbacks_and_connectivities and not state.try_to_connect:
@@ -1409,8 +1409,8 @@ def _subscribe(state, callback, try_to_connect):
def _unsubscribe(state, callback):
with state.lock:
- for index, (subscribed_callback, unused_connectivity) in enumerate(
- state.callbacks_and_connectivities):
+ for index, (subscribed_callback, unused_connectivity) in enumerate(
+ state.callbacks_and_connectivities):
if callback == subscribed_callback:
state.callbacks_and_connectivities.pop(index)
break
@@ -1442,13 +1442,13 @@ class Channel(grpc.Channel):
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.
+ 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.
- """
+ """
python_options, core_options = _separate_channel_options(options)
self._single_threaded_unary_stream = _DEFAULT_SINGLE_THREADED_UNARY_STREAM
self._process_python_options(python_options)
@@ -1476,7 +1476,7 @@ class Channel(grpc.Channel):
request_serializer=None,
response_deserializer=None):
return _UnaryUnaryMultiCallable(
- self._channel, _channel_managed_call_management(self._call_state),
+ self._channel, _channel_managed_call_management(self._call_state),
_common.encode(method), request_serializer, response_deserializer)
def unary_stream(self,
@@ -1503,7 +1503,7 @@ class Channel(grpc.Channel):
request_serializer=None,
response_deserializer=None):
return _StreamUnaryMultiCallable(
- self._channel, _channel_managed_call_management(self._call_state),
+ self._channel, _channel_managed_call_management(self._call_state),
_common.encode(method), request_serializer, response_deserializer)
def stream_stream(self,
@@ -1511,7 +1511,7 @@ class Channel(grpc.Channel):
request_serializer=None,
response_deserializer=None):
return _StreamStreamMultiCallable(
- self._channel, _channel_managed_call_management(self._call_state),
+ self._channel, _channel_managed_call_management(self._call_state),
_common.encode(method), request_serializer, response_deserializer)
def _unsubscribe_all(self):
@@ -1520,36 +1520,36 @@ class Channel(grpc.Channel):
with state.lock:
del state.callbacks_and_connectivities[:]
- def _close(self):
+ def _close(self):
self._unsubscribe_all()
- self._channel.close(cygrpc.StatusCode.cancelled, 'Channel closed!')
+ self._channel.close(cygrpc.StatusCode.cancelled, 'Channel closed!')
cygrpc.fork_unregister_channel(self)
-
+
def _close_on_fork(self):
self._unsubscribe_all()
self._channel.close_on_fork(cygrpc.StatusCode.cancelled,
'Channel closed due to fork')
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- self._close()
- return False
-
- def close(self):
- self._close()
-
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self._close()
+ return False
+
+ def close(self):
+ self._close()
+
def __del__(self):
- # TODO(https://github.com/grpc/grpc/issues/12531): Several releases
- # after 1.12 (1.16 or thereabouts?) add a "self._channel.close" call
- # here (or more likely, call self._close() here). We don't do this today
- # because many valid use cases today allow the channel to be deleted
- # immediately after stubs are created. After a sufficient period of time
- # has passed for all users to be trusted to hang out to their channels
- # 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.
+ # TODO(https://github.com/grpc/grpc/issues/12531): Several releases
+ # after 1.12 (1.16 or thereabouts?) add a "self._channel.close" call
+ # here (or more likely, call self._close() here). We don't do this today
+ # because many valid use cases today allow the channel to be deleted
+ # immediately after stubs are created. After a sufficient period of time
+ # has passed for all users to be trusted to hang out to their channels
+ # 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
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_common.py b/contrib/libs/grpc/src/python/grpcio/grpc/_common.py
index 128124c3256..d86dcbd9bb4 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_common.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_common.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Shared implementation."""
import logging
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/_cython/_cygrpc/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/_cython/_cygrpc/arguments.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi
index 251efe15b39..1b09b8b9846 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
@@ -1,36 +1,36 @@
# 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.
-
-
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 tuple _wrap_grpc_arg(grpc_arg arg)
-
+
cdef grpc_arg _unwrap_grpc_arg(tuple wrapped_arg)
cdef class _ChannelArg:
- cdef grpc_arg c_argument
-
+ cdef grpc_arg c_argument
+
cdef void c(self, argument, references) except *
-
-
+
+
cdef class _ChannelArgs:
-
- cdef readonly tuple _arguments
+
+ cdef readonly tuple _arguments
cdef list _channel_args
- cdef readonly list _references
- cdef grpc_channel_args _c_arguments
-
+ cdef readonly list _references
+ cdef grpc_channel_args _c_arguments
+
cdef grpc_channel_args *c_args(self) except *
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 9df308cdbcd..161b387df9c 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
@@ -1,20 +1,20 @@
-# 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.
+
+
cdef class _GrpcArgWrapper:
-
+
cdef grpc_arg arg
@@ -32,54 +32,54 @@ cdef grpc_arg _unwrap_grpc_arg(tuple wrapped_arg):
cdef class _ChannelArg:
cdef void c(self, argument, references) except *:
- key, value = argument
- cdef bytes encoded_key = _encode(key)
- if encoded_key is not key:
- references.append(encoded_key)
- self.c_argument.key = encoded_key
- if isinstance(value, int):
- self.c_argument.type = GRPC_ARG_INTEGER
- self.c_argument.value.integer = value
- elif isinstance(value, (bytes, str, unicode,)):
- self.c_argument.type = GRPC_ARG_STRING
- encoded_value = _encode(value)
- if encoded_value is not value:
- references.append(encoded_value)
- self.c_argument.value.string = encoded_value
+ key, value = argument
+ cdef bytes encoded_key = _encode(key)
+ if encoded_key is not key:
+ references.append(encoded_key)
+ self.c_argument.key = encoded_key
+ if isinstance(value, int):
+ self.c_argument.type = GRPC_ARG_INTEGER
+ self.c_argument.value.integer = value
+ elif isinstance(value, (bytes, str, unicode,)):
+ self.c_argument.type = GRPC_ARG_STRING
+ encoded_value = _encode(value)
+ if encoded_value is not value:
+ references.append(encoded_value)
+ self.c_argument.value.string = encoded_value
elif isinstance(value, _GrpcArgWrapper):
self.c_argument = (<_GrpcArgWrapper>value).arg
- elif hasattr(value, '__int__'):
- # Pointer objects must override __int__() to return
- # the underlying C address (Python ints are word size). The
- # lifecycle of the pointer is fixed to the lifecycle of the
- # python object wrapping it.
- self.c_argument.type = GRPC_ARG_POINTER
+ elif hasattr(value, '__int__'):
+ # Pointer objects must override __int__() to return
+ # the underlying C address (Python ints are word size). The
+ # 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.address = <void*>(<intptr_t>int(value))
- else:
- raise TypeError(
- 'Expected int, bytes, or behavior, got {}'.format(type(value)))
-
-
+ self.c_argument.value.pointer.address = <void*>(<intptr_t>int(value))
+ else:
+ raise TypeError(
+ 'Expected int, bytes, or behavior, got {}'.format(type(value)))
+
+
cdef class _ChannelArgs:
-
- def __cinit__(self, arguments):
- self._arguments = () if arguments is None else tuple(arguments)
+
+ def __cinit__(self, arguments):
+ self._arguments = () if arguments is None else tuple(arguments)
self._channel_args = []
- self._references = []
- self._c_arguments.arguments_length = len(self._arguments)
+ self._references = []
+ self._c_arguments.arguments_length = len(self._arguments)
if self._c_arguments.arguments_length != 0:
- self._c_arguments.arguments = <grpc_arg *>gpr_malloc(
- self._c_arguments.arguments_length * sizeof(grpc_arg))
- for index, argument in enumerate(self._arguments):
+ self._c_arguments.arguments = <grpc_arg *>gpr_malloc(
+ self._c_arguments.arguments_length * sizeof(grpc_arg))
+ for index, argument in enumerate(self._arguments):
channel_arg = _ChannelArg()
channel_arg.c(argument, self._references)
self._c_arguments.arguments[index] = channel_arg.c_argument
self._channel_args.append(channel_arg)
-
+
cdef grpc_channel_args *c_args(self) except *:
return &self._c_arguments
def __dealloc__(self):
if self._c_arguments.arguments != NULL:
- gpr_free(self._c_arguments.arguments)
+ gpr_free(self._c_arguments.arguments)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pxd.pxi
index 8babeb45361..54760788b0c 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pxd.pxi
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 Call:
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 bdd155bea94..6cebd1ac51f 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
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 Call:
@@ -24,16 +24,16 @@ cdef class Call:
def _start_batch(self, operations, tag, retain_self):
if not self.is_valid:
raise ValueError("invalid call object cannot be used from Python")
- cdef _BatchOperationTag batch_operation_tag = _BatchOperationTag(
- tag, operations, self if retain_self else None)
- batch_operation_tag.prepare()
- cpython.Py_INCREF(batch_operation_tag)
- cdef grpc_call_error error
+ cdef _BatchOperationTag batch_operation_tag = _BatchOperationTag(
+ tag, operations, self if retain_self else None)
+ batch_operation_tag.prepare()
+ cpython.Py_INCREF(batch_operation_tag)
+ cdef grpc_call_error error
with nogil:
- error = grpc_call_start_batch(
- self.c_call, batch_operation_tag.c_ops, batch_operation_tag.c_nops,
- <cpython.PyObject *>batch_operation_tag, NULL)
- return error
+ error = grpc_call_start_batch(
+ self.c_call, batch_operation_tag.c_ops, batch_operation_tag.c_nops,
+ <cpython.PyObject *>batch_operation_tag, NULL)
+ return error
def start_client_batch(self, operations, tag):
# We don't reference this call in the operations tag because
@@ -66,12 +66,12 @@ cdef class Call:
result = grpc_call_cancel(self.c_call, NULL)
return result
- def set_credentials(self, CallCredentials call_credentials not None):
- cdef grpc_call_credentials *c_call_credentials = call_credentials.c()
- cdef grpc_call_error call_error = grpc_call_set_credentials(
- self.c_call, c_call_credentials)
- grpc_call_credentials_release(c_call_credentials)
- return call_error
+ def set_credentials(self, CallCredentials call_credentials not None):
+ cdef grpc_call_credentials *c_call_credentials = call_credentials.c()
+ cdef grpc_call_error call_error = grpc_call_set_credentials(
+ self.c_call, c_call_credentials)
+ grpc_call_credentials_release(c_call_credentials)
+ return call_error
def peer(self):
cdef char *peer = NULL
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi
index eb27f2df7ad..16caaf51cbe 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi
@@ -1,74 +1,74 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT 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 _check_call_error_no_metadata(c_call_error)
-
-
-cdef _check_and_raise_call_error_no_metadata(c_call_error)
-
-
-cdef _check_call_error(c_call_error, metadata)
-
-
-cdef class _CallState:
-
- cdef grpc_call *c_call
- cdef set due
-
-
-cdef class _ChannelState:
-
- cdef object condition
- cdef grpc_channel *c_channel
- # A boolean field indicating that the channel is open (if True) or is being
- # closed (i.e. a call to close is currently executing) or is closed (if
- # False).
- # TODO(https://github.com/grpc/grpc/issues/3064): Eliminate "is being closed"
- # a state in which condition may be acquired by any thread, eliminate this
- # field and just use the NULLness of c_channel as an indication that the
- # channel is closed.
- cdef object open
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 _check_call_error_no_metadata(c_call_error)
+
+
+cdef _check_and_raise_call_error_no_metadata(c_call_error)
+
+
+cdef _check_call_error(c_call_error, metadata)
+
+
+cdef class _CallState:
+
+ cdef grpc_call *c_call
+ cdef set due
+
+
+cdef class _ChannelState:
+
+ cdef object condition
+ cdef grpc_channel *c_channel
+ # A boolean field indicating that the channel is open (if True) or is being
+ # closed (i.e. a call to close is currently executing) or is closed (if
+ # False).
+ # TODO(https://github.com/grpc/grpc/issues/3064): Eliminate "is being closed"
+ # a state in which condition may be acquired by any thread, eliminate this
+ # field and just use the NULLness of c_channel as an indication that the
+ # channel is closed.
+ cdef object open
cdef object closed_reason
-
- # A dict from _BatchOperationTag to _CallState
- cdef dict integrated_call_states
- cdef grpc_completion_queue *c_call_completion_queue
-
- # A set of _CallState
- cdef set segregated_call_states
-
- cdef set connectivity_due
- cdef grpc_completion_queue *c_connectivity_completion_queue
-
-
-cdef class IntegratedCall:
-
- cdef _ChannelState _channel_state
- cdef _CallState _call_state
-
-
-cdef class SegregatedCall:
-
- cdef _ChannelState _channel_state
- cdef _CallState _call_state
- cdef grpc_completion_queue *_c_completion_queue
-
-
+
+ # A dict from _BatchOperationTag to _CallState
+ cdef dict integrated_call_states
+ cdef grpc_completion_queue *c_call_completion_queue
+
+ # A set of _CallState
+ cdef set segregated_call_states
+
+ cdef set connectivity_due
+ cdef grpc_completion_queue *c_connectivity_completion_queue
+
+
+cdef class IntegratedCall:
+
+ cdef _ChannelState _channel_state
+ cdef _CallState _call_state
+
+
+cdef class SegregatedCall:
+
+ cdef _ChannelState _channel_state
+ cdef _CallState _call_state
+ cdef grpc_completion_queue *_c_completion_queue
+
+
cdef class Channel:
- cdef _ChannelState _state
+ cdef _ChannelState _state
# TODO(https://github.com/grpc/grpc/issues/15662): Eliminate this.
cdef tuple _arguments
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 74c7f6c1405..1f2983699c9 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
@@ -1,155 +1,155 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-_INTERNAL_CALL_ERROR_MESSAGE_FORMAT = (
- 'Internal gRPC call error %d. ' +
- 'Please report to https://github.com/grpc/grpc/issues')
-
-
-cdef str _call_error_metadata(metadata):
- return 'metadata was invalid: %s' % metadata
-
-
-cdef str _call_error_no_metadata(c_call_error):
- return _INTERNAL_CALL_ERROR_MESSAGE_FORMAT % c_call_error
-
-
-cdef str _call_error(c_call_error, metadata):
- if c_call_error == GRPC_CALL_ERROR_INVALID_METADATA:
- return _call_error_metadata(metadata)
- else:
- return _call_error_no_metadata(c_call_error)
-
-
-cdef _check_call_error_no_metadata(c_call_error):
- if c_call_error != GRPC_CALL_OK:
- return _INTERNAL_CALL_ERROR_MESSAGE_FORMAT % c_call_error
- else:
- return None
-
-
-cdef _check_and_raise_call_error_no_metadata(c_call_error):
- error = _check_call_error_no_metadata(c_call_error)
- if error is not None:
- raise ValueError(error)
-
-
-cdef _check_call_error(c_call_error, metadata):
- if c_call_error == GRPC_CALL_ERROR_INVALID_METADATA:
- return _call_error_metadata(metadata)
- else:
- return _check_call_error_no_metadata(c_call_error)
-
-
-cdef void _raise_call_error_no_metadata(c_call_error) except *:
- raise ValueError(_call_error_no_metadata(c_call_error))
-
-
-cdef void _raise_call_error(c_call_error, metadata) except *:
- raise ValueError(_call_error(c_call_error, metadata))
-
-
-cdef _destroy_c_completion_queue(grpc_completion_queue *c_completion_queue):
- grpc_completion_queue_shutdown(c_completion_queue)
- grpc_completion_queue_destroy(c_completion_queue)
-
-
-cdef class _CallState:
-
- def __cinit__(self):
- self.due = set()
-
-
-cdef class _ChannelState:
-
- def __cinit__(self):
- self.condition = threading.Condition()
- self.open = True
- self.integrated_call_states = {}
- self.segregated_call_states = set()
- self.connectivity_due = set()
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+_INTERNAL_CALL_ERROR_MESSAGE_FORMAT = (
+ 'Internal gRPC call error %d. ' +
+ 'Please report to https://github.com/grpc/grpc/issues')
+
+
+cdef str _call_error_metadata(metadata):
+ return 'metadata was invalid: %s' % metadata
+
+
+cdef str _call_error_no_metadata(c_call_error):
+ return _INTERNAL_CALL_ERROR_MESSAGE_FORMAT % c_call_error
+
+
+cdef str _call_error(c_call_error, metadata):
+ if c_call_error == GRPC_CALL_ERROR_INVALID_METADATA:
+ return _call_error_metadata(metadata)
+ else:
+ return _call_error_no_metadata(c_call_error)
+
+
+cdef _check_call_error_no_metadata(c_call_error):
+ if c_call_error != GRPC_CALL_OK:
+ return _INTERNAL_CALL_ERROR_MESSAGE_FORMAT % c_call_error
+ else:
+ return None
+
+
+cdef _check_and_raise_call_error_no_metadata(c_call_error):
+ error = _check_call_error_no_metadata(c_call_error)
+ if error is not None:
+ raise ValueError(error)
+
+
+cdef _check_call_error(c_call_error, metadata):
+ if c_call_error == GRPC_CALL_ERROR_INVALID_METADATA:
+ return _call_error_metadata(metadata)
+ else:
+ return _check_call_error_no_metadata(c_call_error)
+
+
+cdef void _raise_call_error_no_metadata(c_call_error) except *:
+ raise ValueError(_call_error_no_metadata(c_call_error))
+
+
+cdef void _raise_call_error(c_call_error, metadata) except *:
+ raise ValueError(_call_error(c_call_error, metadata))
+
+
+cdef _destroy_c_completion_queue(grpc_completion_queue *c_completion_queue):
+ grpc_completion_queue_shutdown(c_completion_queue)
+ grpc_completion_queue_destroy(c_completion_queue)
+
+
+cdef class _CallState:
+
+ def __cinit__(self):
+ self.due = set()
+
+
+cdef class _ChannelState:
+
+ def __cinit__(self):
+ self.condition = threading.Condition()
+ self.open = True
+ self.integrated_call_states = {}
+ self.segregated_call_states = set()
+ self.connectivity_due = set()
self.closed_reason = None
-
-
-cdef tuple _operate(grpc_call *c_call, object operations, object user_tag):
- cdef grpc_call_error c_call_error
- cdef _BatchOperationTag tag = _BatchOperationTag(user_tag, operations, None)
- tag.prepare()
- cpython.Py_INCREF(tag)
- with nogil:
- c_call_error = grpc_call_start_batch(
- c_call, tag.c_ops, tag.c_nops, <cpython.PyObject *>tag, NULL)
- return c_call_error, tag
-
-
-cdef object _operate_from_integrated_call(
- _ChannelState channel_state, _CallState call_state, object operations,
- object user_tag):
- cdef grpc_call_error c_call_error
- cdef _BatchOperationTag tag
- with channel_state.condition:
- if call_state.due:
- c_call_error, tag = _operate(call_state.c_call, operations, user_tag)
- if c_call_error == GRPC_CALL_OK:
- call_state.due.add(tag)
- channel_state.integrated_call_states[tag] = call_state
- return True
- else:
- _raise_call_error_no_metadata(c_call_error)
- else:
- return False
-
-
-cdef object _operate_from_segregated_call(
- _ChannelState channel_state, _CallState call_state, object operations,
- object user_tag):
- cdef grpc_call_error c_call_error
- cdef _BatchOperationTag tag
- with channel_state.condition:
- if call_state.due:
- c_call_error, tag = _operate(call_state.c_call, operations, user_tag)
- if c_call_error == GRPC_CALL_OK:
- call_state.due.add(tag)
- return True
- else:
- _raise_call_error_no_metadata(c_call_error)
- else:
- return False
-
-
-cdef _cancel(
- _ChannelState channel_state, _CallState call_state, grpc_status_code code,
- str details):
- cdef grpc_call_error c_call_error
- with channel_state.condition:
- if call_state.due:
- c_call_error = grpc_call_cancel_with_status(
- call_state.c_call, code, _encode(details), NULL)
- _check_and_raise_call_error_no_metadata(c_call_error)
-
-
+
+
+cdef tuple _operate(grpc_call *c_call, object operations, object user_tag):
+ cdef grpc_call_error c_call_error
+ cdef _BatchOperationTag tag = _BatchOperationTag(user_tag, operations, None)
+ tag.prepare()
+ cpython.Py_INCREF(tag)
+ with nogil:
+ c_call_error = grpc_call_start_batch(
+ c_call, tag.c_ops, tag.c_nops, <cpython.PyObject *>tag, NULL)
+ return c_call_error, tag
+
+
+cdef object _operate_from_integrated_call(
+ _ChannelState channel_state, _CallState call_state, object operations,
+ object user_tag):
+ cdef grpc_call_error c_call_error
+ cdef _BatchOperationTag tag
+ with channel_state.condition:
+ if call_state.due:
+ c_call_error, tag = _operate(call_state.c_call, operations, user_tag)
+ if c_call_error == GRPC_CALL_OK:
+ call_state.due.add(tag)
+ channel_state.integrated_call_states[tag] = call_state
+ return True
+ else:
+ _raise_call_error_no_metadata(c_call_error)
+ else:
+ return False
+
+
+cdef object _operate_from_segregated_call(
+ _ChannelState channel_state, _CallState call_state, object operations,
+ object user_tag):
+ cdef grpc_call_error c_call_error
+ cdef _BatchOperationTag tag
+ with channel_state.condition:
+ if call_state.due:
+ c_call_error, tag = _operate(call_state.c_call, operations, user_tag)
+ if c_call_error == GRPC_CALL_OK:
+ call_state.due.add(tag)
+ return True
+ else:
+ _raise_call_error_no_metadata(c_call_error)
+ else:
+ return False
+
+
+cdef _cancel(
+ _ChannelState channel_state, _CallState call_state, grpc_status_code code,
+ str details):
+ cdef grpc_call_error c_call_error
+ with channel_state.condition:
+ if call_state.due:
+ c_call_error = grpc_call_cancel_with_status(
+ call_state.c_call, code, _encode(details), NULL)
+ _check_and_raise_call_error_no_metadata(c_call_error)
+
+
cdef _next_call_event(
- _ChannelState channel_state, grpc_completion_queue *c_completion_queue,
+ _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.
@@ -174,160 +174,160 @@ cdef _next_call_event(
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,
- grpc_completion_queue *c_completion_queue, on_success, int flags, method,
- host, object deadline, CallCredentials credentials,
+# TODO(https://github.com/grpc/grpc/issues/14569): This could be a lot simpler.
+cdef void _call(
+ _ChannelState channel_state, _CallState call_state,
+ grpc_completion_queue *c_completion_queue, on_success, int flags, method,
+ host, object deadline, CallCredentials credentials,
object operationses_and_user_tags, object metadata,
object context) except *:
- """Invokes an RPC.
-
- Args:
- channel_state: A _ChannelState with its "open" attribute set to True. RPCs
- may not be invoked on a closed channel.
- call_state: An empty _CallState to be altered (specifically assigned a
- c_call and having its due set populated) if the RPC invocation is
- successful.
- c_completion_queue: A grpc_completion_queue to be used for the call's
- operations.
- on_success: A behavior to be called if attempting to start operations for
- the call succeeds. If called the behavior will be called while holding the
- channel_state condition and passed the tags associated with operations
- that were successfully started for the call.
- flags: Flags to be passed to gRPC Core as part of call creation.
- method: The fully-qualified name of the RPC method being invoked.
- host: A "host" string to be passed to gRPC Core as part of call creation.
- deadline: A float for the deadline of the RPC, or None if the RPC is to have
- no deadline.
- credentials: A _CallCredentials for the RPC or None.
- operationses_and_user_tags: A sequence of length-two sequences the first
- element of which is a sequence of Operations and the second element of
- which is an object to be used as a tag. A SendInitialMetadataOperation
- must be present in the first element of this value.
- metadata: The metadata for this call.
+ """Invokes an RPC.
+
+ Args:
+ channel_state: A _ChannelState with its "open" attribute set to True. RPCs
+ may not be invoked on a closed channel.
+ call_state: An empty _CallState to be altered (specifically assigned a
+ c_call and having its due set populated) if the RPC invocation is
+ successful.
+ c_completion_queue: A grpc_completion_queue to be used for the call's
+ operations.
+ on_success: A behavior to be called if attempting to start operations for
+ the call succeeds. If called the behavior will be called while holding the
+ channel_state condition and passed the tags associated with operations
+ that were successfully started for the call.
+ flags: Flags to be passed to gRPC Core as part of call creation.
+ method: The fully-qualified name of the RPC method being invoked.
+ host: A "host" string to be passed to gRPC Core as part of call creation.
+ deadline: A float for the deadline of the RPC, or None if the RPC is to have
+ no deadline.
+ credentials: A _CallCredentials for the RPC or None.
+ operationses_and_user_tags: A sequence of length-two sequences the first
+ element of which is a sequence of Operations and the second element of
+ which is an object to be used as a tag. A SendInitialMetadataOperation
+ must be present in the first element of this value.
+ metadata: The metadata for this call.
context: Context object for distributed tracing.
- """
- cdef grpc_slice method_slice
- cdef grpc_slice host_slice
- cdef grpc_slice *host_slice_ptr
- cdef grpc_call_credentials *c_call_credentials
- cdef grpc_call_error c_call_error
- cdef tuple error_and_wrapper_tag
- cdef _BatchOperationTag wrapper_tag
- with channel_state.condition:
- if channel_state.open:
- method_slice = _slice_from_bytes(method)
- if host is None:
- host_slice_ptr = NULL
- else:
- host_slice = _slice_from_bytes(host)
- host_slice_ptr = &host_slice
- call_state.c_call = grpc_channel_create_call(
- channel_state.c_channel, NULL, flags,
- c_completion_queue, method_slice, host_slice_ptr,
- _timespec_from_time(deadline), NULL)
- grpc_slice_unref(method_slice)
- if host_slice_ptr:
- grpc_slice_unref(host_slice)
+ """
+ cdef grpc_slice method_slice
+ cdef grpc_slice host_slice
+ cdef grpc_slice *host_slice_ptr
+ cdef grpc_call_credentials *c_call_credentials
+ cdef grpc_call_error c_call_error
+ cdef tuple error_and_wrapper_tag
+ cdef _BatchOperationTag wrapper_tag
+ with channel_state.condition:
+ if channel_state.open:
+ method_slice = _slice_from_bytes(method)
+ if host is None:
+ host_slice_ptr = NULL
+ else:
+ host_slice = _slice_from_bytes(host)
+ host_slice_ptr = &host_slice
+ call_state.c_call = grpc_channel_create_call(
+ channel_state.c_channel, NULL, flags,
+ c_completion_queue, method_slice, host_slice_ptr,
+ _timespec_from_time(deadline), NULL)
+ grpc_slice_unref(method_slice)
+ if host_slice_ptr:
+ grpc_slice_unref(host_slice)
if context is not None:
set_census_context_on_call(call_state, context)
- if credentials is not None:
- c_call_credentials = credentials.c()
- c_call_error = grpc_call_set_credentials(
- call_state.c_call, c_call_credentials)
- grpc_call_credentials_release(c_call_credentials)
- if c_call_error != GRPC_CALL_OK:
- grpc_call_unref(call_state.c_call)
- call_state.c_call = NULL
- _raise_call_error_no_metadata(c_call_error)
- started_tags = set()
- for operations, user_tag in operationses_and_user_tags:
- c_call_error, tag = _operate(call_state.c_call, operations, user_tag)
- if c_call_error == GRPC_CALL_OK:
- started_tags.add(tag)
- else:
- grpc_call_cancel(call_state.c_call, NULL)
- grpc_call_unref(call_state.c_call)
- call_state.c_call = NULL
- _raise_call_error(c_call_error, metadata)
- else:
- call_state.due.update(started_tags)
- on_success(started_tags)
- else:
+ if credentials is not None:
+ c_call_credentials = credentials.c()
+ c_call_error = grpc_call_set_credentials(
+ call_state.c_call, c_call_credentials)
+ grpc_call_credentials_release(c_call_credentials)
+ if c_call_error != GRPC_CALL_OK:
+ grpc_call_unref(call_state.c_call)
+ call_state.c_call = NULL
+ _raise_call_error_no_metadata(c_call_error)
+ started_tags = set()
+ for operations, user_tag in operationses_and_user_tags:
+ c_call_error, tag = _operate(call_state.c_call, operations, user_tag)
+ if c_call_error == GRPC_CALL_OK:
+ started_tags.add(tag)
+ else:
+ grpc_call_cancel(call_state.c_call, NULL)
+ grpc_call_unref(call_state.c_call)
+ call_state.c_call = NULL
+ _raise_call_error(c_call_error, metadata)
+ else:
+ call_state.due.update(started_tags)
+ on_success(started_tags)
+ else:
raise ValueError('Cannot invoke RPC: %s' % channel_state.closed_reason)
-cdef void _process_integrated_call_tag(
- _ChannelState state, _BatchOperationTag tag) except *:
- cdef _CallState call_state = state.integrated_call_states.pop(tag)
- call_state.due.remove(tag)
- if not call_state.due:
- grpc_call_unref(call_state.c_call)
- call_state.c_call = NULL
-
-
-cdef class IntegratedCall:
-
- def __cinit__(self, _ChannelState channel_state, _CallState call_state):
- self._channel_state = channel_state
- self._call_state = call_state
-
- def operate(self, operations, tag):
- return _operate_from_integrated_call(
- self._channel_state, self._call_state, operations, tag)
-
- def cancel(self, code, details):
- _cancel(self._channel_state, self._call_state, code, details)
-
-
-cdef IntegratedCall _integrated_call(
- _ChannelState state, int flags, method, host, object deadline,
+cdef void _process_integrated_call_tag(
+ _ChannelState state, _BatchOperationTag tag) except *:
+ cdef _CallState call_state = state.integrated_call_states.pop(tag)
+ call_state.due.remove(tag)
+ if not call_state.due:
+ grpc_call_unref(call_state.c_call)
+ call_state.c_call = NULL
+
+
+cdef class IntegratedCall:
+
+ def __cinit__(self, _ChannelState channel_state, _CallState call_state):
+ self._channel_state = channel_state
+ self._call_state = call_state
+
+ def operate(self, operations, tag):
+ return _operate_from_integrated_call(
+ self._channel_state, self._call_state, operations, tag)
+
+ def cancel(self, code, details):
+ _cancel(self._channel_state, self._call_state, code, details)
+
+
+cdef IntegratedCall _integrated_call(
+ _ChannelState state, int flags, method, host, object deadline,
object metadata, CallCredentials credentials, operationses_and_user_tags,
object context):
- call_state = _CallState()
-
- def on_success(started_tags):
- for started_tag in started_tags:
- state.integrated_call_states[started_tag] = call_state
-
- _call(
- state, call_state, state.c_call_completion_queue, on_success, flags,
+ call_state = _CallState()
+
+ def on_success(started_tags):
+ for started_tag in started_tags:
+ state.integrated_call_states[started_tag] = call_state
+
+ _call(
+ state, call_state, state.c_call_completion_queue, on_success, flags,
method, host, deadline, credentials, operationses_and_user_tags, metadata, context)
-
- return IntegratedCall(state, call_state)
-
-
-cdef object _process_segregated_call_tag(
- _ChannelState state, _CallState call_state,
- grpc_completion_queue *c_completion_queue, _BatchOperationTag tag):
- call_state.due.remove(tag)
- if not call_state.due:
- grpc_call_unref(call_state.c_call)
- call_state.c_call = NULL
- state.segregated_call_states.remove(call_state)
- _destroy_c_completion_queue(c_completion_queue)
- return True
- else:
- return False
-
-
-cdef class SegregatedCall:
-
- def __cinit__(self, _ChannelState channel_state, _CallState call_state):
- self._channel_state = channel_state
- self._call_state = call_state
-
- def operate(self, operations, tag):
- return _operate_from_segregated_call(
- self._channel_state, self._call_state, operations, tag)
-
- def cancel(self, code, details):
- _cancel(self._channel_state, self._call_state, code, details)
-
- def next_event(self):
- def on_success(tag):
- _process_segregated_call_tag(
+
+ return IntegratedCall(state, call_state)
+
+
+cdef object _process_segregated_call_tag(
+ _ChannelState state, _CallState call_state,
+ grpc_completion_queue *c_completion_queue, _BatchOperationTag tag):
+ call_state.due.remove(tag)
+ if not call_state.due:
+ grpc_call_unref(call_state.c_call)
+ call_state.c_call = NULL
+ state.segregated_call_states.remove(call_state)
+ _destroy_c_completion_queue(c_completion_queue)
+ return True
+ else:
+ return False
+
+
+cdef class SegregatedCall:
+
+ def __cinit__(self, _ChannelState channel_state, _CallState call_state):
+ self._channel_state = channel_state
+ self._call_state = call_state
+
+ def operate(self, operations, tag):
+ return _operate_from_segregated_call(
+ self._channel_state, self._call_state, operations, tag)
+
+ def cancel(self, code, details):
+ _cancel(self._channel_state, self._call_state, code, details)
+
+ def next_event(self):
+ 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()
@@ -335,80 +335,80 @@ cdef class SegregatedCall:
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(
+ return _next_call_event(
self._channel_state, self._c_completion_queue, on_success, on_failure, None)
-
-
-cdef SegregatedCall _segregated_call(
- _ChannelState state, int flags, method, host, object deadline,
+
+
+cdef SegregatedCall _segregated_call(
+ _ChannelState state, int flags, method, host, object deadline,
object metadata, CallCredentials credentials, operationses_and_user_tags,
object context):
- cdef _CallState call_state = _CallState()
- cdef SegregatedCall segregated_call
+ cdef _CallState call_state = _CallState()
+ cdef SegregatedCall segregated_call
cdef grpc_completion_queue *c_completion_queue
-
- def on_success(started_tags):
- state.segregated_call_states.add(call_state)
-
+
+ def on_success(started_tags):
+ state.segregated_call_states.add(call_state)
+
with state.condition:
if state.open:
c_completion_queue = (grpc_completion_queue_create_for_next(NULL))
else:
raise ValueError('Cannot invoke RPC on closed channel!')
- try:
- _call(
- state, call_state, c_completion_queue, on_success, flags, method, host,
+ try:
+ _call(
+ state, call_state, c_completion_queue, on_success, flags, method, host,
deadline, credentials, operationses_and_user_tags, metadata,
context)
- except:
- _destroy_c_completion_queue(c_completion_queue)
- raise
-
- segregated_call = SegregatedCall(state, call_state)
- segregated_call._c_completion_queue = c_completion_queue
- return segregated_call
-
-
-cdef object _watch_connectivity_state(
- _ChannelState state, grpc_connectivity_state last_observed_state,
- object deadline):
- cdef _ConnectivityTag tag = _ConnectivityTag(object())
- with state.condition:
- if state.open:
- cpython.Py_INCREF(tag)
- grpc_channel_watch_connectivity_state(
- state.c_channel, last_observed_state, _timespec_from_time(deadline),
- state.c_connectivity_completion_queue, <cpython.PyObject *>tag)
- state.connectivity_due.add(tag)
- else:
+ except:
+ _destroy_c_completion_queue(c_completion_queue)
+ raise
+
+ segregated_call = SegregatedCall(state, call_state)
+ segregated_call._c_completion_queue = c_completion_queue
+ return segregated_call
+
+
+cdef object _watch_connectivity_state(
+ _ChannelState state, grpc_connectivity_state last_observed_state,
+ object deadline):
+ cdef _ConnectivityTag tag = _ConnectivityTag(object())
+ with state.condition:
+ if state.open:
+ cpython.Py_INCREF(tag)
+ grpc_channel_watch_connectivity_state(
+ state.c_channel, last_observed_state, _timespec_from_time(deadline),
+ state.c_connectivity_completion_queue, <cpython.PyObject *>tag)
+ state.connectivity_due.add(tag)
+ else:
raise ValueError('Cannot invoke RPC: %s' % state.closed_reason)
- completed_tag, event = _latent_event(
- state.c_connectivity_completion_queue, None)
- with state.condition:
- state.connectivity_due.remove(completed_tag)
- state.condition.notify_all()
- return event
-
-
+ completed_tag, event = _latent_event(
+ state.c_connectivity_completion_queue, None)
+ with state.condition:
+ state.connectivity_due.remove(completed_tag)
+ state.condition.notify_all()
+ return event
+
+
cdef _close(Channel channel, grpc_status_code code, object details,
drain_calls):
cdef _ChannelState state = channel._state
- cdef _CallState call_state
- encoded_details = _encode(details)
- with state.condition:
- if state.open:
- state.open = False
+ cdef _CallState call_state
+ encoded_details = _encode(details)
+ with state.condition:
+ if state.open:
+ state.open = False
state.closed_reason = details
- for call_state in set(state.integrated_call_states.values()):
- grpc_call_cancel_with_status(
- call_state.c_call, code, encoded_details, NULL)
- for call_state in state.segregated_call_states:
- grpc_call_cancel_with_status(
- call_state.c_call, code, encoded_details, NULL)
- # TODO(https://github.com/grpc/grpc/issues/3064): Cancel connectivity
- # watching.
-
+ for call_state in set(state.integrated_call_states.values()):
+ grpc_call_cancel_with_status(
+ call_state.c_call, code, encoded_details, NULL)
+ for call_state in state.segregated_call_states:
+ grpc_call_cancel_with_status(
+ call_state.c_call, code, encoded_details, NULL)
+ # TODO(https://github.com/grpc/grpc/issues/3064): Cancel connectivity
+ # watching.
+
if drain_calls:
while not _calls_drained(state):
event = channel.next_call_event()
@@ -420,32 +420,32 @@ cdef _close(Channel channel, grpc_status_code code, object details,
state.condition.wait()
while state.connectivity_due:
state.condition.wait()
-
- _destroy_c_completion_queue(state.c_call_completion_queue)
- _destroy_c_completion_queue(state.c_connectivity_completion_queue)
- grpc_channel_destroy(state.c_channel)
- state.c_channel = NULL
+
+ _destroy_c_completion_queue(state.c_call_completion_queue)
+ _destroy_c_completion_queue(state.c_connectivity_completion_queue)
+ grpc_channel_destroy(state.c_channel)
+ state.c_channel = NULL
grpc_shutdown_blocking()
- state.condition.notify_all()
- else:
- # Another call to close already completed in the past or is currently
- # being executed in another thread.
- while state.c_channel != NULL:
- state.condition.wait()
-
-
+ state.condition.notify_all()
+ else:
+ # Another call to close already completed in the past or is currently
+ # being executed in another thread.
+ while state.c_channel != NULL:
+ state.condition.wait()
+
+
cdef _calls_drained(_ChannelState state):
return not (state.integrated_call_states or state.segregated_call_states or
state.connectivity_due)
cdef class Channel:
- def __cinit__(
- self, bytes target, object arguments,
- ChannelCredentials channel_credentials):
+ def __cinit__(
+ self, bytes target, object arguments,
+ ChannelCredentials channel_credentials):
arguments = () if arguments is None else tuple(arguments)
fork_handlers_and_grpc_init()
- self._state = _ChannelState()
+ self._state = _ChannelState()
self._state.c_call_completion_queue = (
grpc_completion_queue_create_for_next(NULL))
self._state.c_connectivity_completion_queue = (
@@ -453,32 +453,32 @@ cdef class Channel:
self._arguments = arguments
cdef _ChannelArgs channel_args = _ChannelArgs(arguments)
if channel_credentials is None:
- self._state.c_channel = grpc_insecure_channel_create(
+ self._state.c_channel = grpc_insecure_channel_create(
<char *>target, channel_args.c_args(), NULL)
else:
- c_channel_credentials = channel_credentials.c()
- self._state.c_channel = grpc_secure_channel_create(
+ c_channel_credentials = channel_credentials.c()
+ self._state.c_channel = grpc_secure_channel_create(
c_channel_credentials, <char *>target, channel_args.c_args(), NULL)
- grpc_channel_credentials_release(c_channel_credentials)
-
- def target(self):
- cdef char *c_target
- with self._state.condition:
- c_target = grpc_channel_get_target(self._state.c_channel)
- target = <bytes>c_target
- gpr_free(c_target)
- return target
-
- def integrated_call(
- self, int flags, method, host, object deadline, object metadata,
+ grpc_channel_credentials_release(c_channel_credentials)
+
+ def target(self):
+ cdef char *c_target
+ with self._state.condition:
+ c_target = grpc_channel_get_target(self._state.c_channel)
+ target = <bytes>c_target
+ gpr_free(c_target)
+ return target
+
+ def integrated_call(
+ self, int flags, method, host, object deadline, object metadata,
CallCredentials credentials, operationses_and_tags,
object context = None):
- return _integrated_call(
- self._state, flags, method, host, deadline, metadata, credentials,
+ return _integrated_call(
+ self._state, flags, method, host, deadline, metadata, credentials,
operationses_and_tags, context)
-
- def next_call_event(self):
- def on_success(tag):
+
+ def next_call_event(self):
+ def on_success(tag):
if tag is not None:
_process_integrated_call_tag(self._state, tag)
if is_fork_support_enabled():
@@ -490,17 +490,17 @@ cdef class Channel:
# 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)
-
- def segregated_call(
- self, int flags, method, host, object deadline, object metadata,
+
+ def segregated_call(
+ self, int flags, method, host, object deadline, object metadata,
CallCredentials credentials, operationses_and_tags,
object context = None):
- return _segregated_call(
- self._state, flags, method, host, deadline, metadata, credentials,
+ return _segregated_call(
+ self._state, flags, method, host, deadline, metadata, credentials,
operationses_and_tags, context)
-
+
def check_connectivity_state(self, bint try_to_connect):
- with self._state.condition:
+ with self._state.condition:
if self._state.open:
return grpc_channel_check_connectivity_state(
self._state.c_channel, try_to_connect)
@@ -508,10 +508,10 @@ cdef class Channel:
raise ValueError('Cannot invoke RPC: %s' % self._state.closed_reason)
def watch_connectivity_state(
- self, grpc_connectivity_state last_observed_state, object deadline):
- return _watch_connectivity_state(self._state, last_observed_state, deadline)
+ self, grpc_connectivity_state last_observed_state, object deadline):
+ return _watch_connectivity_state(self._state, last_observed_state, deadline)
- def close(self, code, details):
+ def close(self, code, details):
_close(self, code, details, False)
def close_on_fork(self, code, details):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pxd.pxi
index 0307f74cbef..258b84363b0 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pxd.pxi
@@ -1,28 +1,28 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 grpc_event _next(grpc_completion_queue *c_completion_queue, deadline) except *
-
-
-cdef _interpret_event(grpc_event c_event)
-
-
+
+
+cdef _interpret_event(grpc_event c_event)
+
+
cdef class CompletionQueue:
cdef grpc_completion_queue *c_completion_queue
cdef bint is_shutting_down
cdef bint is_shutdown
- cdef _interpret_event(self, grpc_event c_event)
+ cdef _interpret_event(self, grpc_event c_event)
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 a47403ac51c..7b7e6f5c0aa 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
@@ -1,95 +1,95 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 int _INTERRUPT_CHECK_PERIOD_MS = 200
cdef grpc_event _next(grpc_completion_queue *c_completion_queue, deadline) except *:
- cdef gpr_timespec c_increment
- cdef gpr_timespec c_timeout
- cdef gpr_timespec c_deadline
- c_increment = gpr_time_from_millis(_INTERRUPT_CHECK_PERIOD_MS, GPR_TIMESPAN)
- if deadline is None:
- c_deadline = gpr_inf_future(GPR_CLOCK_REALTIME)
- else:
- c_deadline = _timespec_from_time(deadline)
-
+ cdef gpr_timespec c_increment
+ cdef gpr_timespec c_timeout
+ cdef gpr_timespec c_deadline
+ c_increment = gpr_time_from_millis(_INTERRUPT_CHECK_PERIOD_MS, GPR_TIMESPAN)
+ if deadline is None:
+ c_deadline = gpr_inf_future(GPR_CLOCK_REALTIME)
+ else:
+ c_deadline = _timespec_from_time(deadline)
+
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_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)
+ 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
-
+ if (c_event.type != GRPC_QUEUE_TIMEOUT or
+ gpr_time_cmp(c_timeout, c_deadline) == 0):
+ break
+
# Handle any signals
cpython.PyErr_CheckSignals()
- return c_event
-
-
-cdef _interpret_event(grpc_event c_event):
- cdef _Tag tag
- if c_event.type == GRPC_QUEUE_TIMEOUT:
+ return c_event
+
+
+cdef _interpret_event(grpc_event c_event):
+ cdef _Tag tag
+ if c_event.type == GRPC_QUEUE_TIMEOUT:
# TODO(ericgribkoff) Do not coopt ConnectivityEvent here.
- return None, ConnectivityEvent(GRPC_QUEUE_TIMEOUT, False, None)
- elif c_event.type == GRPC_QUEUE_SHUTDOWN:
- # NOTE(nathaniel): For now we coopt ConnectivityEvent here.
- return None, ConnectivityEvent(GRPC_QUEUE_SHUTDOWN, False, None)
- else:
- tag = <_Tag>c_event.tag
- # We receive event tags only after they've been inc-ref'd elsewhere in
- # the code.
- cpython.Py_DECREF(tag)
- return tag, tag.event(c_event)
-
-
-cdef _latent_event(grpc_completion_queue *c_completion_queue, object deadline):
- cdef grpc_event c_event = _next(c_completion_queue, deadline)
- return _interpret_event(c_event)
-
-
+ return None, ConnectivityEvent(GRPC_QUEUE_TIMEOUT, False, None)
+ elif c_event.type == GRPC_QUEUE_SHUTDOWN:
+ # NOTE(nathaniel): For now we coopt ConnectivityEvent here.
+ return None, ConnectivityEvent(GRPC_QUEUE_SHUTDOWN, False, None)
+ else:
+ tag = <_Tag>c_event.tag
+ # We receive event tags only after they've been inc-ref'd elsewhere in
+ # the code.
+ cpython.Py_DECREF(tag)
+ return tag, tag.event(c_event)
+
+
+cdef _latent_event(grpc_completion_queue *c_completion_queue, object deadline):
+ cdef grpc_event c_event = _next(c_completion_queue, deadline)
+ return _interpret_event(c_event)
+
+
cdef class CompletionQueue:
- def __cinit__(self, shutdown_cq=False):
- cdef grpc_completion_queue_attributes c_attrs
+ def __cinit__(self, shutdown_cq=False):
+ cdef grpc_completion_queue_attributes c_attrs
fork_handlers_and_grpc_init()
- if shutdown_cq:
- c_attrs.version = 1
- c_attrs.cq_completion_type = GRPC_CQ_NEXT
- c_attrs.cq_polling_type = GRPC_CQ_NON_LISTENING
- self.c_completion_queue = grpc_completion_queue_create(
- grpc_completion_queue_factory_lookup(&c_attrs), &c_attrs, NULL);
- else:
- self.c_completion_queue = grpc_completion_queue_create_for_next(NULL)
+ if shutdown_cq:
+ c_attrs.version = 1
+ c_attrs.cq_completion_type = GRPC_CQ_NEXT
+ c_attrs.cq_polling_type = GRPC_CQ_NON_LISTENING
+ self.c_completion_queue = grpc_completion_queue_create(
+ grpc_completion_queue_factory_lookup(&c_attrs), &c_attrs, NULL);
+ else:
+ self.c_completion_queue = grpc_completion_queue_create_for_next(NULL)
self.is_shutting_down = False
self.is_shutdown = False
- cdef _interpret_event(self, grpc_event c_event):
- unused_tag, event = _interpret_event(c_event)
- if event.completion_type == GRPC_QUEUE_SHUTDOWN:
+ cdef _interpret_event(self, grpc_event c_event):
+ unused_tag, event = _interpret_event(c_event)
+ if event.completion_type == GRPC_QUEUE_SHUTDOWN:
self.is_shutdown = True
- return event
+ return event
- # We name this 'poll' to avoid problems with CPython's expectations for
- # 'special' methods (like next and __next__).
- def poll(self, deadline=None):
- return self._interpret_event(_next(self.c_completion_queue, deadline))
+ # We name this 'poll' to avoid problems with CPython's expectations for
+ # 'special' methods (like next and __next__).
+ def poll(self, deadline=None):
+ return self._interpret_event(_next(self.c_completion_queue, deadline))
def shutdown(self):
with nogil:
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 ddaedb30bd4..cbb55c6cf8a 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
@@ -1,102 +1,102 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 CallCredentials:
+cdef class CallCredentials:
cdef grpc_call_credentials *c(self) except *
-
- # TODO(https://github.com/grpc/grpc/issues/12531): remove.
- cdef grpc_call_credentials *c_credentials
-
-
-cdef int _get_metadata(
- void *state, grpc_auth_metadata_context context,
- grpc_credentials_plugin_metadata_cb cb, void *user_data,
- grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
- size_t *num_creds_md, grpc_status_code *status,
+
+ # TODO(https://github.com/grpc/grpc/issues/12531): remove.
+ cdef grpc_call_credentials *c_credentials
+
+
+cdef int _get_metadata(
+ void *state, grpc_auth_metadata_context context,
+ grpc_credentials_plugin_metadata_cb cb, void *user_data,
+ grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
+ size_t *num_creds_md, grpc_status_code *status,
const char **error_details) except * with gil
-
+
cdef void _destroy(void *state) except * with gil
-
-
-cdef class MetadataPluginCallCredentials(CallCredentials):
-
- cdef readonly object _metadata_plugin
- cdef readonly bytes _name
-
+
+
+cdef class MetadataPluginCallCredentials(CallCredentials):
+
+ cdef readonly object _metadata_plugin
+ cdef readonly bytes _name
+
cdef grpc_call_credentials *c(self) except *
-
-
-cdef grpc_call_credentials *_composition(call_credentialses)
-
-
-cdef class CompositeCallCredentials(CallCredentials):
-
- cdef readonly tuple _call_credentialses
-
+
+
+cdef grpc_call_credentials *_composition(call_credentialses)
+
+
+cdef class CompositeCallCredentials(CallCredentials):
+
+ cdef readonly tuple _call_credentialses
+
cdef grpc_call_credentials *c(self) except *
-
-
+
+
cdef class ChannelCredentials:
cdef grpc_channel_credentials *c(self) except *
-
+
cdef class SSLSessionCacheLRU:
cdef grpc_ssl_session_cache *_cache
-cdef class SSLChannelCredentials(ChannelCredentials):
+cdef class SSLChannelCredentials(ChannelCredentials):
- cdef readonly object _pem_root_certificates
- cdef readonly object _private_key
- cdef readonly object _certificate_chain
+ cdef readonly object _pem_root_certificates
+ cdef readonly object _private_key
+ cdef readonly object _certificate_chain
cdef grpc_channel_credentials *c(self) except *
-cdef class CompositeChannelCredentials(ChannelCredentials):
+cdef class CompositeChannelCredentials(ChannelCredentials):
- cdef readonly tuple _call_credentialses
- cdef readonly ChannelCredentials _channel_credentials
+ cdef readonly tuple _call_credentialses
+ cdef readonly ChannelCredentials _channel_credentials
cdef grpc_channel_credentials *c(self) except *
-cdef class ServerCertificateConfig:
+cdef class ServerCertificateConfig:
- cdef grpc_ssl_server_certificate_config *c_cert_config
- cdef const char *c_pem_root_certs
- cdef grpc_ssl_pem_key_cert_pair *c_ssl_pem_key_cert_pairs
- cdef size_t c_ssl_pem_key_cert_pairs_count
- cdef list references
+ cdef grpc_ssl_server_certificate_config *c_cert_config
+ cdef const char *c_pem_root_certs
+ cdef grpc_ssl_pem_key_cert_pair *c_ssl_pem_key_cert_pairs
+ cdef size_t c_ssl_pem_key_cert_pairs_count
+ cdef list references
-cdef class ServerCredentials:
+cdef class ServerCredentials:
- cdef grpc_server_credentials *c_credentials
- cdef grpc_ssl_pem_key_cert_pair *c_ssl_pem_key_cert_pairs
- cdef size_t c_ssl_pem_key_cert_pairs_count
- cdef list references
- # the cert config related state is used only if this credentials is
- # created with cert config/fetcher
- cdef object initial_cert_config
- cdef object cert_config_fetcher
- # whether C-core has asked for the initial_cert_config
- cdef bint initial_cert_config_fetched
+ cdef grpc_server_credentials *c_credentials
+ cdef grpc_ssl_pem_key_cert_pair *c_ssl_pem_key_cert_pairs
+ cdef size_t c_ssl_pem_key_cert_pairs_count
+ cdef list references
+ # the cert config related state is used only if this credentials is
+ # created with cert config/fetcher
+ cdef object initial_cert_config
+ 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):
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 c75579cc04f..11c00bcf43f 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
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
def _spawn_callback_in_thread(cb_func, args):
@@ -28,10 +28,10 @@ def _spawn_callback_async(callback, args):
async_callback_func(callback, args)
-cdef class CallCredentials:
+cdef class CallCredentials:
cdef grpc_call_credentials *c(self) except *:
- raise NotImplementedError()
+ raise NotImplementedError()
cdef int _get_metadata(void *state,
@@ -42,74 +42,74 @@ cdef int _get_metadata(void *state,
size_t *num_creds_md,
grpc_status_code *status,
const char **error_details) except * with gil:
- cdef size_t metadata_count
- cdef grpc_metadata *c_metadata
- def callback(metadata, grpc_status_code status, bytes error_details):
+ cdef size_t metadata_count
+ cdef grpc_metadata *c_metadata
+ def callback(metadata, grpc_status_code status, bytes error_details):
if status == StatusCode.ok:
- _store_c_metadata(metadata, &c_metadata, &metadata_count)
- cb(user_data, c_metadata, metadata_count, status, NULL)
- _release_c_metadata(c_metadata, metadata_count)
- else:
- cb(user_data, NULL, 0, status, error_details)
- args = context.service_url, context.method_name, callback,
+ _store_c_metadata(metadata, &c_metadata, &metadata_count)
+ cb(user_data, c_metadata, metadata_count, status, NULL)
+ _release_c_metadata(c_metadata, metadata_count)
+ else:
+ cb(user_data, NULL, 0, status, error_details)
+ args = context.service_url, context.method_name, callback,
_spawn_callback_async(<object>state, args)
- return 0 # Asynchronous return
+ return 0 # Asynchronous return
cdef void _destroy(void *state) except * with gil:
- cpython.Py_DECREF(<object>state)
+ cpython.Py_DECREF(<object>state)
grpc_shutdown_blocking()
-cdef class MetadataPluginCallCredentials(CallCredentials):
+cdef class MetadataPluginCallCredentials(CallCredentials):
- def __cinit__(self, metadata_plugin, name):
- self._metadata_plugin = metadata_plugin
- self._name = name
+ def __cinit__(self, metadata_plugin, name):
+ self._metadata_plugin = metadata_plugin
+ self._name = name
cdef grpc_call_credentials *c(self) except *:
- cdef grpc_metadata_credentials_plugin c_metadata_plugin
- c_metadata_plugin.get_metadata = _get_metadata
- c_metadata_plugin.destroy = _destroy
- c_metadata_plugin.state = <void *>self._metadata_plugin
- c_metadata_plugin.type = self._name
- cpython.Py_INCREF(self._metadata_plugin)
+ cdef grpc_metadata_credentials_plugin c_metadata_plugin
+ c_metadata_plugin.get_metadata = _get_metadata
+ c_metadata_plugin.destroy = _destroy
+ c_metadata_plugin.state = <void *>self._metadata_plugin
+ c_metadata_plugin.type = self._name
+ cpython.Py_INCREF(self._metadata_plugin)
fork_handlers_and_grpc_init()
# TODO(yihuazhang): Expose min_security_level via the Python API so that
# applications can decide what minimum security level their plugins require.
return grpc_metadata_credentials_create_from_plugin(c_metadata_plugin, GRPC_PRIVACY_AND_INTEGRITY, NULL)
-cdef grpc_call_credentials *_composition(call_credentialses):
- call_credentials_iterator = iter(call_credentialses)
- cdef CallCredentials composition = next(call_credentials_iterator)
- cdef grpc_call_credentials *c_composition = composition.c()
- cdef CallCredentials additional_call_credentials
- cdef grpc_call_credentials *c_additional_call_credentials
- cdef grpc_call_credentials *c_next_composition
- for additional_call_credentials in call_credentials_iterator:
- c_additional_call_credentials = additional_call_credentials.c()
- c_next_composition = grpc_composite_call_credentials_create(
- c_composition, c_additional_call_credentials, NULL)
- grpc_call_credentials_release(c_composition)
- grpc_call_credentials_release(c_additional_call_credentials)
- c_composition = c_next_composition
- return c_composition
+cdef grpc_call_credentials *_composition(call_credentialses):
+ call_credentials_iterator = iter(call_credentialses)
+ cdef CallCredentials composition = next(call_credentials_iterator)
+ cdef grpc_call_credentials *c_composition = composition.c()
+ cdef CallCredentials additional_call_credentials
+ cdef grpc_call_credentials *c_additional_call_credentials
+ cdef grpc_call_credentials *c_next_composition
+ for additional_call_credentials in call_credentials_iterator:
+ c_additional_call_credentials = additional_call_credentials.c()
+ c_next_composition = grpc_composite_call_credentials_create(
+ c_composition, c_additional_call_credentials, NULL)
+ grpc_call_credentials_release(c_composition)
+ grpc_call_credentials_release(c_additional_call_credentials)
+ c_composition = c_next_composition
+ return c_composition
-cdef class CompositeCallCredentials(CallCredentials):
+cdef class CompositeCallCredentials(CallCredentials):
- def __cinit__(self, call_credentialses):
- self._call_credentialses = call_credentialses
+ def __cinit__(self, call_credentialses):
+ self._call_credentialses = call_credentialses
cdef grpc_call_credentials *c(self) except *:
- return _composition(self._call_credentialses)
+ return _composition(self._call_credentialses)
-cdef class ChannelCredentials:
+cdef class ChannelCredentials:
cdef grpc_channel_credentials *c(self) except *:
- raise NotImplementedError()
+ raise NotImplementedError()
cdef class SSLSessionCacheLRU:
@@ -127,26 +127,26 @@ cdef class SSLSessionCacheLRU:
grpc_shutdown_blocking()
-cdef class SSLChannelCredentials(ChannelCredentials):
+cdef class SSLChannelCredentials(ChannelCredentials):
- def __cinit__(self, pem_root_certificates, private_key, certificate_chain):
+ def __cinit__(self, pem_root_certificates, private_key, certificate_chain):
if pem_root_certificates is not None and not isinstance(pem_root_certificates, bytes):
raise TypeError('expected certificate to be bytes, got %s' % (type(pem_root_certificates)))
- self._pem_root_certificates = pem_root_certificates
- self._private_key = private_key
- self._certificate_chain = certificate_chain
+ self._pem_root_certificates = pem_root_certificates
+ self._private_key = private_key
+ self._certificate_chain = certificate_chain
cdef grpc_channel_credentials *c(self) except *:
- cdef const char *c_pem_root_certificates
- cdef grpc_ssl_pem_key_cert_pair c_pem_key_certificate_pair
- if self._pem_root_certificates is None:
- c_pem_root_certificates = NULL
- else:
- c_pem_root_certificates = self._pem_root_certificates
- if self._private_key is None and self._certificate_chain is None:
- return grpc_ssl_credentials_create(
+ cdef const char *c_pem_root_certificates
+ cdef grpc_ssl_pem_key_cert_pair c_pem_key_certificate_pair
+ if self._pem_root_certificates is None:
+ c_pem_root_certificates = NULL
+ else:
+ c_pem_root_certificates = self._pem_root_certificates
+ if self._private_key is None and self._certificate_chain is None:
+ return grpc_ssl_credentials_create(
c_pem_root_certificates, NULL, NULL, NULL)
- else:
+ else:
if self._private_key:
c_pem_key_certificate_pair.private_key = self._private_key
else:
@@ -155,142 +155,142 @@ cdef class SSLChannelCredentials(ChannelCredentials):
c_pem_key_certificate_pair.certificate_chain = self._certificate_chain
else:
c_pem_key_certificate_pair.certificate_chain = NULL
- return grpc_ssl_credentials_create(
+ return grpc_ssl_credentials_create(
c_pem_root_certificates, &c_pem_key_certificate_pair, NULL, NULL)
-cdef class CompositeChannelCredentials(ChannelCredentials):
+cdef class CompositeChannelCredentials(ChannelCredentials):
- def __cinit__(self, call_credentialses, channel_credentials):
- self._call_credentialses = call_credentialses
- self._channel_credentials = channel_credentials
+ def __cinit__(self, call_credentialses, channel_credentials):
+ self._call_credentialses = call_credentialses
+ self._channel_credentials = channel_credentials
cdef grpc_channel_credentials *c(self) except *:
- cdef grpc_channel_credentials *c_channel_credentials
- c_channel_credentials = self._channel_credentials.c()
- cdef grpc_call_credentials *c_call_credentials_composition = _composition(
- self._call_credentialses)
- cdef grpc_channel_credentials *composition
- c_composition = grpc_composite_channel_credentials_create(
- c_channel_credentials, c_call_credentials_composition, NULL)
- grpc_channel_credentials_release(c_channel_credentials)
- grpc_call_credentials_release(c_call_credentials_composition)
- return c_composition
+ cdef grpc_channel_credentials *c_channel_credentials
+ c_channel_credentials = self._channel_credentials.c()
+ cdef grpc_call_credentials *c_call_credentials_composition = _composition(
+ self._call_credentialses)
+ cdef grpc_channel_credentials *composition
+ c_composition = grpc_composite_channel_credentials_create(
+ c_channel_credentials, c_call_credentials_composition, NULL)
+ grpc_channel_credentials_release(c_channel_credentials)
+ grpc_call_credentials_release(c_call_credentials_composition)
+ return c_composition
-cdef class ServerCertificateConfig:
+cdef class ServerCertificateConfig:
- def __cinit__(self):
+ def __cinit__(self):
fork_handlers_and_grpc_init()
- self.c_cert_config = NULL
- self.c_pem_root_certs = NULL
- self.c_ssl_pem_key_cert_pairs = NULL
- self.references = []
-
- def __dealloc__(self):
- grpc_ssl_server_certificate_config_destroy(self.c_cert_config)
- gpr_free(self.c_ssl_pem_key_cert_pairs)
+ self.c_cert_config = NULL
+ self.c_pem_root_certs = NULL
+ self.c_ssl_pem_key_cert_pairs = NULL
+ self.references = []
+
+ 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()
-cdef class ServerCredentials:
+cdef class ServerCredentials:
- def __cinit__(self):
+ def __cinit__(self):
fork_handlers_and_grpc_init()
- self.c_credentials = NULL
- self.references = []
- self.initial_cert_config = None
- self.cert_config_fetcher = None
- self.initial_cert_config_fetched = False
-
- def __dealloc__(self):
- if self.c_credentials != NULL:
- grpc_server_credentials_release(self.c_credentials)
+ self.c_credentials = NULL
+ self.references = []
+ self.initial_cert_config = None
+ self.cert_config_fetcher = None
+ self.initial_cert_config_fetched = False
+
+ def __dealloc__(self):
+ if self.c_credentials != NULL:
+ grpc_server_credentials_release(self.c_credentials)
grpc_shutdown_blocking()
-cdef const char* _get_c_pem_root_certs(pem_root_certs):
- if pem_root_certs is None:
- return NULL
- else:
- return pem_root_certs
-
-cdef grpc_ssl_pem_key_cert_pair* _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs):
- # return a malloc'ed grpc_ssl_pem_key_cert_pair from a _list_ of SslPemKeyCertPair
- for pair in pem_key_cert_pairs:
- if not isinstance(pair, SslPemKeyCertPair):
- raise TypeError("expected pem_key_cert_pairs to be sequence of "
- "SslPemKeyCertPair")
- cdef size_t c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs)
- cdef grpc_ssl_pem_key_cert_pair* c_ssl_pem_key_cert_pairs = NULL
+cdef const char* _get_c_pem_root_certs(pem_root_certs):
+ if pem_root_certs is None:
+ return NULL
+ else:
+ return pem_root_certs
+
+cdef grpc_ssl_pem_key_cert_pair* _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs):
+ # return a malloc'ed grpc_ssl_pem_key_cert_pair from a _list_ of SslPemKeyCertPair
+ for pair in pem_key_cert_pairs:
+ if not isinstance(pair, SslPemKeyCertPair):
+ raise TypeError("expected pem_key_cert_pairs to be sequence of "
+ "SslPemKeyCertPair")
+ cdef size_t c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs)
+ cdef grpc_ssl_pem_key_cert_pair* c_ssl_pem_key_cert_pairs = NULL
with nogil:
- c_ssl_pem_key_cert_pairs = (
- <grpc_ssl_pem_key_cert_pair *>gpr_malloc(
- sizeof(grpc_ssl_pem_key_cert_pair) * c_ssl_pem_key_cert_pairs_count))
- for i in range(c_ssl_pem_key_cert_pairs_count):
- c_ssl_pem_key_cert_pairs[i] = (
- (<SslPemKeyCertPair>pem_key_cert_pairs[i]).c_pair)
- return c_ssl_pem_key_cert_pairs
+ c_ssl_pem_key_cert_pairs = (
+ <grpc_ssl_pem_key_cert_pair *>gpr_malloc(
+ sizeof(grpc_ssl_pem_key_cert_pair) * c_ssl_pem_key_cert_pairs_count))
+ for i in range(c_ssl_pem_key_cert_pairs_count):
+ c_ssl_pem_key_cert_pairs[i] = (
+ (<SslPemKeyCertPair>pem_key_cert_pairs[i]).c_pair)
+ return c_ssl_pem_key_cert_pairs
def server_credentials_ssl(pem_root_certs, pem_key_cert_pairs,
bint force_client_auth):
pem_root_certs = str_to_bytes(pem_root_certs)
pem_key_cert_pairs = list(pem_key_cert_pairs)
cdef ServerCredentials credentials = ServerCredentials()
- credentials.references.append(pem_root_certs)
+ credentials.references.append(pem_root_certs)
credentials.references.append(pem_key_cert_pairs)
- cdef const char * c_pem_root_certs = _get_c_pem_root_certs(pem_root_certs)
+ cdef const char * c_pem_root_certs = _get_c_pem_root_certs(pem_root_certs)
credentials.c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs)
- credentials.c_ssl_pem_key_cert_pairs = _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs)
- cdef grpc_ssl_server_certificate_config *c_cert_config = NULL
- c_cert_config = grpc_ssl_server_certificate_config_create(
- c_pem_root_certs, credentials.c_ssl_pem_key_cert_pairs,
- credentials.c_ssl_pem_key_cert_pairs_count)
- cdef grpc_ssl_server_credentials_options* c_options = NULL
- # C-core assumes ownership of c_cert_config
- c_options = grpc_ssl_server_credentials_create_options_using_config(
- GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
- if force_client_auth else
- GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE,
- c_cert_config)
- # C-core assumes ownership of c_options
- credentials.c_credentials = grpc_ssl_server_credentials_create_with_options(c_options)
+ credentials.c_ssl_pem_key_cert_pairs = _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs)
+ cdef grpc_ssl_server_certificate_config *c_cert_config = NULL
+ c_cert_config = grpc_ssl_server_certificate_config_create(
+ c_pem_root_certs, credentials.c_ssl_pem_key_cert_pairs,
+ credentials.c_ssl_pem_key_cert_pairs_count)
+ cdef grpc_ssl_server_credentials_options* c_options = NULL
+ # C-core assumes ownership of c_cert_config
+ c_options = grpc_ssl_server_credentials_create_options_using_config(
+ GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
+ if force_client_auth else
+ GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE,
+ c_cert_config)
+ # C-core assumes ownership of c_options
+ credentials.c_credentials = grpc_ssl_server_credentials_create_with_options(c_options)
return credentials
-def server_certificate_config_ssl(pem_root_certs, pem_key_cert_pairs):
- pem_root_certs = str_to_bytes(pem_root_certs)
- pem_key_cert_pairs = list(pem_key_cert_pairs)
- cdef ServerCertificateConfig cert_config = ServerCertificateConfig()
- cert_config.references.append(pem_root_certs)
- cert_config.references.append(pem_key_cert_pairs)
- cert_config.c_pem_root_certs = _get_c_pem_root_certs(pem_root_certs)
- cert_config.c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs)
- cert_config.c_ssl_pem_key_cert_pairs = _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs)
- cert_config.c_cert_config = grpc_ssl_server_certificate_config_create(
- cert_config.c_pem_root_certs, cert_config.c_ssl_pem_key_cert_pairs,
- cert_config.c_ssl_pem_key_cert_pairs_count)
- return cert_config
-
-def server_credentials_ssl_dynamic_cert_config(initial_cert_config,
- cert_config_fetcher,
- bint force_client_auth):
- if not isinstance(initial_cert_config, grpc.ServerCertificateConfiguration):
- raise TypeError(
- 'initial_cert_config must be a grpc.ServerCertificateConfiguration')
- if not callable(cert_config_fetcher):
- raise TypeError('cert_config_fetcher must be callable')
- cdef ServerCredentials credentials = ServerCredentials()
- credentials.initial_cert_config = initial_cert_config
- credentials.cert_config_fetcher = cert_config_fetcher
- cdef grpc_ssl_server_credentials_options* c_options = NULL
- c_options = grpc_ssl_server_credentials_create_options_using_config_fetcher(
- GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
- if force_client_auth else
- GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE,
- _server_cert_config_fetcher_wrapper,
- <void*>credentials)
- # C-core assumes ownership of c_options
- credentials.c_credentials = grpc_ssl_server_credentials_create_with_options(c_options)
- return credentials
+def server_certificate_config_ssl(pem_root_certs, pem_key_cert_pairs):
+ pem_root_certs = str_to_bytes(pem_root_certs)
+ pem_key_cert_pairs = list(pem_key_cert_pairs)
+ cdef ServerCertificateConfig cert_config = ServerCertificateConfig()
+ cert_config.references.append(pem_root_certs)
+ cert_config.references.append(pem_key_cert_pairs)
+ cert_config.c_pem_root_certs = _get_c_pem_root_certs(pem_root_certs)
+ cert_config.c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs)
+ cert_config.c_ssl_pem_key_cert_pairs = _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs)
+ cert_config.c_cert_config = grpc_ssl_server_certificate_config_create(
+ cert_config.c_pem_root_certs, cert_config.c_ssl_pem_key_cert_pairs,
+ cert_config.c_ssl_pem_key_cert_pairs_count)
+ return cert_config
+
+def server_credentials_ssl_dynamic_cert_config(initial_cert_config,
+ cert_config_fetcher,
+ bint force_client_auth):
+ if not isinstance(initial_cert_config, grpc.ServerCertificateConfiguration):
+ raise TypeError(
+ 'initial_cert_config must be a grpc.ServerCertificateConfiguration')
+ if not callable(cert_config_fetcher):
+ raise TypeError('cert_config_fetcher must be callable')
+ cdef ServerCredentials credentials = ServerCredentials()
+ credentials.initial_cert_config = initial_cert_config
+ credentials.cert_config_fetcher = cert_config_fetcher
+ cdef grpc_ssl_server_credentials_options* c_options = NULL
+ c_options = grpc_ssl_server_credentials_create_options_using_config_fetcher(
+ GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
+ if force_client_auth else
+ GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE,
+ _server_cert_config_fetcher_wrapper,
+ <void*>credentials)
+ # C-core assumes ownership of c_options
+ credentials.c_credentials = grpc_ssl_server_credentials_create_with_options(c_options)
+ return credentials
cdef grpc_ssl_certificate_config_reload_status _server_cert_config_fetcher_wrapper(
void* user_data, grpc_ssl_server_certificate_config **config) with gil:
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pxd.pxi
index 686199ecf4c..664762380f9 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pxd.pxi
@@ -1,45 +1,45 @@
-# 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.
-
-
-cdef class ConnectivityEvent:
-
- cdef readonly grpc_completion_type completion_type
- cdef readonly bint success
- cdef readonly object tag
-
-
-cdef class RequestCallEvent:
-
- cdef readonly grpc_completion_type completion_type
- cdef readonly bint success
- cdef readonly object tag
- cdef readonly Call call
- cdef readonly CallDetails call_details
- cdef readonly tuple invocation_metadata
-
-
-cdef class BatchOperationEvent:
-
- cdef readonly grpc_completion_type completion_type
- cdef readonly bint success
- cdef readonly object tag
- cdef readonly object batch_operations
-
-
-cdef class ServerShutdownEvent:
-
- cdef readonly grpc_completion_type completion_type
- cdef readonly bint success
- cdef readonly object 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.
+
+
+cdef class ConnectivityEvent:
+
+ cdef readonly grpc_completion_type completion_type
+ cdef readonly bint success
+ cdef readonly object tag
+
+
+cdef class RequestCallEvent:
+
+ cdef readonly grpc_completion_type completion_type
+ cdef readonly bint success
+ cdef readonly object tag
+ cdef readonly Call call
+ cdef readonly CallDetails call_details
+ cdef readonly tuple invocation_metadata
+
+
+cdef class BatchOperationEvent:
+
+ cdef readonly grpc_completion_type completion_type
+ cdef readonly bint success
+ cdef readonly object tag
+ cdef readonly object batch_operations
+
+
+cdef class ServerShutdownEvent:
+
+ cdef readonly grpc_completion_type completion_type
+ cdef readonly bint success
+ cdef readonly object tag
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pyx.pxi
index af26d273186..64437d96142 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/event.pyx.pxi
@@ -1,55 +1,55 @@
-# 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.
-
-
-cdef class ConnectivityEvent:
-
- def __cinit__(
- self, grpc_completion_type completion_type, bint success, object tag):
- self.completion_type = completion_type
- self.success = success
- self.tag = tag
-
-
-cdef class RequestCallEvent:
-
- def __cinit__(
- self, grpc_completion_type completion_type, bint success, object tag,
- Call call, CallDetails call_details, tuple invocation_metadata):
- self.completion_type = completion_type
- self.success = success
- self.tag = tag
- self.call = call
- self.call_details = call_details
- self.invocation_metadata = invocation_metadata
-
-
-cdef class BatchOperationEvent:
-
- def __cinit__(
- self, grpc_completion_type completion_type, bint success, object tag,
- object batch_operations):
- self.completion_type = completion_type
- self.success = success
- self.tag = tag
- self.batch_operations = batch_operations
-
-
-cdef class ServerShutdownEvent:
-
- def __cinit__(
- self, grpc_completion_type completion_type, bint success, object tag):
- self.completion_type = completion_type
- self.success = success
- self.tag = 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.
+
+
+cdef class ConnectivityEvent:
+
+ def __cinit__(
+ self, grpc_completion_type completion_type, bint success, object tag):
+ self.completion_type = completion_type
+ self.success = success
+ self.tag = tag
+
+
+cdef class RequestCallEvent:
+
+ def __cinit__(
+ self, grpc_completion_type completion_type, bint success, object tag,
+ Call call, CallDetails call_details, tuple invocation_metadata):
+ self.completion_type = completion_type
+ self.success = success
+ self.tag = tag
+ self.call = call
+ self.call_details = call_details
+ self.invocation_metadata = invocation_metadata
+
+
+cdef class BatchOperationEvent:
+
+ def __cinit__(
+ self, grpc_completion_type completion_type, bint success, object tag,
+ object batch_operations):
+ self.completion_type = completion_type
+ self.success = success
+ self.tag = tag
+ self.batch_operations = batch_operations
+
+
+cdef class ServerShutdownEvent:
+
+ def __cinit__(
+ self, grpc_completion_type completion_type, bint success, object tag):
+ self.completion_type = completion_type
+ self.success = success
+ self.tag = tag
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 54eb7fdffc4..bc34b061f81 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
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
cimport libc.time
@@ -29,7 +29,7 @@ ctypedef unsigned long long uint64_t
cdef extern from "grpc/support/alloc.h":
void *gpr_malloc(size_t size) nogil
- void *gpr_zalloc(size_t size) nogil
+ void *gpr_zalloc(size_t size) nogil
void gpr_free(void *ptr) nogil
void *gpr_realloc(void *p, size_t size) nogil
@@ -55,14 +55,14 @@ cdef extern from "grpc/grpc.h":
grpc_slice grpc_slice_ref(grpc_slice s) nogil
void grpc_slice_unref(grpc_slice s) nogil
- grpc_slice grpc_empty_slice() nogil
+ grpc_slice grpc_empty_slice() nogil
grpc_slice grpc_slice_new(void *p, size_t len, void (*destroy)(void *)) nogil
grpc_slice grpc_slice_new_with_len(
void *p, size_t len, void (*destroy)(void *, size_t)) nogil
grpc_slice grpc_slice_malloc(size_t length) nogil
grpc_slice grpc_slice_from_copied_string(const char *source) nogil
grpc_slice grpc_slice_from_copied_buffer(const char *source, size_t len) nogil
- grpc_slice grpc_slice_copy(grpc_slice s) nogil
+ grpc_slice grpc_slice_copy(grpc_slice s) nogil
# Declare functions for function-like macros (because Cython)...
void *grpc_slice_start_ptr "GRPC_SLICE_START_PTR" (grpc_slice s) nogil
@@ -183,7 +183,7 @@ cdef extern from "grpc/grpc.h":
ctypedef struct grpc_arg_pointer_vtable:
void *(*copy)(void *)
- void (*destroy)(void *)
+ void (*destroy)(void *)
int (*cmp)(void *, void *)
ctypedef struct grpc_arg_value_pointer:
@@ -204,12 +204,12 @@ cdef extern from "grpc/grpc.h":
size_t arguments_length "num_args"
grpc_arg *arguments "args"
- ctypedef enum grpc_stream_compression_level:
- GRPC_STREAM_COMPRESS_LEVEL_NONE
- GRPC_STREAM_COMPRESS_LEVEL_LOW
- GRPC_STREAM_COMPRESS_LEVEL_MED
- GRPC_STREAM_COMPRESS_LEVEL_HIGH
-
+ ctypedef enum grpc_stream_compression_level:
+ GRPC_STREAM_COMPRESS_LEVEL_NONE
+ GRPC_STREAM_COMPRESS_LEVEL_LOW
+ GRPC_STREAM_COMPRESS_LEVEL_MED
+ GRPC_STREAM_COMPRESS_LEVEL_HIGH
+
ctypedef enum grpc_call_error:
GRPC_CALL_OK
GRPC_CALL_ERROR
@@ -223,20 +223,20 @@ cdef extern from "grpc/grpc.h":
GRPC_CALL_ERROR_INVALID_FLAGS
GRPC_CALL_ERROR_INVALID_METADATA
- ctypedef enum grpc_cq_completion_type:
- GRPC_CQ_NEXT
- GRPC_CQ_PLUCK
-
- ctypedef enum grpc_cq_polling_type:
- GRPC_CQ_DEFAULT_POLLING
- GRPC_CQ_NON_LISTENING
- GRPC_CQ_NON_POLLING
-
- ctypedef struct grpc_completion_queue_attributes:
- int version
- grpc_cq_completion_type cq_completion_type
- grpc_cq_polling_type cq_polling_type
-
+ ctypedef enum grpc_cq_completion_type:
+ GRPC_CQ_NEXT
+ GRPC_CQ_PLUCK
+
+ ctypedef enum grpc_cq_polling_type:
+ GRPC_CQ_DEFAULT_POLLING
+ GRPC_CQ_NON_LISTENING
+ GRPC_CQ_NON_POLLING
+
+ ctypedef struct grpc_completion_queue_attributes:
+ int version
+ grpc_cq_completion_type cq_completion_type
+ grpc_cq_polling_type cq_polling_type
+
ctypedef enum grpc_connectivity_state:
GRPC_CHANNEL_IDLE
GRPC_CHANNEL_CONNECTING
@@ -245,8 +245,8 @@ cdef extern from "grpc/grpc.h":
GRPC_CHANNEL_SHUTDOWN
ctypedef struct grpc_metadata:
- grpc_slice key
- grpc_slice value
+ grpc_slice key
+ grpc_slice value
# ignore the 'internal_data.obfuscated' fields.
ctypedef enum grpc_completion_type:
@@ -268,8 +268,8 @@ cdef extern from "grpc/grpc.h":
void grpc_metadata_array_destroy(grpc_metadata_array *array) nogil
ctypedef struct grpc_call_details:
- grpc_slice method
- grpc_slice host
+ grpc_slice method
+ grpc_slice host
gpr_timespec deadline
void grpc_call_details_init(grpc_call_details *details) nogil
@@ -285,25 +285,25 @@ cdef extern from "grpc/grpc.h":
GRPC_OP_RECV_STATUS_ON_CLIENT
GRPC_OP_RECV_CLOSE_ON_SERVER
- ctypedef struct grpc_op_send_initial_metadata_maybe_compression_level:
- uint8_t is_set
- grpc_compression_level level
-
+ ctypedef struct grpc_op_send_initial_metadata_maybe_compression_level:
+ uint8_t is_set
+ grpc_compression_level level
+
ctypedef struct grpc_op_data_send_initial_metadata:
size_t count
grpc_metadata *metadata
- grpc_op_send_initial_metadata_maybe_compression_level maybe_compression_level
+ grpc_op_send_initial_metadata_maybe_compression_level maybe_compression_level
ctypedef struct grpc_op_data_send_status_from_server:
size_t trailing_metadata_count
grpc_metadata *trailing_metadata
grpc_status_code status
- grpc_slice *status_details
+ grpc_slice *status_details
ctypedef struct grpc_op_data_recv_status_on_client:
grpc_metadata_array *trailing_metadata
grpc_status_code *status
- grpc_slice *status_details
+ grpc_slice *status_details
char** error_string
ctypedef struct grpc_op_data_recv_close_on_server:
@@ -338,16 +338,16 @@ cdef extern from "grpc/grpc.h":
void grpc_shutdown_blocking() nogil
int grpc_is_initialized() nogil
- ctypedef struct grpc_completion_queue_factory:
- pass
-
- grpc_completion_queue_factory *grpc_completion_queue_factory_lookup(
- const grpc_completion_queue_attributes* attributes) nogil
- grpc_completion_queue *grpc_completion_queue_create(
- const grpc_completion_queue_factory* factory,
- const grpc_completion_queue_attributes* attr, void* reserved) nogil
- grpc_completion_queue *grpc_completion_queue_create_for_next(void *reserved) nogil
-
+ ctypedef struct grpc_completion_queue_factory:
+ pass
+
+ grpc_completion_queue_factory *grpc_completion_queue_factory_lookup(
+ const grpc_completion_queue_attributes* attributes) nogil
+ grpc_completion_queue *grpc_completion_queue_create(
+ const grpc_completion_queue_factory* factory,
+ const grpc_completion_queue_attributes* attr, void* reserved) nogil
+ grpc_completion_queue *grpc_completion_queue_create_for_next(void *reserved) nogil
+
grpc_event grpc_completion_queue_next(grpc_completion_queue *cq,
gpr_timespec deadline,
void *reserved) nogil
@@ -370,15 +370,15 @@ cdef extern from "grpc/grpc.h":
const char *description,
void *reserved) nogil
char *grpc_call_get_peer(grpc_call *call) nogil
- void grpc_call_unref(grpc_call *call) nogil
+ void grpc_call_unref(grpc_call *call) nogil
grpc_channel *grpc_insecure_channel_create(const char *target,
const grpc_channel_args *args,
void *reserved) nogil
grpc_call *grpc_channel_create_call(
- grpc_channel *channel, grpc_call *parent_call, uint32_t propagation_mask,
- grpc_completion_queue *completion_queue, grpc_slice method,
- const grpc_slice *host, gpr_timespec deadline, void *reserved) nogil
+ grpc_channel *channel, grpc_call *parent_call, uint32_t propagation_mask,
+ grpc_completion_queue *completion_queue, grpc_slice method,
+ const grpc_slice *host, gpr_timespec deadline, void *reserved) nogil
grpc_connectivity_state grpc_channel_check_connectivity_state(
grpc_channel *channel, int try_to_connect) nogil
void grpc_channel_watch_connectivity_state(
@@ -418,10 +418,10 @@ cdef extern from "grpc/grpc.h":
cdef extern from "grpc/grpc_security.h":
- # Declare this as an enum, this is the only way to make it a const in
- # cython
- enum: GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX
-
+ # Declare this as an enum, this is the only way to make it a const in
+ # cython
+ enum: GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX
+
ctypedef enum grpc_ssl_roots_override_result:
GRPC_SSL_ROOTS_OVERRIDE_OK
GRPC_SSL_ROOTS_OVERRIDE_FAILED_PERMANENTLY
@@ -441,42 +441,42 @@ cdef extern from "grpc/grpc_security.h":
GRPC_PRIVACY_AND_INTEGRITY
GRPC_SECURITY_MAX = GRPC_PRIVACY_AND_INTEGRITY
- ctypedef enum grpc_ssl_certificate_config_reload_status:
- GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED
- GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW
- GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL
-
- ctypedef struct grpc_ssl_server_certificate_config:
- # We don't care about the internals
- pass
-
- ctypedef struct grpc_ssl_server_credentials_options:
- # We don't care about the internals
- pass
-
- grpc_ssl_server_certificate_config * grpc_ssl_server_certificate_config_create(
- const char *pem_root_certs,
- const grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs,
- size_t num_key_cert_pairs)
-
- void grpc_ssl_server_certificate_config_destroy(grpc_ssl_server_certificate_config *config)
-
- ctypedef grpc_ssl_certificate_config_reload_status (*grpc_ssl_server_certificate_config_callback)(
- void *user_data,
- grpc_ssl_server_certificate_config **config)
-
- grpc_ssl_server_credentials_options *grpc_ssl_server_credentials_create_options_using_config(
- grpc_ssl_client_certificate_request_type client_certificate_request,
- grpc_ssl_server_certificate_config *certificate_config)
-
- grpc_ssl_server_credentials_options* grpc_ssl_server_credentials_create_options_using_config_fetcher(
- grpc_ssl_client_certificate_request_type client_certificate_request,
- grpc_ssl_server_certificate_config_callback cb,
- void *user_data)
-
- grpc_server_credentials *grpc_ssl_server_credentials_create_with_options(
- grpc_ssl_server_credentials_options *options)
-
+ ctypedef enum grpc_ssl_certificate_config_reload_status:
+ GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED
+ GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW
+ GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL
+
+ ctypedef struct grpc_ssl_server_certificate_config:
+ # We don't care about the internals
+ pass
+
+ ctypedef struct grpc_ssl_server_credentials_options:
+ # We don't care about the internals
+ pass
+
+ grpc_ssl_server_certificate_config * grpc_ssl_server_certificate_config_create(
+ const char *pem_root_certs,
+ const grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs,
+ size_t num_key_cert_pairs)
+
+ void grpc_ssl_server_certificate_config_destroy(grpc_ssl_server_certificate_config *config)
+
+ ctypedef grpc_ssl_certificate_config_reload_status (*grpc_ssl_server_certificate_config_callback)(
+ void *user_data,
+ grpc_ssl_server_certificate_config **config)
+
+ grpc_ssl_server_credentials_options *grpc_ssl_server_credentials_create_options_using_config(
+ grpc_ssl_client_certificate_request_type client_certificate_request,
+ grpc_ssl_server_certificate_config *certificate_config)
+
+ grpc_ssl_server_credentials_options* grpc_ssl_server_credentials_create_options_using_config_fetcher(
+ grpc_ssl_client_certificate_request_type client_certificate_request,
+ grpc_ssl_server_certificate_config_callback cb,
+ void *user_data)
+
+ grpc_server_credentials *grpc_ssl_server_credentials_create_with_options(
+ grpc_ssl_server_credentials_options *options)
+
ctypedef struct grpc_ssl_pem_key_cert_pair:
const char *private_key
const char *certificate_chain "cert_chain"
@@ -559,11 +559,11 @@ cdef extern from "grpc/grpc_security.h":
grpc_status_code status, const char *error_details)
ctypedef struct grpc_metadata_credentials_plugin:
- int (*get_metadata)(
+ int (*get_metadata)(
void *state, grpc_auth_metadata_context context,
- grpc_credentials_plugin_metadata_cb cb, void *user_data,
- grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
- size_t *num_creds_md, grpc_status_code *status,
+ 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 *
void *state
@@ -572,36 +572,36 @@ cdef extern from "grpc/grpc_security.h":
grpc_call_credentials *grpc_metadata_credentials_create_from_plugin(
grpc_metadata_credentials_plugin plugin, grpc_security_level min_security_level, void *reserved) nogil
- ctypedef struct grpc_auth_property_iterator:
- pass
-
- ctypedef struct grpc_auth_property:
- char *name
- char *value
- size_t value_length
-
- grpc_auth_property *grpc_auth_property_iterator_next(
- grpc_auth_property_iterator *it)
-
- grpc_auth_property_iterator grpc_auth_context_property_iterator(
- const grpc_auth_context *ctx)
-
- grpc_auth_property_iterator grpc_auth_context_peer_identity(
- const grpc_auth_context *ctx)
-
- char *grpc_auth_context_peer_identity_property_name(
- const grpc_auth_context *ctx)
-
- grpc_auth_property_iterator grpc_auth_context_find_properties_by_name(
- const grpc_auth_context *ctx, const char *name)
-
- grpc_auth_context_peer_is_authenticated(
- const grpc_auth_context *ctx)
-
- grpc_auth_context *grpc_call_auth_context(grpc_call *call)
-
- void grpc_auth_context_release(grpc_auth_context *context)
+ ctypedef struct grpc_auth_property_iterator:
+ pass
+ ctypedef struct grpc_auth_property:
+ char *name
+ char *value
+ size_t value_length
+
+ grpc_auth_property *grpc_auth_property_iterator_next(
+ grpc_auth_property_iterator *it)
+
+ grpc_auth_property_iterator grpc_auth_context_property_iterator(
+ const grpc_auth_context *ctx)
+
+ grpc_auth_property_iterator grpc_auth_context_peer_identity(
+ const grpc_auth_context *ctx)
+
+ char *grpc_auth_context_peer_identity_property_name(
+ const grpc_auth_context *ctx)
+
+ grpc_auth_property_iterator grpc_auth_context_find_properties_by_name(
+ const grpc_auth_context *ctx, const char *name)
+
+ grpc_auth_context_peer_is_authenticated(
+ const grpc_auth_context *ctx)
+
+ grpc_auth_context *grpc_call_auth_context(grpc_call *call)
+
+ 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(
@@ -629,7 +629,7 @@ cdef extern from "grpc/compression.h":
GRPC_COMPRESS_NONE
GRPC_COMPRESS_DEFLATE
GRPC_COMPRESS_GZIP
- GRPC_COMPRESS_STREAM_GZIP
+ GRPC_COMPRESS_STREAM_GZIP
GRPC_COMPRESS_ALGORITHMS_COUNT
ctypedef enum grpc_compression_level:
@@ -643,9 +643,9 @@ cdef extern from "grpc/compression.h":
uint32_t enabled_algorithms_bitset
int grpc_compression_algorithm_parse(
- grpc_slice value, grpc_compression_algorithm *algorithm) nogil
+ grpc_slice value, grpc_compression_algorithm *algorithm) nogil
int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm,
- const char **name) nogil
+ const char **name) nogil
grpc_compression_algorithm grpc_compression_algorithm_for_level(
grpc_compression_level level, uint32_t accepted_encodings) nogil
void grpc_compression_options_init(grpc_compression_options *opts) nogil
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 5c1e0679a97..ac8e3d01c1e 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
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 function will ascii encode unicode string inputs if necessary.
@@ -22,30 +22,30 @@ cdef bytes str_to_bytes(object s):
return s.encode('ascii')
else:
raise TypeError('Expected bytes, str, or unicode, not {}'.format(type(s)))
-
-
-# TODO(https://github.com/grpc/grpc/issues/13782): It would be nice for us if
-# the type of metadata that we accept were exactly the same as the type of
-# metadata that we deliver to our users (so "str" for this function's
-# parameter rather than "object"), but would it be nice for our users? Right
-# now we haven't yet heard from enough users to know one way or another.
-cdef bytes _encode(object string_or_none):
- if string_or_none is None:
- return b''
- elif isinstance(string_or_none, (bytes,)):
- return <bytes>string_or_none
- elif isinstance(string_or_none, (unicode,)):
+
+
+# TODO(https://github.com/grpc/grpc/issues/13782): It would be nice for us if
+# the type of metadata that we accept were exactly the same as the type of
+# metadata that we deliver to our users (so "str" for this function's
+# parameter rather than "object"), but would it be nice for our users? Right
+# now we haven't yet heard from enough users to know one way or another.
+cdef bytes _encode(object string_or_none):
+ if string_or_none is None:
+ return b''
+ elif isinstance(string_or_none, (bytes,)):
+ return <bytes>string_or_none
+ elif isinstance(string_or_none, (unicode,)):
return string_or_none.encode('utf8')
- else:
- raise TypeError('Expected str, not {}'.format(type(string_or_none)))
-
-
-cdef str _decode(bytes bytestring):
- if isinstance(bytestring, (str,)):
- return <str>bytestring
- else:
- try:
- return bytestring.decode('utf8')
- except UnicodeDecodeError:
+ else:
+ raise TypeError('Expected str, not {}'.format(type(string_or_none)))
+
+
+cdef str _decode(bytes bytestring):
+ if isinstance(bytestring, (str,)):
+ return <str>bytestring
+ else:
+ try:
+ return bytestring.decode('utf8')
+ except UnicodeDecodeError:
_LOGGER.exception('Invalid encoding on %s', bytestring)
- return bytestring.decode('latin1')
+ return bytestring.decode('latin1')
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi
index fc72ac1576b..d743aae5619 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi
@@ -1,26 +1,26 @@
-# 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.
-
-
-cdef void _store_c_metadata(
+# 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.
+
+
+cdef void _store_c_metadata(
metadata, grpc_metadata **c_metadata, size_t *c_count) except *
-
-
+
+
cdef void _release_c_metadata(grpc_metadata *c_metadata, int count) except *
-
-
-cdef tuple _metadatum(grpc_slice key_slice, grpc_slice value_slice)
-
-
-cdef tuple _metadata(grpc_metadata_array *c_metadata_array)
+
+
+cdef tuple _metadatum(grpc_slice key_slice, grpc_slice value_slice)
+
+
+cdef tuple _metadata(grpc_metadata_array *c_metadata_array)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi
index b2dd1e33808..0c52a22489d 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi
@@ -1,73 +1,73 @@
-# 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 collections
-
-
+# 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 collections
+
+
class InitialMetadataFlags:
used_mask = GRPC_INITIAL_METADATA_USED_MASK
wait_for_ready = GRPC_INITIAL_METADATA_WAIT_FOR_READY
wait_for_ready_explicitly_set = GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET
-_Metadatum = collections.namedtuple('_Metadatum', ('key', 'value',))
-
-
-cdef void _store_c_metadata(
+_Metadatum = collections.namedtuple('_Metadatum', ('key', 'value',))
+
+
+cdef void _store_c_metadata(
metadata, grpc_metadata **c_metadata, size_t *c_count) except *:
- if metadata is None:
- c_count[0] = 0
- c_metadata[0] = NULL
- else:
- metadatum_count = len(metadata)
- if metadatum_count == 0:
- c_count[0] = 0
- c_metadata[0] = NULL
- else:
- c_count[0] = metadatum_count
- c_metadata[0] = <grpc_metadata *>gpr_malloc(
- metadatum_count * sizeof(grpc_metadata))
- for index, (key, value) in enumerate(metadata):
- encoded_key = _encode(key)
- encoded_value = value if encoded_key[-4:] == b'-bin' else _encode(value)
+ if metadata is None:
+ c_count[0] = 0
+ c_metadata[0] = NULL
+ else:
+ metadatum_count = len(metadata)
+ if metadatum_count == 0:
+ c_count[0] = 0
+ c_metadata[0] = NULL
+ else:
+ c_count[0] = metadatum_count
+ c_metadata[0] = <grpc_metadata *>gpr_malloc(
+ metadatum_count * sizeof(grpc_metadata))
+ for index, (key, value) in enumerate(metadata):
+ encoded_key = _encode(key)
+ encoded_value = value if encoded_key[-4:] == b'-bin' else _encode(value)
if not isinstance(encoded_value, bytes):
raise TypeError('Binary metadata key="%s" expected bytes, got %s' % (
key,
type(encoded_value)
))
- c_metadata[0][index].key = _slice_from_bytes(encoded_key)
- c_metadata[0][index].value = _slice_from_bytes(encoded_value)
-
-
+ c_metadata[0][index].key = _slice_from_bytes(encoded_key)
+ c_metadata[0][index].value = _slice_from_bytes(encoded_value)
+
+
cdef void _release_c_metadata(grpc_metadata *c_metadata, int count) except *:
- if 0 < count:
- for index in range(count):
- grpc_slice_unref(c_metadata[index].key)
- grpc_slice_unref(c_metadata[index].value)
- gpr_free(c_metadata)
-
-
-cdef tuple _metadatum(grpc_slice key_slice, grpc_slice value_slice):
- cdef bytes key = _slice_bytes(key_slice)
- cdef bytes value = _slice_bytes(value_slice)
- return <tuple>_Metadatum(
- _decode(key), value if key[-4:] == b'-bin' else _decode(value))
-
-
-cdef tuple _metadata(grpc_metadata_array *c_metadata_array):
- return tuple(
- _metadatum(
- c_metadata_array.metadata[index].key,
- c_metadata_array.metadata[index].value)
- for index in range(c_metadata_array.count))
+ if 0 < count:
+ for index in range(count):
+ grpc_slice_unref(c_metadata[index].key)
+ grpc_slice_unref(c_metadata[index].value)
+ gpr_free(c_metadata)
+
+
+cdef tuple _metadatum(grpc_slice key_slice, grpc_slice value_slice):
+ cdef bytes key = _slice_bytes(key_slice)
+ cdef bytes value = _slice_bytes(value_slice)
+ return <tuple>_Metadatum(
+ _decode(key), value if key[-4:] == b'-bin' else _decode(value))
+
+
+cdef tuple _metadata(grpc_metadata_array *c_metadata_array):
+ return tuple(
+ _metadatum(
+ c_metadata_array.metadata[index].key,
+ c_metadata_array.metadata[index].value)
+ for index in range(c_metadata_array.count))
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi
index c9df32dadf5..a992eca09cf 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi
@@ -1,111 +1,111 @@
-# 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.
-
-
-cdef class Operation:
-
+# 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.
+
+
+cdef class Operation:
+
cdef void c(self) except *
cdef void un_c(self) except *
-
- # TODO(https://github.com/grpc/grpc/issues/7950): Eliminate this!
- cdef grpc_op c_op
-
-
-cdef class SendInitialMetadataOperation(Operation):
-
- cdef readonly object _initial_metadata;
- cdef readonly int _flags
- cdef grpc_metadata *_c_initial_metadata
- cdef size_t _c_initial_metadata_count
-
+
+ # TODO(https://github.com/grpc/grpc/issues/7950): Eliminate this!
+ cdef grpc_op c_op
+
+
+cdef class SendInitialMetadataOperation(Operation):
+
+ cdef readonly object _initial_metadata;
+ cdef readonly int _flags
+ cdef grpc_metadata *_c_initial_metadata
+ cdef size_t _c_initial_metadata_count
+
cdef void c(self) except *
cdef void un_c(self) except *
-
-
-cdef class SendMessageOperation(Operation):
-
- cdef readonly bytes _message
- cdef readonly int _flags
- cdef grpc_byte_buffer *_c_message_byte_buffer
-
+
+
+cdef class SendMessageOperation(Operation):
+
+ cdef readonly bytes _message
+ cdef readonly int _flags
+ cdef grpc_byte_buffer *_c_message_byte_buffer
+
cdef void c(self) except *
cdef void un_c(self) except *
-
-
-cdef class SendCloseFromClientOperation(Operation):
-
- cdef readonly int _flags
-
+
+
+cdef class SendCloseFromClientOperation(Operation):
+
+ cdef readonly int _flags
+
cdef void c(self) except *
cdef void un_c(self) except *
-
-
-cdef class SendStatusFromServerOperation(Operation):
-
- cdef readonly object _trailing_metadata
- cdef readonly object _code
- cdef readonly object _details
- cdef readonly int _flags
- cdef grpc_metadata *_c_trailing_metadata
- cdef size_t _c_trailing_metadata_count
- cdef grpc_slice _c_details
-
+
+
+cdef class SendStatusFromServerOperation(Operation):
+
+ cdef readonly object _trailing_metadata
+ cdef readonly object _code
+ cdef readonly object _details
+ cdef readonly int _flags
+ cdef grpc_metadata *_c_trailing_metadata
+ cdef size_t _c_trailing_metadata_count
+ cdef grpc_slice _c_details
+
cdef void c(self) except *
cdef void un_c(self) except *
-
-
-cdef class ReceiveInitialMetadataOperation(Operation):
-
- cdef readonly int _flags
- cdef tuple _initial_metadata
- cdef grpc_metadata_array _c_initial_metadata
-
+
+
+cdef class ReceiveInitialMetadataOperation(Operation):
+
+ cdef readonly int _flags
+ cdef tuple _initial_metadata
+ cdef grpc_metadata_array _c_initial_metadata
+
cdef void c(self) except *
cdef void un_c(self) except *
-
-
-cdef class ReceiveMessageOperation(Operation):
-
- cdef readonly int _flags
- cdef grpc_byte_buffer *_c_message_byte_buffer
- cdef bytes _message
-
+
+
+cdef class ReceiveMessageOperation(Operation):
+
+ cdef readonly int _flags
+ cdef grpc_byte_buffer *_c_message_byte_buffer
+ cdef bytes _message
+
cdef void c(self) except *
cdef void un_c(self) except *
-
-
-cdef class ReceiveStatusOnClientOperation(Operation):
-
- cdef readonly int _flags
- cdef grpc_metadata_array _c_trailing_metadata
- cdef grpc_status_code _c_code
- cdef grpc_slice _c_details
+
+
+cdef class ReceiveStatusOnClientOperation(Operation):
+
+ cdef readonly int _flags
+ cdef grpc_metadata_array _c_trailing_metadata
+ cdef grpc_status_code _c_code
+ cdef grpc_slice _c_details
cdef const char* _c_error_string
- cdef tuple _trailing_metadata
- cdef object _code
- cdef str _details
+ cdef tuple _trailing_metadata
+ cdef object _code
+ cdef str _details
cdef str _error_string
-
+
cdef void c(self) except *
cdef void un_c(self) except *
-
-
-cdef class ReceiveCloseOnServerOperation(Operation):
-
- cdef readonly int _flags
- cdef object _cancelled
- cdef int _c_cancelled
-
+
+
+cdef class ReceiveCloseOnServerOperation(Operation):
+
+ cdef readonly int _flags
+ cdef object _cancelled
+ cdef int _c_cancelled
+
cdef void c(self) except *
cdef void un_c(self) except *
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi
index 3f3fd75407c..a1e1b61665b 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi
@@ -1,250 +1,250 @@
-# 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.
-
-
-cdef class Operation:
-
+# 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.
+
+
+cdef class Operation:
+
cdef void c(self) except *:
- raise NotImplementedError()
-
+ raise NotImplementedError()
+
cdef void un_c(self) except *:
- raise NotImplementedError()
-
-
-cdef class SendInitialMetadataOperation(Operation):
-
- def __cinit__(self, initial_metadata, flags):
- self._initial_metadata = initial_metadata
- self._flags = flags
-
- def type(self):
- return GRPC_OP_SEND_INITIAL_METADATA
-
+ raise NotImplementedError()
+
+
+cdef class SendInitialMetadataOperation(Operation):
+
+ def __cinit__(self, initial_metadata, flags):
+ self._initial_metadata = initial_metadata
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_SEND_INITIAL_METADATA
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_SEND_INITIAL_METADATA
- self.c_op.flags = self._flags
- _store_c_metadata(
- self._initial_metadata, &self._c_initial_metadata,
- &self._c_initial_metadata_count)
- self.c_op.data.send_initial_metadata.metadata = self._c_initial_metadata
- self.c_op.data.send_initial_metadata.count = self._c_initial_metadata_count
- self.c_op.data.send_initial_metadata.maybe_compression_level.is_set = 0
-
+ self.c_op.type = GRPC_OP_SEND_INITIAL_METADATA
+ self.c_op.flags = self._flags
+ _store_c_metadata(
+ self._initial_metadata, &self._c_initial_metadata,
+ &self._c_initial_metadata_count)
+ self.c_op.data.send_initial_metadata.metadata = self._c_initial_metadata
+ self.c_op.data.send_initial_metadata.count = self._c_initial_metadata_count
+ self.c_op.data.send_initial_metadata.maybe_compression_level.is_set = 0
+
cdef void un_c(self) except *:
- _release_c_metadata(
- self._c_initial_metadata, self._c_initial_metadata_count)
-
-
-cdef class SendMessageOperation(Operation):
-
- def __cinit__(self, bytes message, int flags):
+ _release_c_metadata(
+ self._c_initial_metadata, self._c_initial_metadata_count)
+
+
+cdef class SendMessageOperation(Operation):
+
+ def __cinit__(self, bytes message, int flags):
if message is None:
self._message = b''
else:
self._message = message
- self._flags = flags
-
- def type(self):
- return GRPC_OP_SEND_MESSAGE
-
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_SEND_MESSAGE
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_SEND_MESSAGE
- self.c_op.flags = self._flags
- cdef grpc_slice message_slice = grpc_slice_from_copied_buffer(
- self._message, len(self._message))
- self._c_message_byte_buffer = grpc_raw_byte_buffer_create(
- &message_slice, 1)
- grpc_slice_unref(message_slice)
- self.c_op.data.send_message.send_message = self._c_message_byte_buffer
-
+ self.c_op.type = GRPC_OP_SEND_MESSAGE
+ self.c_op.flags = self._flags
+ cdef grpc_slice message_slice = grpc_slice_from_copied_buffer(
+ self._message, len(self._message))
+ self._c_message_byte_buffer = grpc_raw_byte_buffer_create(
+ &message_slice, 1)
+ grpc_slice_unref(message_slice)
+ self.c_op.data.send_message.send_message = self._c_message_byte_buffer
+
cdef void un_c(self) except *:
- grpc_byte_buffer_destroy(self._c_message_byte_buffer)
-
-
-cdef class SendCloseFromClientOperation(Operation):
-
- def __cinit__(self, int flags):
- self._flags = flags
-
- def type(self):
- return GRPC_OP_SEND_CLOSE_FROM_CLIENT
-
+ grpc_byte_buffer_destroy(self._c_message_byte_buffer)
+
+
+cdef class SendCloseFromClientOperation(Operation):
+
+ def __cinit__(self, int flags):
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_SEND_CLOSE_FROM_CLIENT
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_SEND_CLOSE_FROM_CLIENT
- self.c_op.flags = self._flags
-
+ self.c_op.type = GRPC_OP_SEND_CLOSE_FROM_CLIENT
+ self.c_op.flags = self._flags
+
cdef void un_c(self) except *:
- pass
-
-
-cdef class SendStatusFromServerOperation(Operation):
-
- def __cinit__(self, trailing_metadata, code, object details, int flags):
- self._trailing_metadata = trailing_metadata
- self._code = code
- self._details = details
- self._flags = flags
-
- def type(self):
- return GRPC_OP_SEND_STATUS_FROM_SERVER
-
+ pass
+
+
+cdef class SendStatusFromServerOperation(Operation):
+
+ def __cinit__(self, trailing_metadata, code, object details, int flags):
+ self._trailing_metadata = trailing_metadata
+ self._code = code
+ self._details = details
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_SEND_STATUS_FROM_SERVER
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_SEND_STATUS_FROM_SERVER
- self.c_op.flags = self._flags
- _store_c_metadata(
- self._trailing_metadata, &self._c_trailing_metadata,
- &self._c_trailing_metadata_count)
- self.c_op.data.send_status_from_server.trailing_metadata = (
- self._c_trailing_metadata)
- self.c_op.data.send_status_from_server.trailing_metadata_count = (
- self._c_trailing_metadata_count)
- self.c_op.data.send_status_from_server.status = self._code
- self._c_details = _slice_from_bytes(_encode(self._details))
- self.c_op.data.send_status_from_server.status_details = &self._c_details
-
+ self.c_op.type = GRPC_OP_SEND_STATUS_FROM_SERVER
+ self.c_op.flags = self._flags
+ _store_c_metadata(
+ self._trailing_metadata, &self._c_trailing_metadata,
+ &self._c_trailing_metadata_count)
+ self.c_op.data.send_status_from_server.trailing_metadata = (
+ self._c_trailing_metadata)
+ self.c_op.data.send_status_from_server.trailing_metadata_count = (
+ self._c_trailing_metadata_count)
+ self.c_op.data.send_status_from_server.status = self._code
+ self._c_details = _slice_from_bytes(_encode(self._details))
+ self.c_op.data.send_status_from_server.status_details = &self._c_details
+
cdef void un_c(self) except *:
- grpc_slice_unref(self._c_details)
- _release_c_metadata(
- self._c_trailing_metadata, self._c_trailing_metadata_count)
-
-
-cdef class ReceiveInitialMetadataOperation(Operation):
-
- def __cinit__(self, flags):
- self._flags = flags
-
- def type(self):
- return GRPC_OP_RECV_INITIAL_METADATA
-
+ grpc_slice_unref(self._c_details)
+ _release_c_metadata(
+ self._c_trailing_metadata, self._c_trailing_metadata_count)
+
+
+cdef class ReceiveInitialMetadataOperation(Operation):
+
+ def __cinit__(self, flags):
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_RECV_INITIAL_METADATA
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_RECV_INITIAL_METADATA
- self.c_op.flags = self._flags
- grpc_metadata_array_init(&self._c_initial_metadata)
- self.c_op.data.receive_initial_metadata.receive_initial_metadata = (
- &self._c_initial_metadata)
-
+ self.c_op.type = GRPC_OP_RECV_INITIAL_METADATA
+ self.c_op.flags = self._flags
+ grpc_metadata_array_init(&self._c_initial_metadata)
+ self.c_op.data.receive_initial_metadata.receive_initial_metadata = (
+ &self._c_initial_metadata)
+
cdef void un_c(self) except *:
- self._initial_metadata = _metadata(&self._c_initial_metadata)
- grpc_metadata_array_destroy(&self._c_initial_metadata)
-
- def initial_metadata(self):
- return self._initial_metadata
-
-
-cdef class ReceiveMessageOperation(Operation):
-
- def __cinit__(self, flags):
- self._flags = flags
-
- def type(self):
- return GRPC_OP_RECV_MESSAGE
-
+ self._initial_metadata = _metadata(&self._c_initial_metadata)
+ grpc_metadata_array_destroy(&self._c_initial_metadata)
+
+ def initial_metadata(self):
+ return self._initial_metadata
+
+
+cdef class ReceiveMessageOperation(Operation):
+
+ def __cinit__(self, flags):
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_RECV_MESSAGE
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_RECV_MESSAGE
- self.c_op.flags = self._flags
- self.c_op.data.receive_message.receive_message = (
- &self._c_message_byte_buffer)
-
+ self.c_op.type = GRPC_OP_RECV_MESSAGE
+ self.c_op.flags = self._flags
+ self.c_op.data.receive_message.receive_message = (
+ &self._c_message_byte_buffer)
+
cdef void un_c(self) except *:
- cdef grpc_byte_buffer_reader message_reader
- cdef bint message_reader_status
- cdef grpc_slice message_slice
- cdef size_t message_slice_length
- cdef void *message_slice_pointer
- if self._c_message_byte_buffer != NULL:
- message_reader_status = grpc_byte_buffer_reader_init(
- &message_reader, self._c_message_byte_buffer)
- if message_reader_status:
- message = bytearray()
- while grpc_byte_buffer_reader_next(&message_reader, &message_slice):
- message_slice_pointer = grpc_slice_start_ptr(message_slice)
- message_slice_length = grpc_slice_length(message_slice)
- message += (<char *>message_slice_pointer)[:message_slice_length]
- grpc_slice_unref(message_slice)
- grpc_byte_buffer_reader_destroy(&message_reader)
- self._message = bytes(message)
- else:
- self._message = None
- grpc_byte_buffer_destroy(self._c_message_byte_buffer)
- else:
- self._message = None
-
- def message(self):
- return self._message
-
-
-cdef class ReceiveStatusOnClientOperation(Operation):
-
- def __cinit__(self, flags):
- self._flags = flags
-
- def type(self):
- return GRPC_OP_RECV_STATUS_ON_CLIENT
-
+ cdef grpc_byte_buffer_reader message_reader
+ cdef bint message_reader_status
+ cdef grpc_slice message_slice
+ cdef size_t message_slice_length
+ cdef void *message_slice_pointer
+ if self._c_message_byte_buffer != NULL:
+ message_reader_status = grpc_byte_buffer_reader_init(
+ &message_reader, self._c_message_byte_buffer)
+ if message_reader_status:
+ message = bytearray()
+ while grpc_byte_buffer_reader_next(&message_reader, &message_slice):
+ message_slice_pointer = grpc_slice_start_ptr(message_slice)
+ message_slice_length = grpc_slice_length(message_slice)
+ message += (<char *>message_slice_pointer)[:message_slice_length]
+ grpc_slice_unref(message_slice)
+ grpc_byte_buffer_reader_destroy(&message_reader)
+ self._message = bytes(message)
+ else:
+ self._message = None
+ grpc_byte_buffer_destroy(self._c_message_byte_buffer)
+ else:
+ self._message = None
+
+ def message(self):
+ return self._message
+
+
+cdef class ReceiveStatusOnClientOperation(Operation):
+
+ def __cinit__(self, flags):
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_RECV_STATUS_ON_CLIENT
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_RECV_STATUS_ON_CLIENT
- self.c_op.flags = self._flags
- grpc_metadata_array_init(&self._c_trailing_metadata)
- self.c_op.data.receive_status_on_client.trailing_metadata = (
- &self._c_trailing_metadata)
- self.c_op.data.receive_status_on_client.status = (
- &self._c_code)
- self.c_op.data.receive_status_on_client.status_details = (
- &self._c_details)
+ self.c_op.type = GRPC_OP_RECV_STATUS_ON_CLIENT
+ self.c_op.flags = self._flags
+ grpc_metadata_array_init(&self._c_trailing_metadata)
+ self.c_op.data.receive_status_on_client.trailing_metadata = (
+ &self._c_trailing_metadata)
+ self.c_op.data.receive_status_on_client.status = (
+ &self._c_code)
+ self.c_op.data.receive_status_on_client.status_details = (
+ &self._c_details)
self.c_op.data.receive_status_on_client.error_string = (
&self._c_error_string)
-
+
cdef void un_c(self) except *:
- self._trailing_metadata = _metadata(&self._c_trailing_metadata)
- grpc_metadata_array_destroy(&self._c_trailing_metadata)
- self._code = self._c_code
- self._details = _decode(_slice_bytes(self._c_details))
- grpc_slice_unref(self._c_details)
+ self._trailing_metadata = _metadata(&self._c_trailing_metadata)
+ grpc_metadata_array_destroy(&self._c_trailing_metadata)
+ self._code = self._c_code
+ self._details = _decode(_slice_bytes(self._c_details))
+ grpc_slice_unref(self._c_details)
if self._c_error_string != NULL:
self._error_string = _decode(self._c_error_string)
gpr_free(<void*>self._c_error_string)
else:
self._error_string = ""
-
- def trailing_metadata(self):
- return self._trailing_metadata
-
- def code(self):
- return self._code
-
- def details(self):
- return self._details
-
+
+ def trailing_metadata(self):
+ return self._trailing_metadata
+
+ def code(self):
+ return self._code
+
+ def details(self):
+ return self._details
+
def error_string(self):
return self._error_string
-
-
-cdef class ReceiveCloseOnServerOperation(Operation):
-
- def __cinit__(self, flags):
- self._flags = flags
-
- def type(self):
- return GRPC_OP_RECV_CLOSE_ON_SERVER
-
+
+
+cdef class ReceiveCloseOnServerOperation(Operation):
+
+ def __cinit__(self, flags):
+ self._flags = flags
+
+ def type(self):
+ return GRPC_OP_RECV_CLOSE_ON_SERVER
+
cdef void c(self) except *:
- self.c_op.type = GRPC_OP_RECV_CLOSE_ON_SERVER
- self.c_op.flags = self._flags
- self.c_op.data.receive_close_on_server.cancelled = &self._c_cancelled
-
+ self.c_op.type = GRPC_OP_RECV_CLOSE_ON_SERVER
+ self.c_op.flags = self._flags
+ self.c_op.data.receive_close_on_server.cancelled = &self._c_cancelled
+
cdef void un_c(self) except *:
- self._cancelled = bool(self._c_cancelled)
-
- def cancelled(self):
- return self._cancelled
+ self._cancelled = bool(self._c_cancelled)
+
+ def cancelled(self):
+ return self._cancelled
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pxd.pxi
index 35e1bdb0aeb..d69b51a9e84 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pxd.pxi
@@ -1,21 +1,21 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 bytes _slice_bytes(grpc_slice slice)
-cdef grpc_slice _copy_slice(grpc_slice slice) nogil
-cdef grpc_slice _slice_from_bytes(bytes value) nogil
+cdef bytes _slice_bytes(grpc_slice slice)
+cdef grpc_slice _copy_slice(grpc_slice slice) nogil
+cdef grpc_slice _slice_from_bytes(bytes value) nogil
cdef class CallDetails:
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 308d677695f..755bc9fa9d1 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
@@ -1,37 +1,37 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT 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 bytes _slice_bytes(grpc_slice slice):
- cdef void *start = grpc_slice_start_ptr(slice)
- cdef size_t length = grpc_slice_length(slice)
- return (<const char *>start)[:length]
-
-cdef grpc_slice _copy_slice(grpc_slice slice) nogil:
- cdef void *start = grpc_slice_start_ptr(slice)
- cdef size_t length = grpc_slice_length(slice)
- return grpc_slice_from_copied_buffer(<const char *>start, length)
-
-cdef grpc_slice _slice_from_bytes(bytes value) nogil:
- cdef const char *value_ptr
- cdef size_t length
- with gil:
- value_ptr = <const char *>value
- length = len(value)
- return grpc_slice_from_copied_buffer(value_ptr, length)
-
-
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 bytes _slice_bytes(grpc_slice slice):
+ cdef void *start = grpc_slice_start_ptr(slice)
+ cdef size_t length = grpc_slice_length(slice)
+ return (<const char *>start)[:length]
+
+cdef grpc_slice _copy_slice(grpc_slice slice) nogil:
+ cdef void *start = grpc_slice_start_ptr(slice)
+ cdef size_t length = grpc_slice_length(slice)
+ return grpc_slice_from_copied_buffer(<const char *>start, length)
+
+cdef grpc_slice _slice_from_bytes(bytes value) nogil:
+ cdef const char *value_ptr
+ cdef size_t length
+ with gil:
+ value_ptr = <const char *>value
+ length = len(value)
+ return grpc_slice_from_copied_buffer(value_ptr, length)
+
+
class ConnectivityState:
idle = GRPC_CHANNEL_IDLE
connecting = GRPC_CHANNEL_CONNECTING
@@ -141,15 +141,15 @@ cdef class CallDetails:
@property
def method(self):
- return _slice_bytes(self.c_details.method)
+ return _slice_bytes(self.c_details.method)
@property
def host(self):
- return _slice_bytes(self.c_details.host)
+ return _slice_bytes(self.c_details.host)
@property
def deadline(self):
- return _time_from_timespec(self.c_details.deadline)
+ return _time_from_timespec(self.c_details.deadline)
cdef class SslPemKeyCertPair:
@@ -183,14 +183,14 @@ cdef class CompressionOptions:
return result
def to_channel_arg(self):
- return (
- GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET,
- self.c_options.enabled_algorithms_bitset,
- )
+ return (
+ GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET,
+ self.c_options.enabled_algorithms_bitset,
+ )
def compression_algorithm_name(grpc_compression_algorithm algorithm):
- cdef const char* name
+ cdef const char* name
with nogil:
grpc_compression_algorithm_name(algorithm, &name)
# Let Cython do the right thing with string casting
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pxd.pxi
index e6e79536bbe..2b06557cbb4 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pxd.pxi
@@ -1,17 +1,17 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 grpc_ssl_roots_override_result ssl_roots_override_callback(
- char **pem_root_certs) nogil
+ char **pem_root_certs) nogil
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pyx.pxi
index 9cc3fd5a211..ae24cab9df3 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pyx.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/security.pyx.pxi
@@ -1,85 +1,85 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 libc.string cimport memcpy
cdef grpc_ssl_roots_override_result ssl_roots_override_callback(
- char **pem_root_certs) nogil:
- with gil:
- temporary_pem_root_certs = ''
- pem_root_certs[0] = <char *>gpr_malloc(len(temporary_pem_root_certs) + 1)
- memcpy(
- pem_root_certs[0], <char *>temporary_pem_root_certs,
- len(temporary_pem_root_certs))
- pem_root_certs[0][len(temporary_pem_root_certs)] = '\0'
-
+ char **pem_root_certs) nogil:
+ with gil:
+ temporary_pem_root_certs = ''
+ pem_root_certs[0] = <char *>gpr_malloc(len(temporary_pem_root_certs) + 1)
+ memcpy(
+ pem_root_certs[0], <char *>temporary_pem_root_certs,
+ len(temporary_pem_root_certs))
+ pem_root_certs[0][len(temporary_pem_root_certs)] = '\0'
+
return GRPC_SSL_ROOTS_OVERRIDE_OK
-
-
-def peer_identities(Call call):
- cdef grpc_auth_context* auth_context
- cdef grpc_auth_property_iterator properties
- cdef const grpc_auth_property* property
-
- auth_context = grpc_call_auth_context(call.c_call)
- if auth_context == NULL:
- return None
- properties = grpc_auth_context_peer_identity(auth_context)
- identities = []
- while True:
- property = grpc_auth_property_iterator_next(&properties)
- if property == NULL:
- break
- if property.value != NULL:
- identities.append(<bytes>(property.value))
- grpc_auth_context_release(auth_context)
- return identities if identities else None
-
-def peer_identity_key(Call call):
- cdef grpc_auth_context* auth_context
- cdef const char* c_key
- auth_context = grpc_call_auth_context(call.c_call)
- if auth_context == NULL:
- return None
- c_key = grpc_auth_context_peer_identity_property_name(auth_context)
- if c_key == NULL:
- key = None
- else:
- key = <bytes> grpc_auth_context_peer_identity_property_name(auth_context)
- grpc_auth_context_release(auth_context)
- return key
-
-def auth_context(Call call):
- cdef grpc_auth_context* auth_context
- cdef grpc_auth_property_iterator properties
- cdef const grpc_auth_property* property
-
- auth_context = grpc_call_auth_context(call.c_call)
- if auth_context == NULL:
- return {}
- properties = grpc_auth_context_property_iterator(auth_context)
- py_auth_context = {}
- while True:
- property = grpc_auth_property_iterator_next(&properties)
- if property == NULL:
- break
- if property.name != NULL and property.value != NULL:
- key = <bytes> property.name
- if key in py_auth_context:
- py_auth_context[key].append(<bytes>(property.value))
- else:
- py_auth_context[key] = [<bytes> property.value]
- grpc_auth_context_release(auth_context)
- return py_auth_context
-
+
+
+def peer_identities(Call call):
+ cdef grpc_auth_context* auth_context
+ cdef grpc_auth_property_iterator properties
+ cdef const grpc_auth_property* property
+
+ auth_context = grpc_call_auth_context(call.c_call)
+ if auth_context == NULL:
+ return None
+ properties = grpc_auth_context_peer_identity(auth_context)
+ identities = []
+ while True:
+ property = grpc_auth_property_iterator_next(&properties)
+ if property == NULL:
+ break
+ if property.value != NULL:
+ identities.append(<bytes>(property.value))
+ grpc_auth_context_release(auth_context)
+ return identities if identities else None
+
+def peer_identity_key(Call call):
+ cdef grpc_auth_context* auth_context
+ cdef const char* c_key
+ auth_context = grpc_call_auth_context(call.c_call)
+ if auth_context == NULL:
+ return None
+ c_key = grpc_auth_context_peer_identity_property_name(auth_context)
+ if c_key == NULL:
+ key = None
+ else:
+ key = <bytes> grpc_auth_context_peer_identity_property_name(auth_context)
+ grpc_auth_context_release(auth_context)
+ return key
+
+def auth_context(Call call):
+ cdef grpc_auth_context* auth_context
+ cdef grpc_auth_property_iterator properties
+ cdef const grpc_auth_property* property
+
+ auth_context = grpc_call_auth_context(call.c_call)
+ if auth_context == NULL:
+ return {}
+ properties = grpc_auth_context_property_iterator(auth_context)
+ py_auth_context = {}
+ while True:
+ property = grpc_auth_property_iterator_next(&properties)
+ if property == NULL:
+ break
+ if property.name != NULL and property.value != NULL:
+ key = <bytes> property.name
+ if key in py_auth_context:
+ py_auth_context[key].append(<bytes>(property.value))
+ else:
+ py_auth_context[key] = [<bytes> property.value]
+ grpc_auth_context_release(auth_context)
+ return py_auth_context
+
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 b89ed99d97b..60cd48a6936 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
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 Server:
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 eff95c4f299..0c5b8fb680a 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
@@ -1,21 +1,21 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 Server:
- def __cinit__(self, object arguments):
+ def __cinit__(self, object arguments):
fork_handlers_and_grpc_init()
self.references = []
self.registered_completion_queues = []
@@ -34,15 +34,15 @@ cdef class Server:
raise ValueError("server must be started and not shutting down")
if server_queue not in self.registered_completion_queues:
raise ValueError("server_queue must be a registered completion queue")
- cdef _RequestCallTag request_call_tag = _RequestCallTag(tag)
- request_call_tag.prepare()
- cpython.Py_INCREF(request_call_tag)
- return grpc_server_request_call(
- self.c_server, &request_call_tag.call.c_call,
- &request_call_tag.call_details.c_details,
- &request_call_tag.c_invocation_metadata,
- call_queue.c_completion_queue, server_queue.c_completion_queue,
- <cpython.PyObject *>request_call_tag)
+ cdef _RequestCallTag request_call_tag = _RequestCallTag(tag)
+ request_call_tag.prepare()
+ cpython.Py_INCREF(request_call_tag)
+ return grpc_server_request_call(
+ self.c_server, &request_call_tag.call.c_call,
+ &request_call_tag.call_details.c_details,
+ &request_call_tag.c_invocation_metadata,
+ call_queue.c_completion_queue, server_queue.c_completion_queue,
+ <cpython.PyObject *>request_call_tag)
def register_completion_queue(
self, CompletionQueue queue not None):
@@ -92,12 +92,12 @@ cdef class Server:
cdef _c_shutdown(self, CompletionQueue queue, tag):
self.is_shutting_down = True
- cdef _ServerShutdownTag server_shutdown_tag = _ServerShutdownTag(tag, self)
- cpython.Py_INCREF(server_shutdown_tag)
+ cdef _ServerShutdownTag server_shutdown_tag = _ServerShutdownTag(tag, self)
+ cpython.Py_INCREF(server_shutdown_tag)
with nogil:
grpc_server_shutdown_and_notify(
self.c_server, queue.c_completion_queue,
- <cpython.PyObject *>server_shutdown_tag)
+ <cpython.PyObject *>server_shutdown_tag)
def shutdown(self, CompletionQueue queue not None, tag):
if queue.is_shutting_down:
@@ -112,8 +112,8 @@ cdef class Server:
self._c_shutdown(queue, tag)
cdef notify_shutdown_complete(self):
- # called only after our server shutdown tag has emerged from a completion
- # queue.
+ # called only after our server shutdown tag has emerged from a completion
+ # queue.
self.is_shutdown = True
def cancel_all_calls(self):
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi
index d8ba1ea9bd5..bd188d4a76e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi
@@ -1,58 +1,58 @@
-# 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.
-
-
-cdef class _Tag:
-
- cdef object event(self, grpc_event c_event)
-
-
-cdef class _ConnectivityTag(_Tag):
-
- cdef readonly object _user_tag
-
- cdef ConnectivityEvent event(self, grpc_event c_event)
-
-
-cdef class _RequestCallTag(_Tag):
-
- cdef readonly object _user_tag
- cdef Call call
- cdef CallDetails call_details
- cdef grpc_metadata_array c_invocation_metadata
-
+# 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.
+
+
+cdef class _Tag:
+
+ cdef object event(self, grpc_event c_event)
+
+
+cdef class _ConnectivityTag(_Tag):
+
+ cdef readonly object _user_tag
+
+ cdef ConnectivityEvent event(self, grpc_event c_event)
+
+
+cdef class _RequestCallTag(_Tag):
+
+ cdef readonly object _user_tag
+ cdef Call call
+ cdef CallDetails call_details
+ cdef grpc_metadata_array c_invocation_metadata
+
cdef void prepare(self) except *
- cdef RequestCallEvent event(self, grpc_event c_event)
-
-
-cdef class _BatchOperationTag(_Tag):
-
- cdef object _user_tag
- cdef readonly object _operations
- cdef readonly object _retained_call
- cdef grpc_op *c_ops
- cdef size_t c_nops
-
+ cdef RequestCallEvent event(self, grpc_event c_event)
+
+
+cdef class _BatchOperationTag(_Tag):
+
+ cdef object _user_tag
+ cdef readonly object _operations
+ cdef readonly object _retained_call
+ cdef grpc_op *c_ops
+ cdef size_t c_nops
+
cdef void prepare(self) except *
- cdef BatchOperationEvent event(self, grpc_event c_event)
-
-
-cdef class _ServerShutdownTag(_Tag):
-
- cdef readonly object _user_tag
- # This allows CompletionQueue to notify the Python Server object that the
- # underlying GRPC core server has shutdown
- cdef readonly Server _shutting_down_server
-
- cdef ServerShutdownEvent event(self, grpc_event c_event)
+ cdef BatchOperationEvent event(self, grpc_event c_event)
+
+
+cdef class _ServerShutdownTag(_Tag):
+
+ cdef readonly object _user_tag
+ # This allows CompletionQueue to notify the Python Server object that the
+ # underlying GRPC core server has shutdown
+ cdef readonly Server _shutting_down_server
+
+ cdef ServerShutdownEvent event(self, grpc_event c_event)
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 e80dc88767e..6bc74ea1471 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
@@ -1,88 +1,88 @@
-# 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.
-
-
-cdef class _Tag:
-
- cdef object event(self, grpc_event c_event):
- raise NotImplementedError()
-
-
-cdef class _ConnectivityTag(_Tag):
-
- def __cinit__(self, user_tag):
- self._user_tag = user_tag
-
- cdef ConnectivityEvent event(self, grpc_event c_event):
- return ConnectivityEvent(c_event.type, c_event.success, self._user_tag)
-
-
-cdef class _RequestCallTag(_Tag):
-
- def __cinit__(self, user_tag):
- self._user_tag = user_tag
- self.call = None
- self.call_details = None
-
+# 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.
+
+
+cdef class _Tag:
+
+ cdef object event(self, grpc_event c_event):
+ raise NotImplementedError()
+
+
+cdef class _ConnectivityTag(_Tag):
+
+ def __cinit__(self, user_tag):
+ self._user_tag = user_tag
+
+ cdef ConnectivityEvent event(self, grpc_event c_event):
+ return ConnectivityEvent(c_event.type, c_event.success, self._user_tag)
+
+
+cdef class _RequestCallTag(_Tag):
+
+ def __cinit__(self, user_tag):
+ self._user_tag = user_tag
+ self.call = None
+ self.call_details = None
+
cdef void prepare(self) except *:
- self.call = Call()
- self.call_details = CallDetails()
- grpc_metadata_array_init(&self.c_invocation_metadata)
-
- cdef RequestCallEvent event(self, grpc_event c_event):
- cdef tuple invocation_metadata = _metadata(&self.c_invocation_metadata)
- grpc_metadata_array_destroy(&self.c_invocation_metadata)
- return RequestCallEvent(
- c_event.type, c_event.success, self._user_tag, self.call,
- self.call_details, invocation_metadata)
-
-
-cdef class _BatchOperationTag:
-
- def __cinit__(self, user_tag, operations, call):
- self._user_tag = user_tag
- self._operations = operations
- self._retained_call = call
-
+ self.call = Call()
+ self.call_details = CallDetails()
+ grpc_metadata_array_init(&self.c_invocation_metadata)
+
+ cdef RequestCallEvent event(self, grpc_event c_event):
+ cdef tuple invocation_metadata = _metadata(&self.c_invocation_metadata)
+ grpc_metadata_array_destroy(&self.c_invocation_metadata)
+ return RequestCallEvent(
+ c_event.type, c_event.success, self._user_tag, self.call,
+ self.call_details, invocation_metadata)
+
+
+cdef class _BatchOperationTag:
+
+ def __cinit__(self, user_tag, operations, call):
+ self._user_tag = user_tag
+ self._operations = operations
+ self._retained_call = call
+
cdef void prepare(self) except *:
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):
+ 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
-
- cdef BatchOperationEvent event(self, grpc_event c_event):
+
+ cdef BatchOperationEvent event(self, grpc_event c_event):
cdef Operation operation
- if 0 < self.c_nops:
+ if 0 < self.c_nops:
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)
- else:
- return BatchOperationEvent(
- c_event.type, c_event.success, self._user_tag, ())
-
-
-cdef class _ServerShutdownTag(_Tag):
-
- def __cinit__(self, user_tag, shutting_down_server):
- self._user_tag = user_tag
- self._shutting_down_server = shutting_down_server
-
- cdef ServerShutdownEvent event(self, grpc_event c_event):
- self._shutting_down_server.notify_shutdown_complete()
+ gpr_free(self.c_ops)
+ return BatchOperationEvent(
+ c_event.type, c_event.success, self._user_tag, self._operations)
+ else:
+ return BatchOperationEvent(
+ c_event.type, c_event.success, self._user_tag, ())
+
+
+cdef class _ServerShutdownTag(_Tag):
+
+ def __cinit__(self, user_tag, shutting_down_server):
+ self._user_tag = user_tag
+ self._shutting_down_server = shutting_down_server
+
+ 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)
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 c46e8a98b04..b1495ac2ef4 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
@@ -1,19 +1,19 @@
-# 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.
+
+
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 6d181bb1d60..a66ca571b75 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
@@ -1,29 +1,29 @@
-# 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.
+
+
cdef gpr_timespec _timespec_from_time(object time) except *:
- if time is None:
- return gpr_inf_future(GPR_CLOCK_REALTIME)
- else:
+ 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,
)
-
-
+
+
cdef double _time_from_timespec(gpr_timespec timespec) except *:
- cdef gpr_timespec real_timespec = gpr_convert_clock_type(
- timespec, GPR_CLOCK_REALTIME)
+ cdef gpr_timespec real_timespec = gpr_convert_clock_type(
+ timespec, GPR_CLOCK_REALTIME)
return gpr_timespec_to_micros(real_timespec) / GPR_US_PER_SEC
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 166be370227..03b71c76186 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd
@@ -1,39 +1,39 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT 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++
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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++
cimport cpython
include "_cygrpc/grpc.pxi"
-include "_cygrpc/arguments.pxd.pxi"
+include "_cygrpc/arguments.pxd.pxi"
include "_cygrpc/call.pxd.pxi"
include "_cygrpc/channel.pxd.pxi"
include "_cygrpc/credentials.pxd.pxi"
include "_cygrpc/completion_queue.pxd.pxi"
-include "_cygrpc/event.pxd.pxi"
-include "_cygrpc/metadata.pxd.pxi"
-include "_cygrpc/operation.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/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/tag.pxd.pxi"
+include "_cygrpc/time.pxd.pxi"
include "_cygrpc/vtable.pxd.pxi"
include "_cygrpc/_hooks.pxd.pxi"
-
+
include "_cygrpc/iomgr.pxd.pxi"
include "_cygrpc/grpc_gevent.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 8d355c6fbbb..b3e7ebb69c5 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx
@@ -1,17 +1,17 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT 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++
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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++
cimport cpython
@@ -37,28 +37,28 @@ _LOGGER = logging.getLogger(__name__)
# TODO(atash): figure out why the coverage tool gets confused about the Cython
# coverage plugin when the following files don't have a '.pxi' suffix.
include "_cygrpc/grpc_string.pyx.pxi"
-include "_cygrpc/arguments.pyx.pxi"
+include "_cygrpc/arguments.pyx.pxi"
include "_cygrpc/call.pyx.pxi"
include "_cygrpc/channel.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/event.pyx.pxi"
+include "_cygrpc/metadata.pyx.pxi"
+include "_cygrpc/operation.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/tag.pyx.pxi"
+include "_cygrpc/time.pyx.pxi"
include "_cygrpc/vtable.pyx.pxi"
include "_cygrpc/_hooks.pyx.pxi"
include "_cygrpc/iomgr.pyx.pxi"
include "_cygrpc/grpc_gevent.pyx.pxi"
-
+
include "_cygrpc/thread.pyx.pxi"
IF UNAME_SYSNAME == "Windows":
@@ -86,14 +86,14 @@ include "_cygrpc/aio/server.pyx.pxi"
#
cdef extern from "Python.h":
- int PyEval_InitThreads()
+ int PyEval_InitThreads()
-cdef _initialize():
- # We have Python callbacks called by c-core threads, this ensures the GIL
- # is initialized.
- PyEval_InitThreads()
+cdef _initialize():
+ # We have Python callbacks called by c-core threads, this ensures the GIL
+ # is initialized.
+ PyEval_InitThreads()
import ssl
grpc_dont_init_openssl()
- # Load Arcadia certs in ComputePemRootCerts and do not override here.
+ # Load Arcadia certs in ComputePemRootCerts and do not override here.
_initialize()
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_grpcio_metadata.py b/contrib/libs/grpc/src/python/grpcio/grpc/_grpcio_metadata.py
index f5d0668407a..a7e85e57e47 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_grpcio_metadata.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_grpcio_metadata.py
@@ -1,17 +1,17 @@
-# 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.
-
-# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio/grpc/_grpcio_metadata.py.template`!!!
-
+# 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.
+
+# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio/grpc/_grpcio_metadata.py.template`!!!
+
__version__ = """1.33.2"""
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py b/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py
index ee63cb31452..43171481966 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py
@@ -1,151 +1,151 @@
-# 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.
-"""Implementation of gRPC Python interceptors."""
-
-import collections
-import sys
-
-import grpc
-
-
-class _ServicePipeline(object):
-
- def __init__(self, interceptors):
- self.interceptors = tuple(interceptors)
-
- def _continuation(self, thunk, index):
- return lambda context: self._intercept_at(thunk, index, context)
-
- def _intercept_at(self, thunk, index, context):
- if index < len(self.interceptors):
- interceptor = self.interceptors[index]
- thunk = self._continuation(thunk, index + 1)
- return interceptor.intercept_service(thunk, context)
- else:
- return thunk(context)
-
- def execute(self, thunk, context):
- return self._intercept_at(thunk, 0, context)
-
-
-def service_pipeline(interceptors):
- return _ServicePipeline(interceptors) if interceptors else None
-
-
-class _ClientCallDetails(
+# 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.
+"""Implementation of gRPC Python interceptors."""
+
+import collections
+import sys
+
+import grpc
+
+
+class _ServicePipeline(object):
+
+ def __init__(self, interceptors):
+ self.interceptors = tuple(interceptors)
+
+ def _continuation(self, thunk, index):
+ return lambda context: self._intercept_at(thunk, index, context)
+
+ def _intercept_at(self, thunk, index, context):
+ if index < len(self.interceptors):
+ interceptor = self.interceptors[index]
+ thunk = self._continuation(thunk, index + 1)
+ return interceptor.intercept_service(thunk, context)
+ else:
+ return thunk(context)
+
+ def execute(self, thunk, context):
+ return self._intercept_at(thunk, 0, context)
+
+
+def service_pipeline(interceptors):
+ return _ServicePipeline(interceptors) if interceptors else None
+
+
+class _ClientCallDetails(
collections.namedtuple('_ClientCallDetails',
('method', 'timeout', 'metadata', 'credentials',
'wait_for_ready', 'compression')),
- grpc.ClientCallDetails):
- pass
-
-
-def _unwrap_client_call_details(call_details, default_details):
- try:
- method = call_details.method
- except AttributeError:
- method = default_details.method
-
- try:
- timeout = call_details.timeout
- except AttributeError:
- timeout = default_details.timeout
-
- try:
- metadata = call_details.metadata
- except AttributeError:
- metadata = default_details.metadata
-
- try:
- credentials = call_details.credentials
- except AttributeError:
- credentials = default_details.credentials
-
+ grpc.ClientCallDetails):
+ pass
+
+
+def _unwrap_client_call_details(call_details, default_details):
+ try:
+ method = call_details.method
+ except AttributeError:
+ method = default_details.method
+
+ try:
+ timeout = call_details.timeout
+ except AttributeError:
+ timeout = default_details.timeout
+
+ try:
+ metadata = call_details.metadata
+ except AttributeError:
+ metadata = default_details.metadata
+
+ try:
+ credentials = call_details.credentials
+ except AttributeError:
+ credentials = default_details.credentials
+
try:
wait_for_ready = call_details.wait_for_ready
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
-
+
class _FailureOutcome(grpc.RpcError, grpc.Future, grpc.Call): # pylint: disable=too-many-ancestors
- def __init__(self, exception, traceback):
+ def __init__(self, exception, traceback):
super(_FailureOutcome, self).__init__()
- self._exception = exception
- self._traceback = traceback
-
- def initial_metadata(self):
- return None
-
- def trailing_metadata(self):
- return None
-
- def code(self):
- return grpc.StatusCode.INTERNAL
-
- def details(self):
- return 'Exception raised while intercepting the RPC'
-
- def cancel(self):
- return False
-
- def cancelled(self):
- return False
-
+ self._exception = exception
+ self._traceback = traceback
+
+ def initial_metadata(self):
+ return None
+
+ def trailing_metadata(self):
+ return None
+
+ def code(self):
+ return grpc.StatusCode.INTERNAL
+
+ def details(self):
+ return 'Exception raised while intercepting the RPC'
+
+ def cancel(self):
+ return False
+
+ def cancelled(self):
+ return False
+
def is_active(self):
return False
def time_remaining(self):
return None
- def running(self):
- return False
-
- def done(self):
- return True
-
- def result(self, ignored_timeout=None):
- raise self._exception
-
- def exception(self, ignored_timeout=None):
- return self._exception
-
- def traceback(self, ignored_timeout=None):
- return self._traceback
-
+ def running(self):
+ return False
+
+ def done(self):
+ return True
+
+ def result(self, ignored_timeout=None):
+ raise self._exception
+
+ def exception(self, ignored_timeout=None):
+ return self._exception
+
+ def traceback(self, ignored_timeout=None):
+ return self._traceback
+
def add_callback(self, unused_callback):
return False
- def add_done_callback(self, fn):
- fn(self)
-
- def __iter__(self):
- return self
-
+ def add_done_callback(self, fn):
+ fn(self)
+
+ def __iter__(self):
+ return self
+
def __next__(self):
- raise self._exception
-
+ raise self._exception
+
def next(self):
return self.__next__()
-
+
class _UnaryOutcome(grpc.Call, grpc.Future):
@@ -199,13 +199,13 @@ class _UnaryOutcome(grpc.Call, grpc.Future):
fn(self)
-class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
-
- def __init__(self, thunk, method, interceptor):
- self._thunk = thunk
- self._method = method
- self._interceptor = interceptor
-
+class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
+
+ def __init__(self, thunk, method, interceptor):
+ self._thunk = thunk
+ self._method = method
+ self._interceptor = interceptor
+
def __call__(self,
request,
timeout=None,
@@ -220,7 +220,7 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
wait_for_ready=wait_for_ready,
compression=compression)
return response
-
+
def _with_call(self,
request,
timeout=None,
@@ -269,7 +269,7 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
credentials=credentials,
wait_for_ready=wait_for_ready,
compression=compression)
-
+
def future(self,
request,
timeout=None,
@@ -280,34 +280,34 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
client_call_details = _ClientCallDetails(self._method, timeout,
metadata, credentials,
wait_for_ready, compression)
-
- def continuation(new_details, request):
+
+ 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))
- return self._thunk(new_method).future(
- request,
- timeout=new_timeout,
- metadata=new_metadata,
+ 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)
-
- try:
- return self._interceptor.intercept_unary_unary(
- continuation, client_call_details, request)
- except Exception as exception: # pylint:disable=broad-except
+
+ try:
+ return self._interceptor.intercept_unary_unary(
+ continuation, client_call_details, request)
+ except Exception as exception: # pylint:disable=broad-except
return _FailureOutcome(exception, sys.exc_info()[2])
-
-
-class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
-
- def __init__(self, thunk, method, interceptor):
- self._thunk = thunk
- self._method = method
- self._interceptor = interceptor
-
+
+
+class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
+
+ def __init__(self, thunk, method, interceptor):
+ self._thunk = thunk
+ self._method = method
+ self._interceptor = interceptor
+
def __call__(self,
request,
timeout=None,
@@ -318,8 +318,8 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
client_call_details = _ClientCallDetails(self._method, timeout,
metadata, credentials,
wait_for_ready, compression)
-
- def continuation(new_details, request):
+
+ def continuation(new_details, request):
(new_method, new_timeout, new_metadata, new_credentials,
new_wait_for_ready,
new_compression) = (_unwrap_client_call_details(
@@ -330,25 +330,25 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
credentials=new_credentials,
wait_for_ready=new_wait_for_ready,
compression=new_compression)
-
- try:
- return self._interceptor.intercept_unary_stream(
- continuation, client_call_details, request)
- except Exception as exception: # pylint:disable=broad-except
+
+ try:
+ return self._interceptor.intercept_unary_stream(
+ continuation, client_call_details, request)
+ except Exception as exception: # pylint:disable=broad-except
return _FailureOutcome(exception, sys.exc_info()[2])
-
-
-class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
-
- def __init__(self, thunk, method, interceptor):
- self._thunk = thunk
- self._method = method
- self._interceptor = interceptor
-
- def __call__(self,
- request_iterator,
- timeout=None,
- metadata=None,
+
+
+class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
+
+ def __init__(self, thunk, method, interceptor):
+ self._thunk = thunk
+ self._method = method
+ self._interceptor = interceptor
+
+ def __call__(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
credentials=None,
wait_for_ready=None,
compression=None):
@@ -359,7 +359,7 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
wait_for_ready=wait_for_ready,
compression=compression)
return response
-
+
def _with_call(self,
request_iterator,
timeout=None,
@@ -395,10 +395,10 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
request_iterator)
return call.result(), call
- def with_call(self,
- request_iterator,
- timeout=None,
- metadata=None,
+ def with_call(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
credentials=None,
wait_for_ready=None,
compression=None):
@@ -408,57 +408,57 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
credentials=credentials,
wait_for_ready=wait_for_ready,
compression=compression)
-
- def future(self,
- request_iterator,
- timeout=None,
- metadata=None,
+
+ def future(self,
+ request_iterator,
+ 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)
-
- def continuation(new_details, request_iterator):
+
+ 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))
- return self._thunk(new_method).future(
- request_iterator,
- timeout=new_timeout,
- metadata=new_metadata,
+ 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)
-
- try:
- return self._interceptor.intercept_stream_unary(
- continuation, client_call_details, request_iterator)
- except Exception as exception: # pylint:disable=broad-except
+
+ try:
+ return self._interceptor.intercept_stream_unary(
+ continuation, client_call_details, request_iterator)
+ except Exception as exception: # pylint:disable=broad-except
return _FailureOutcome(exception, sys.exc_info()[2])
-
-
-class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
-
- def __init__(self, thunk, method, interceptor):
- self._thunk = thunk
- self._method = method
- self._interceptor = interceptor
-
- def __call__(self,
- request_iterator,
- timeout=None,
- metadata=None,
+
+
+class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
+
+ def __init__(self, thunk, method, interceptor):
+ self._thunk = thunk
+ self._method = method
+ self._interceptor = interceptor
+
+ def __call__(self,
+ request_iterator,
+ 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)
-
- def continuation(new_details, request_iterator):
+
+ def continuation(new_details, request_iterator):
(new_method, new_timeout, new_metadata, new_credentials,
new_wait_for_ready,
new_compression) = (_unwrap_client_call_details(
@@ -469,94 +469,94 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
credentials=new_credentials,
wait_for_ready=new_wait_for_ready,
compression=new_compression)
-
- try:
- return self._interceptor.intercept_stream_stream(
- continuation, client_call_details, request_iterator)
- except Exception as exception: # pylint:disable=broad-except
+
+ try:
+ return self._interceptor.intercept_stream_stream(
+ continuation, client_call_details, request_iterator)
+ except Exception as exception: # pylint:disable=broad-except
return _FailureOutcome(exception, sys.exc_info()[2])
-
-
-class _Channel(grpc.Channel):
-
- def __init__(self, channel, interceptor):
- self._channel = channel
- self._interceptor = interceptor
-
+
+
+class _Channel(grpc.Channel):
+
+ def __init__(self, channel, interceptor):
+ self._channel = channel
+ self._interceptor = interceptor
+
def subscribe(self, callback, try_to_connect=False):
self._channel.subscribe(callback, try_to_connect=try_to_connect)
-
+
def unsubscribe(self, callback):
self._channel.unsubscribe(callback)
-
- def unary_unary(self,
- method,
- request_serializer=None,
- response_deserializer=None):
+
+ def unary_unary(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
thunk = lambda m: self._channel.unary_unary(m, request_serializer,
response_deserializer)
- if isinstance(self._interceptor, grpc.UnaryUnaryClientInterceptor):
- return _UnaryUnaryMultiCallable(thunk, method, self._interceptor)
- else:
- return thunk(method)
-
- def unary_stream(self,
- method,
- request_serializer=None,
- response_deserializer=None):
+ if isinstance(self._interceptor, grpc.UnaryUnaryClientInterceptor):
+ return _UnaryUnaryMultiCallable(thunk, method, self._interceptor)
+ else:
+ return thunk(method)
+
+ def unary_stream(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
thunk = lambda m: self._channel.unary_stream(m, request_serializer,
response_deserializer)
- if isinstance(self._interceptor, grpc.UnaryStreamClientInterceptor):
- return _UnaryStreamMultiCallable(thunk, method, self._interceptor)
- else:
- return thunk(method)
-
- def stream_unary(self,
- method,
- request_serializer=None,
- response_deserializer=None):
+ if isinstance(self._interceptor, grpc.UnaryStreamClientInterceptor):
+ return _UnaryStreamMultiCallable(thunk, method, self._interceptor)
+ else:
+ return thunk(method)
+
+ def stream_unary(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
thunk = lambda m: self._channel.stream_unary(m, request_serializer,
response_deserializer)
- if isinstance(self._interceptor, grpc.StreamUnaryClientInterceptor):
- return _StreamUnaryMultiCallable(thunk, method, self._interceptor)
- else:
- return thunk(method)
-
- def stream_stream(self,
- method,
- request_serializer=None,
- response_deserializer=None):
+ if isinstance(self._interceptor, grpc.StreamUnaryClientInterceptor):
+ return _StreamUnaryMultiCallable(thunk, method, self._interceptor)
+ else:
+ return thunk(method)
+
+ def stream_stream(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
thunk = lambda m: self._channel.stream_stream(m, request_serializer,
response_deserializer)
- if isinstance(self._interceptor, grpc.StreamStreamClientInterceptor):
- return _StreamStreamMultiCallable(thunk, method, self._interceptor)
- else:
- return thunk(method)
-
- def _close(self):
- self._channel.close()
-
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- self._close()
- return False
-
- def close(self):
- self._channel.close()
-
-
-def intercept_channel(channel, *interceptors):
- for interceptor in reversed(list(interceptors)):
- if not isinstance(interceptor, grpc.UnaryUnaryClientInterceptor) and \
- not isinstance(interceptor, grpc.UnaryStreamClientInterceptor) and \
- not isinstance(interceptor, grpc.StreamUnaryClientInterceptor) and \
- not isinstance(interceptor, grpc.StreamStreamClientInterceptor):
- raise TypeError('interceptor must be '
- 'grpc.UnaryUnaryClientInterceptor or '
- 'grpc.UnaryStreamClientInterceptor or '
- 'grpc.StreamUnaryClientInterceptor or '
- 'grpc.StreamStreamClientInterceptor or ')
- channel = _Channel(channel, interceptor)
- return channel
+ if isinstance(self._interceptor, grpc.StreamStreamClientInterceptor):
+ return _StreamStreamMultiCallable(thunk, method, self._interceptor)
+ else:
+ return thunk(method)
+
+ def _close(self):
+ self._channel.close()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self._close()
+ return False
+
+ def close(self):
+ self._channel.close()
+
+
+def intercept_channel(channel, *interceptors):
+ for interceptor in reversed(list(interceptors)):
+ if not isinstance(interceptor, grpc.UnaryUnaryClientInterceptor) and \
+ not isinstance(interceptor, grpc.UnaryStreamClientInterceptor) and \
+ not isinstance(interceptor, grpc.StreamUnaryClientInterceptor) and \
+ not isinstance(interceptor, grpc.StreamStreamClientInterceptor):
+ raise TypeError('interceptor must be '
+ 'grpc.UnaryUnaryClientInterceptor or '
+ 'grpc.UnaryStreamClientInterceptor or '
+ 'grpc.StreamUnaryClientInterceptor or '
+ 'grpc.StreamStreamClientInterceptor or ')
+ channel = _Channel(channel, interceptor)
+ return channel
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py b/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py
index e3bfa909169..9be507027fc 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py
@@ -1,19 +1,19 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 collections
-import logging
+import logging
import threading
import grpc
@@ -23,79 +23,79 @@ from grpc._cython import cygrpc
_LOGGER = logging.getLogger(__name__)
-class _AuthMetadataContext(
+class _AuthMetadataContext(
collections.namedtuple('AuthMetadataContext', (
- 'service_url',
- 'method_name',
- )), grpc.AuthMetadataContext):
+ 'service_url',
+ 'method_name',
+ )), grpc.AuthMetadataContext):
pass
-class _CallbackState(object):
+class _CallbackState(object):
- def __init__(self):
- self.lock = threading.Lock()
- self.called = False
- self.exception = None
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.called = False
+ self.exception = None
-class _AuthMetadataPluginCallback(grpc.AuthMetadataPluginCallback):
+class _AuthMetadataPluginCallback(grpc.AuthMetadataPluginCallback):
- def __init__(self, state, callback):
- self._state = state
- self._callback = callback
+ def __init__(self, state, callback):
+ self._state = state
+ self._callback = callback
def __call__(self, metadata, error):
- with self._state.lock:
- if self._state.exception is None:
- if self._state.called:
- raise RuntimeError(
- 'AuthMetadataPluginCallback invoked more than once!')
- else:
- self._state.called = True
- else:
- raise RuntimeError(
- 'AuthMetadataPluginCallback raised exception "{}"!'.format(
- self._state.exception))
+ with self._state.lock:
+ if self._state.exception is None:
+ if self._state.called:
+ raise RuntimeError(
+ 'AuthMetadataPluginCallback invoked more than once!')
+ else:
+ self._state.called = True
+ else:
+ raise RuntimeError(
+ 'AuthMetadataPluginCallback raised exception "{}"!'.format(
+ self._state.exception))
if error is None:
- self._callback(metadata, cygrpc.StatusCode.ok, None)
+ self._callback(metadata, cygrpc.StatusCode.ok, None)
else:
- self._callback(None, cygrpc.StatusCode.internal,
- _common.encode(str(error)))
+ self._callback(None, cygrpc.StatusCode.internal,
+ _common.encode(str(error)))
-class _Plugin(object):
+class _Plugin(object):
- def __init__(self, metadata_plugin):
- self._metadata_plugin = metadata_plugin
+ def __init__(self, metadata_plugin):
+ self._metadata_plugin = metadata_plugin
- def __call__(self, service_url, method_name, callback):
+ def __call__(self, service_url, method_name, callback):
context = _AuthMetadataContext(_common.decode(service_url),
_common.decode(method_name))
- callback_state = _CallbackState()
+ callback_state = _CallbackState()
try:
self._metadata_plugin(
context, _AuthMetadataPluginCallback(callback_state, callback))
- except Exception as exception: # pylint: disable=broad-except
+ except Exception as exception: # pylint: disable=broad-except
_LOGGER.exception(
- 'AuthMetadataPluginCallback "%s" raised exception!',
- self._metadata_plugin)
- with callback_state.lock:
- callback_state.exception = exception
- if callback_state.called:
- return
- callback(None, cygrpc.StatusCode.internal,
- _common.encode(str(exception)))
-
-
-def metadata_plugin_call_credentials(metadata_plugin, name):
- if name is None:
- try:
- effective_name = metadata_plugin.__name__
- except AttributeError:
- effective_name = metadata_plugin.__class__.__name__
- else:
- effective_name = name
- return grpc.CallCredentials(
+ 'AuthMetadataPluginCallback "%s" raised exception!',
+ self._metadata_plugin)
+ with callback_state.lock:
+ callback_state.exception = exception
+ if callback_state.called:
+ return
+ callback(None, cygrpc.StatusCode.internal,
+ _common.encode(str(exception)))
+
+
+def metadata_plugin_call_credentials(metadata_plugin, name):
+ if name is None:
+ try:
+ effective_name = metadata_plugin.__name__
+ except AttributeError:
+ effective_name = metadata_plugin.__class__.__name__
+ else:
+ effective_name = name
+ return grpc.CallCredentials(
cygrpc.MetadataPluginCallCredentials(_Plugin(metadata_plugin),
_common.encode(effective_name)))
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_server.py b/contrib/libs/grpc/src/python/grpcio/grpc/_server.py
index 48ff7439951..8a0cddbeed1 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_server.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_server.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Service-side implementation of gRPC Python."""
import collections
@@ -20,12 +20,12 @@ import threading
import time
from concurrent import futures
-import six
-
+import six
+
import grpc
from grpc import _common
from grpc import _compression
-from grpc import _interceptor
+from grpc import _interceptor
from grpc._cython import cygrpc
_LOGGER = logging.getLogger(__name__)
@@ -54,7 +54,7 @@ _INF_TIMEOUT = 1e9
def _serialized_request(request_event):
- return request_event.batch_operations[0].message()
+ return request_event.batch_operations[0].message()
def _application_code(code):
@@ -82,9 +82,9 @@ def _details(state):
class _HandlerCallDetails(
collections.namedtuple('_HandlerCallDetails', (
- 'method',
- 'invocation_metadata',
- )), grpc.HandlerCallDetails):
+ 'method',
+ 'invocation_metadata',
+ )), grpc.HandlerCallDetails):
pass
@@ -157,21 +157,21 @@ def _abort(state, call, code, details):
effective_code = _abortion_code(state, code)
effective_details = details if state.details is None else state.details
if state.initial_metadata_allowed:
- operations = (
+ operations = (
_get_initial_metadata_operation(state, None),
cygrpc.SendStatusFromServerOperation(state.trailing_metadata,
effective_code,
effective_details,
_EMPTY_FLAGS),
- )
+ )
token = _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN
else:
- operations = (cygrpc.SendStatusFromServerOperation(
- state.trailing_metadata, effective_code, effective_details,
- _EMPTY_FLAGS),)
+ operations = (cygrpc.SendStatusFromServerOperation(
+ state.trailing_metadata, effective_code, effective_details,
+ _EMPTY_FLAGS),)
token = _SEND_STATUS_FROM_SERVER_TOKEN
- call.start_server_batch(operations,
- _send_status_from_server(state, token))
+ call.start_server_batch(operations,
+ _send_status_from_server(state, token))
state.statused = True
state.due.add(token)
@@ -180,7 +180,7 @@ def _receive_close_on_server(state):
def receive_close_on_server(receive_close_on_server_event):
with state.condition:
- if receive_close_on_server_event.batch_operations[0].cancelled():
+ if receive_close_on_server_event.batch_operations[0].cancelled():
state.client = _CANCELLED
elif state.client is _OPEN:
state.client = _CLOSED
@@ -246,10 +246,10 @@ class _Context(grpc.ServicerContext):
return _is_rpc_state_active(self._state)
def time_remaining(self):
- return max(self._rpc_event.call_details.deadline - time.time(), 0)
+ return max(self._rpc_event.call_details.deadline - time.time(), 0)
def cancel(self):
- self._rpc_event.call.cancel()
+ self._rpc_event.call.cancel()
def add_callback(self, callback):
with self._state.condition:
@@ -264,24 +264,24 @@ class _Context(grpc.ServicerContext):
self._state.disable_next_compression = True
def invocation_metadata(self):
- return self._rpc_event.invocation_metadata
+ return self._rpc_event.invocation_metadata
def peer(self):
- return _common.decode(self._rpc_event.call.peer())
-
- def peer_identities(self):
- return cygrpc.peer_identities(self._rpc_event.call)
-
- def peer_identity_key(self):
- id_key = cygrpc.peer_identity_key(self._rpc_event.call)
- return id_key if id_key is None else _common.decode(id_key)
-
- def auth_context(self):
- return {
+ return _common.decode(self._rpc_event.call.peer())
+
+ def peer_identities(self):
+ return cygrpc.peer_identities(self._rpc_event.call)
+
+ def peer_identity_key(self):
+ id_key = cygrpc.peer_identity_key(self._rpc_event.call)
+ return id_key if id_key is None else _common.decode(id_key)
+
+ def auth_context(self):
+ return {
_common.decode(key): value for key, value in six.iteritems(
- cygrpc.auth_context(self._rpc_event.call))
- }
-
+ cygrpc.auth_context(self._rpc_event.call))
+ }
+
def set_compression(self, compression):
with self._state.condition:
self._state.compression_algorithm = compression
@@ -294,8 +294,8 @@ class _Context(grpc.ServicerContext):
if self._state.initial_metadata_allowed:
operation = _get_initial_metadata_operation(
self._state, initial_metadata)
- self._rpc_event.call.start_server_batch(
- (operation,), _send_initial_metadata(self._state))
+ self._rpc_event.call.start_server_batch(
+ (operation,), _send_initial_metadata(self._state))
self._state.initial_metadata_allowed = False
self._state.due.add(_SEND_INITIAL_METADATA_TOKEN)
else:
@@ -303,21 +303,21 @@ class _Context(grpc.ServicerContext):
def set_trailing_metadata(self, trailing_metadata):
with self._state.condition:
- self._state.trailing_metadata = trailing_metadata
+ self._state.trailing_metadata = trailing_metadata
- def abort(self, code, details):
- # treat OK like other invalid arguments: fail the RPC
- if code == grpc.StatusCode.OK:
+ def abort(self, code, details):
+ # treat OK like other invalid arguments: fail the RPC
+ if code == grpc.StatusCode.OK:
_LOGGER.error(
- 'abort() called with StatusCode.OK; returning UNKNOWN')
- code = grpc.StatusCode.UNKNOWN
- details = ''
- with self._state.condition:
- self._state.code = code
- self._state.details = _common.encode(details)
+ 'abort() called with StatusCode.OK; returning UNKNOWN')
+ code = grpc.StatusCode.UNKNOWN
+ details = ''
+ with self._state.condition:
+ self._state.code = code
+ self._state.details = _common.encode(details)
self._state.aborted = True
raise Exception()
-
+
def abort_with_status(self, status):
self._state.trailing_metadata = status.trailing_metadata
self.abort(status.code, status.details)
@@ -348,7 +348,7 @@ class _RequestIterator(object):
raise StopIteration()
else:
self._call.start_server_batch(
- (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
_receive_message(self._state, self._call,
self._request_deserializer))
self._state.due.add(_RECEIVE_MESSAGE_TOKEN)
@@ -392,9 +392,9 @@ def _unary_request(rpc_event, state, request_deserializer):
if not _is_rpc_state_active(state):
return None
else:
- rpc_event.call.start_server_batch(
- (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
- _receive_message(state, rpc_event.call,
+ rpc_event.call.start_server_batch(
+ (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
+ _receive_message(state, rpc_event.call,
request_deserializer))
state.due.add(_RECEIVE_MESSAGE_TOKEN)
while True:
@@ -402,8 +402,8 @@ def _unary_request(rpc_event, state, request_deserializer):
if state.request is None:
if state.client is _CLOSED:
details = '"{}" requires exactly one request message.'.format(
- rpc_event.call_details.method)
- _abort(state, rpc_event.call,
+ rpc_event.call_details.method)
+ _abort(state, rpc_event.call,
cygrpc.StatusCode.unimplemented,
_common.encode(details))
return None
@@ -453,16 +453,16 @@ def _take_response_from_response_iterator(rpc_event, state, response_iterator):
return next(response_iterator), True
except StopIteration:
return None, True
- except Exception as exception: # pylint: disable=broad-except
+ 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 iterating responses: {}'.format(exception)
+ _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
+ b'RPC Aborted')
+ elif exception not in state.rpc_errors:
+ details = 'Exception iterating responses: {}'.format(exception)
_LOGGER.exception(details)
- _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
- _common.encode(details))
+ _abort(state, rpc_event.call, cygrpc.StatusCode.unknown,
+ _common.encode(details))
return None, False
@@ -470,7 +470,7 @@ def _serialize_response(rpc_event, state, response, response_serializer):
serialized_response = _common.serialize(response, response_serializer)
if serialized_response is None:
with state.condition:
- _abort(state, rpc_event.call, cygrpc.StatusCode.internal,
+ _abort(state, rpc_event.call, cygrpc.StatusCode.internal,
b'Failed to serialize response!')
return None
else:
@@ -495,21 +495,21 @@ def _send_response(rpc_event, state, serialized_response):
return False
else:
if state.initial_metadata_allowed:
- operations = (
+ operations = (
_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(
+ operations = (cygrpc.SendMessageOperation(
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))
+ rpc_event.call.start_server_batch(operations,
+ _send_message(state, token))
state.due.add(token)
_reset_per_message_state(state)
while True:
@@ -535,8 +535,8 @@ def _status(rpc_event, state, serialized_response):
cygrpc.SendMessageOperation(
serialized_response,
_get_send_message_op_flags_from_state(state)))
- rpc_event.call.start_server_batch(
- operations,
+ 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)
@@ -626,10 +626,10 @@ def _handle_unary_unary(rpc_event, state, method_handler, default_thread_pool):
method_handler.request_deserializer)
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)
+ 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):
@@ -637,14 +637,14 @@ def _handle_unary_stream(rpc_event, state, method_handler, default_thread_pool):
method_handler.request_deserializer)
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)
+ 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):
- request_iterator = _RequestIterator(state, rpc_event.call,
+ 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)
@@ -657,7 +657,7 @@ def _handle_stream_unary(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,
+ 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)
@@ -668,34 +668,34 @@ def _handle_stream_stream(rpc_event, state, method_handler,
method_handler.response_serializer)
-def _find_method_handler(rpc_event, generic_handlers, interceptor_pipeline):
-
- def query_handlers(handler_call_details):
- for generic_handler in generic_handlers:
- method_handler = generic_handler.service(handler_call_details)
- if method_handler is not None:
- return method_handler
+def _find_method_handler(rpc_event, generic_handlers, interceptor_pipeline):
+
+ def query_handlers(handler_call_details):
+ for generic_handler in generic_handlers:
+ method_handler = generic_handler.service(handler_call_details)
+ if method_handler is not None:
+ return method_handler
return None
- handler_call_details = _HandlerCallDetails(
- _common.decode(rpc_event.call_details.method),
- rpc_event.invocation_metadata)
-
- if interceptor_pipeline is not None:
- return interceptor_pipeline.execute(query_handlers,
- handler_call_details)
- else:
- return query_handlers(handler_call_details)
-
-
-def _reject_rpc(rpc_event, status, details):
+ handler_call_details = _HandlerCallDetails(
+ _common.decode(rpc_event.call_details.method),
+ rpc_event.invocation_metadata)
+
+ if interceptor_pipeline is not None:
+ return interceptor_pipeline.execute(query_handlers,
+ handler_call_details)
+ else:
+ return query_handlers(handler_call_details)
+
+
+def _reject_rpc(rpc_event, status, details):
rpc_state = _RPCState()
operations = (
_get_initial_metadata_operation(rpc_state, None),
- cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(None, status, details,
- _EMPTY_FLAGS),
- )
+ cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
+ cygrpc.SendStatusFromServerOperation(None, status, details,
+ _EMPTY_FLAGS),
+ )
rpc_event.call.start_server_batch(operations, lambda ignored_event: (
rpc_state,
(),
@@ -706,50 +706,50 @@ def _reject_rpc(rpc_event, status, details):
def _handle_with_method_handler(rpc_event, method_handler, thread_pool):
state = _RPCState()
with state.condition:
- rpc_event.call.start_server_batch(
- (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
+ rpc_event.call.start_server_batch(
+ (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
_receive_close_on_server(state))
state.due.add(_RECEIVE_CLOSE_ON_SERVER_TOKEN)
if method_handler.request_streaming:
if method_handler.response_streaming:
- return state, _handle_stream_stream(rpc_event, state,
- method_handler, thread_pool)
+ return state, _handle_stream_stream(rpc_event, state,
+ method_handler, thread_pool)
else:
- return state, _handle_stream_unary(rpc_event, state,
- method_handler, thread_pool)
+ return state, _handle_stream_unary(rpc_event, state,
+ method_handler, thread_pool)
else:
if method_handler.response_streaming:
- return state, _handle_unary_stream(rpc_event, state,
- method_handler, thread_pool)
+ return state, _handle_unary_stream(rpc_event, state,
+ method_handler, thread_pool)
else:
- return state, _handle_unary_unary(rpc_event, state,
- method_handler, thread_pool)
-
-
-def _handle_call(rpc_event, generic_handlers, interceptor_pipeline, thread_pool,
- concurrency_exceeded):
- if not rpc_event.success:
- return None, None
- if rpc_event.call_details.method is not None:
- try:
- method_handler = _find_method_handler(rpc_event, generic_handlers,
- interceptor_pipeline)
- except Exception as exception: # pylint: disable=broad-except
- details = 'Exception servicing handler: {}'.format(exception)
+ return state, _handle_unary_unary(rpc_event, state,
+ method_handler, thread_pool)
+
+
+def _handle_call(rpc_event, generic_handlers, interceptor_pipeline, thread_pool,
+ concurrency_exceeded):
+ if not rpc_event.success:
+ return None, None
+ if rpc_event.call_details.method is not None:
+ try:
+ method_handler = _find_method_handler(rpc_event, generic_handlers,
+ interceptor_pipeline)
+ except Exception as exception: # pylint: disable=broad-except
+ details = 'Exception servicing handler: {}'.format(exception)
_LOGGER.exception(details)
- return _reject_rpc(rpc_event, cygrpc.StatusCode.unknown,
- b'Error in service handler!'), None
+ return _reject_rpc(rpc_event, cygrpc.StatusCode.unknown,
+ b'Error in service handler!'), None
if method_handler is None:
- return _reject_rpc(rpc_event, cygrpc.StatusCode.unimplemented,
- b'Method not found!'), None
- elif concurrency_exceeded:
- return _reject_rpc(rpc_event, cygrpc.StatusCode.resource_exhausted,
- b'Concurrent RPC limit exceeded!'), None
+ return _reject_rpc(rpc_event, cygrpc.StatusCode.unimplemented,
+ b'Method not found!'), None
+ elif concurrency_exceeded:
+ return _reject_rpc(rpc_event, cygrpc.StatusCode.resource_exhausted,
+ b'Concurrent RPC limit exceeded!'), None
else:
return _handle_with_method_handler(rpc_event, method_handler,
thread_pool)
else:
- return None, None
+ return None, None
@enum.unique
@@ -761,20 +761,20 @@ class _ServerStage(enum.Enum):
class _ServerState(object):
- # pylint: disable=too-many-arguments
- def __init__(self, completion_queue, server, generic_handlers,
- interceptor_pipeline, thread_pool, maximum_concurrent_rpcs):
- self.lock = threading.RLock()
+ # pylint: disable=too-many-arguments
+ def __init__(self, completion_queue, server, generic_handlers,
+ interceptor_pipeline, thread_pool, maximum_concurrent_rpcs):
+ self.lock = threading.RLock()
self.completion_queue = completion_queue
self.server = server
self.generic_handlers = list(generic_handlers)
- self.interceptor_pipeline = interceptor_pipeline
+ 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.maximum_concurrent_rpcs = maximum_concurrent_rpcs
- self.active_rpc_count = 0
+ self.maximum_concurrent_rpcs = maximum_concurrent_rpcs
+ self.active_rpc_count = 0
# TODO(https://github.com/grpc/grpc/issues/6597): eliminate these fields.
self.rpc_states = set()
@@ -818,11 +818,11 @@ def _stop_serving(state):
return False
-def _on_call_completed(state):
- with state.lock:
- state.active_rpc_count -= 1
-
-
+def _on_call_completed(state):
+ with state.lock:
+ state.active_rpc_count -= 1
+
+
def _process_event_and_continue(state, event):
should_continue = True
if event.tag is _SHUTDOWN_TAG:
@@ -874,10 +874,10 @@ def _serve(state):
if event.completion_type != cygrpc.CompletionType.queue_timeout:
if not _process_event_and_continue(state, event):
return
- # We want to force the deletion of the previous event
- # ~before~ we poll again; if the event has a reference
- # to a shutdown Call object, this can induce spinlock.
- event = None
+ # We want to force the deletion of the previous event
+ # ~before~ we poll again; if the event has a reference
+ # to a shutdown Call object, this can induce spinlock.
+ event = None
def _begin_shutdown_once(state):
@@ -943,15 +943,15 @@ def _augment_options(base_options, compression):
class _Server(grpc.Server):
- # pylint: disable=too-many-arguments
- def __init__(self, thread_pool, generic_handlers, interceptors, options,
+ # pylint: disable=too-many-arguments
+ def __init__(self, thread_pool, generic_handlers, interceptors, options,
maximum_concurrent_rpcs, compression):
completion_queue = cygrpc.CompletionQueue()
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),
- thread_pool, maximum_concurrent_rpcs)
+ _interceptor.service_pipeline(interceptors),
+ thread_pool, maximum_concurrent_rpcs)
def add_generic_rpc_handlers(self, generic_rpc_handlers):
_validate_generic_rpc_handlers(generic_rpc_handlers)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py b/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py
index c48aaf60a2f..67789382d29 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Internal utilities for gRPC Python."""
import collections
@@ -31,15 +31,15 @@ _DONE_CALLBACK_EXCEPTION_LOG_MESSAGE = (
class RpcMethodHandler(
collections.namedtuple('_RpcMethodHandler', (
- 'request_streaming',
- 'response_streaming',
- 'request_deserializer',
- 'response_serializer',
- 'unary_unary',
- 'unary_stream',
- 'stream_unary',
- 'stream_stream',
- )), grpc.RpcMethodHandler):
+ 'request_streaming',
+ 'response_streaming',
+ 'request_deserializer',
+ 'response_serializer',
+ 'unary_unary',
+ 'unary_stream',
+ 'stream_unary',
+ 'stream_stream',
+ )), grpc.RpcMethodHandler):
pass
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/beta/_client_adaptations.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_client_adaptations.py
index 652ae0ea171..fb2925b413e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/_client_adaptations.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_client_adaptations.py
@@ -1,28 +1,28 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Translates gRPC's client-side API into gRPC's client-side Beta API."""
import grpc
from grpc import _common
-from grpc.beta import _metadata
+from grpc.beta import _metadata
from grpc.beta import interfaces
from grpc.framework.common import cardinality
from grpc.framework.foundation import future
from grpc.framework.interfaces.face import face
-# pylint: disable=too-many-arguments,too-many-locals,unused-argument
-
+# pylint: disable=too-many-arguments,too-many-locals,unused-argument
+
_STATUS_CODE_TO_ABORTION_KIND_AND_ABORTION_ERROR_CLASS = {
grpc.StatusCode.CANCELLED:
(face.Abortion.Kind.CANCELLED, face.CancellationError),
@@ -51,7 +51,7 @@ def _abortion(rpc_error_call):
code = rpc_error_call.code()
pair = _STATUS_CODE_TO_ABORTION_KIND_AND_ABORTION_ERROR_CLASS.get(code)
error_kind = face.Abortion.Kind.LOCAL_FAILURE if pair is None else pair[0]
- return face.Abortion(error_kind, rpc_error_call.initial_metadata(),
+ return face.Abortion(error_kind, rpc_error_call.initial_metadata(),
rpc_error_call.trailing_metadata(), code,
rpc_error_call.details())
@@ -157,10 +157,10 @@ class _Rendezvous(future.Future, face.Call):
return _InvocationProtocolContext()
def initial_metadata(self):
- return _metadata.beta(self._call.initial_metadata())
+ return _metadata.beta(self._call.initial_metadata())
def terminal_metadata(self):
- return _metadata.beta(self._call.terminal_metadata())
+ return _metadata.beta(self._call.terminal_metadata())
def code(self):
return self._call.code()
@@ -182,7 +182,7 @@ def _blocking_unary_unary(channel, group, method, timeout, with_call,
response, call = multi_callable.with_call(
request,
timeout=timeout,
- metadata=_metadata.unbeta(effective_metadata),
+ metadata=_metadata.unbeta(effective_metadata),
credentials=_credentials(protocol_options))
return response, _Rendezvous(None, None, call)
else:
@@ -205,7 +205,7 @@ def _future_unary_unary(channel, group, method, timeout, protocol_options,
response_future = multi_callable.future(
request,
timeout=timeout,
- metadata=_metadata.unbeta(effective_metadata),
+ metadata=_metadata.unbeta(effective_metadata),
credentials=_credentials(protocol_options))
return _Rendezvous(response_future, None, response_future)
@@ -221,7 +221,7 @@ def _unary_stream(channel, group, method, timeout, protocol_options, metadata,
response_iterator = multi_callable(
request,
timeout=timeout,
- metadata=_metadata.unbeta(effective_metadata),
+ metadata=_metadata.unbeta(effective_metadata),
credentials=_credentials(protocol_options))
return _Rendezvous(None, response_iterator, response_iterator)
@@ -240,7 +240,7 @@ def _blocking_stream_unary(channel, group, method, timeout, with_call,
response, call = multi_callable.with_call(
request_iterator,
timeout=timeout,
- metadata=_metadata.unbeta(effective_metadata),
+ metadata=_metadata.unbeta(effective_metadata),
credentials=_credentials(protocol_options))
return response, _Rendezvous(None, None, call)
else:
@@ -263,7 +263,7 @@ def _future_stream_unary(channel, group, method, timeout, protocol_options,
response_future = multi_callable.future(
request_iterator,
timeout=timeout,
- metadata=_metadata.unbeta(effective_metadata),
+ metadata=_metadata.unbeta(effective_metadata),
credentials=_credentials(protocol_options))
return _Rendezvous(response_future, None, response_future)
@@ -279,7 +279,7 @@ def _stream_stream(channel, group, method, timeout, protocol_options, metadata,
response_iterator = multi_callable(
request_iterator,
timeout=timeout,
- metadata=_metadata.unbeta(effective_metadata),
+ metadata=_metadata.unbeta(effective_metadata),
credentials=_credentials(protocol_options))
return _Rendezvous(None, response_iterator, response_iterator)
@@ -444,14 +444,14 @@ class _GenericStub(face.GenericStub):
metadata=None,
with_call=None,
protocol_options=None):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _blocking_unary_unary(self._channel, group, method, timeout,
with_call, protocol_options, metadata,
self._metadata_transformer, request,
@@ -464,14 +464,14 @@ class _GenericStub(face.GenericStub):
timeout,
metadata=None,
protocol_options=None):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _future_unary_unary(self._channel, group, method, timeout,
protocol_options, metadata,
self._metadata_transformer, request,
@@ -484,14 +484,14 @@ class _GenericStub(face.GenericStub):
timeout,
metadata=None,
protocol_options=None):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _unary_stream(self._channel, group, method, timeout,
protocol_options, metadata,
self._metadata_transformer, request,
@@ -505,14 +505,14 @@ class _GenericStub(face.GenericStub):
metadata=None,
with_call=None,
protocol_options=None):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _blocking_stream_unary(self._channel, group, method, timeout,
with_call, protocol_options, metadata,
self._metadata_transformer,
@@ -526,14 +526,14 @@ class _GenericStub(face.GenericStub):
timeout,
metadata=None,
protocol_options=None):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _future_stream_unary(self._channel, group, method, timeout,
protocol_options, metadata,
self._metadata_transformer,
@@ -547,14 +547,14 @@ class _GenericStub(face.GenericStub):
timeout,
metadata=None,
protocol_options=None):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _stream_stream(self._channel, group, method, timeout,
protocol_options, metadata,
self._metadata_transformer, request_iterator,
@@ -603,56 +603,56 @@ class _GenericStub(face.GenericStub):
raise NotImplementedError()
def unary_unary(self, group, method):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _UnaryUnaryMultiCallable(self._channel, group, method,
self._metadata_transformer,
request_serializer,
response_deserializer)
def unary_stream(self, group, method):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _UnaryStreamMultiCallable(self._channel, group, method,
self._metadata_transformer,
request_serializer,
response_deserializer)
def stream_unary(self, group, method):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _StreamUnaryMultiCallable(self._channel, group, method,
self._metadata_transformer,
request_serializer,
response_deserializer)
def stream_stream(self, group, method):
- request_serializer = self._request_serializers.get((
- group,
- method,
- ))
- response_deserializer = self._response_deserializers.get((
- group,
- method,
- ))
+ request_serializer = self._request_serializers.get((
+ group,
+ method,
+ ))
+ response_deserializer = self._response_deserializers.get((
+ group,
+ method,
+ ))
return _StreamStreamMultiCallable(self._channel, group, method,
self._metadata_transformer,
request_serializer,
@@ -667,8 +667,8 @@ class _GenericStub(face.GenericStub):
class _DynamicStub(face.DynamicStub):
- def __init__(self, backing_generic_stub, group, cardinalities):
- self._generic_stub = backing_generic_stub
+ def __init__(self, backing_generic_stub, group, cardinalities):
+ self._generic_stub = backing_generic_stub
self._group = group
self._cardinalities = cardinalities
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/_metadata.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_metadata.py
index b7c85352853..bf94e628d6b 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/_metadata.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_metadata.py
@@ -1,52 +1,52 @@
-# 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.
-"""API metadata conversion utilities."""
-
-import collections
-
-_Metadatum = collections.namedtuple('_Metadatum', (
- 'key',
- 'value',
-))
-
-
-def _beta_metadatum(key, value):
- beta_key = key if isinstance(key, (bytes,)) else key.encode('ascii')
- beta_value = value if isinstance(value, (bytes,)) else value.encode('ascii')
- return _Metadatum(beta_key, beta_value)
-
-
-def _metadatum(beta_key, beta_value):
- key = beta_key if isinstance(beta_key, (str,)) else beta_key.decode('utf8')
- if isinstance(beta_value, (str,)) or key[-4:] == '-bin':
- value = beta_value
- else:
- value = beta_value.decode('utf8')
- return _Metadatum(key, value)
-
-
-def beta(metadata):
- if metadata is None:
- return ()
- else:
- return tuple(_beta_metadatum(key, value) for key, value in metadata)
-
-
-def unbeta(beta_metadata):
- if beta_metadata is None:
- return ()
- else:
- return tuple(
- _metadatum(beta_key, beta_value)
- for beta_key, beta_value in beta_metadata)
+# 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.
+"""API metadata conversion utilities."""
+
+import collections
+
+_Metadatum = collections.namedtuple('_Metadatum', (
+ 'key',
+ 'value',
+))
+
+
+def _beta_metadatum(key, value):
+ beta_key = key if isinstance(key, (bytes,)) else key.encode('ascii')
+ beta_value = value if isinstance(value, (bytes,)) else value.encode('ascii')
+ return _Metadatum(beta_key, beta_value)
+
+
+def _metadatum(beta_key, beta_value):
+ key = beta_key if isinstance(beta_key, (str,)) else beta_key.decode('utf8')
+ if isinstance(beta_value, (str,)) or key[-4:] == '-bin':
+ value = beta_value
+ else:
+ value = beta_value.decode('utf8')
+ return _Metadatum(key, value)
+
+
+def beta(metadata):
+ if metadata is None:
+ return ()
+ else:
+ return tuple(_beta_metadatum(key, value) for key, value in metadata)
+
+
+def unbeta(beta_metadata):
+ if beta_metadata is None:
+ return ()
+ else:
+ return tuple(
+ _metadatum(beta_key, beta_value)
+ for beta_key, beta_value in beta_metadata)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py
index 8843a3c5502..2618ad896ef 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Translates gRPC's server-side API into gRPC's server-side Beta API."""
import collections
@@ -18,7 +18,7 @@ import threading
import grpc
from grpc import _common
-from grpc.beta import _metadata
+from grpc.beta import _metadata
from grpc.beta import interfaces
from grpc.framework.common import cardinality
from grpc.framework.common import style
@@ -27,8 +27,8 @@ from grpc.framework.foundation import logging_pool
from grpc.framework.foundation import stream
from grpc.framework.interfaces.face import face
-# pylint: disable=too-many-return-statements
-
+# pylint: disable=too-many-return-statements
+
_DEFAULT_POOL_SIZE = 8
@@ -66,15 +66,15 @@ class _FaceServicerContext(face.ServicerContext):
return _ServerProtocolContext(self._servicer_context)
def invocation_metadata(self):
- return _metadata.beta(self._servicer_context.invocation_metadata())
+ return _metadata.beta(self._servicer_context.invocation_metadata())
def initial_metadata(self, initial_metadata):
- self._servicer_context.send_initial_metadata(
- _metadata.unbeta(initial_metadata))
+ self._servicer_context.send_initial_metadata(
+ _metadata.unbeta(initial_metadata))
def terminal_metadata(self, terminal_metadata):
- self._servicer_context.set_terminal_metadata(
- _metadata.unbeta(terminal_metadata))
+ self._servicer_context.set_terminal_metadata(
+ _metadata.unbeta(terminal_metadata))
def code(self, code):
self._servicer_context.set_code(code)
@@ -242,15 +242,15 @@ def _adapt_stream_stream_event(stream_stream_event):
class _SimpleMethodHandler(
collections.namedtuple('_MethodHandler', (
- 'request_streaming',
- 'response_streaming',
- 'request_deserializer',
- 'response_serializer',
- 'unary_unary',
- 'unary_stream',
- 'stream_unary',
- 'stream_stream',
- )), grpc.RpcMethodHandler):
+ 'request_streaming',
+ 'response_streaming',
+ 'request_deserializer',
+ 'response_serializer',
+ 'unary_unary',
+ 'unary_stream',
+ 'stream_unary',
+ 'stream_stream',
+ )), grpc.RpcMethodHandler):
pass
@@ -344,27 +344,27 @@ class _GenericRpcHandler(grpc.GenericRpcHandler):
class _Server(interfaces.Server):
- def __init__(self, grpc_server):
- self._grpc_server = grpc_server
+ def __init__(self, grpc_server):
+ self._grpc_server = grpc_server
def add_insecure_port(self, address):
- return self._grpc_server.add_insecure_port(address)
+ return self._grpc_server.add_insecure_port(address)
def add_secure_port(self, address, server_credentials):
- return self._grpc_server.add_secure_port(address, server_credentials)
+ return self._grpc_server.add_secure_port(address, server_credentials)
def start(self):
- self._grpc_server.start()
+ self._grpc_server.start()
def stop(self, grace):
- return self._grpc_server.stop(grace)
+ return self._grpc_server.stop(grace)
def __enter__(self):
- self._grpc_server.start()
+ self._grpc_server.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
- self._grpc_server.stop(None)
+ self._grpc_server.stop(None)
return False
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/implementations.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/implementations.py
index c5507b543fb..5be04202f05 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/implementations.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/implementations.py
@@ -1,51 +1,51 @@
-# Copyright 2015-2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 points into the Beta API of gRPC Python."""
# threading is referenced from specification in this module.
import threading # pylint: disable=unused-import
-# interfaces, cardinality, and face are referenced from specification in this
-# module.
+# interfaces, cardinality, and face are referenced from specification in this
+# module.
import grpc
from grpc import _auth
from grpc.beta import _client_adaptations
-from grpc.beta import _metadata
+from grpc.beta import _metadata
from grpc.beta import _server_adaptations
-from grpc.beta import interfaces # pylint: disable=unused-import
+from grpc.beta import interfaces # pylint: disable=unused-import
from grpc.framework.common import cardinality # pylint: disable=unused-import
from grpc.framework.interfaces.face import face # pylint: disable=unused-import
-# pylint: disable=too-many-arguments
-
+# pylint: disable=too-many-arguments
+
ChannelCredentials = grpc.ChannelCredentials
ssl_channel_credentials = grpc.ssl_channel_credentials
CallCredentials = grpc.CallCredentials
-def metadata_call_credentials(metadata_plugin, name=None):
-
- def plugin(context, callback):
-
- def wrapped_callback(beta_metadata, error):
- callback(_metadata.unbeta(beta_metadata), error)
-
- metadata_plugin(context, wrapped_callback)
-
- return grpc.metadata_call_credentials(plugin, name=name)
-
-
+def metadata_call_credentials(metadata_plugin, name=None):
+
+ def plugin(context, callback):
+
+ def wrapped_callback(beta_metadata, error):
+ callback(_metadata.unbeta(beta_metadata), error)
+
+ metadata_plugin(context, wrapped_callback)
+
+ return grpc.metadata_call_credentials(plugin, name=name)
+
+
def google_call_credentials(credentials):
"""Construct CallCredentials from GoogleCredentials.
@@ -216,7 +216,7 @@ def dynamic_stub(channel, service, cardinalities, options=None):
Returns:
A face.DynamicStub with which RPCs can be invoked.
"""
- effective_options = _EMPTY_STUB_OPTIONS if options is None else options
+ effective_options = _EMPTY_STUB_OPTIONS if options is None else options
return _client_adaptations.dynamic_stub(
channel._channel, # pylint: disable=protected-access
service,
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/interfaces.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/interfaces.py
index fb8266c74bd..28136a98402 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/interfaces.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/interfaces.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 interfaces of the Beta API of gRPC Python."""
import abc
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py
index fe3ce606c94..af88ddc925e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 the gRPC Python Beta API."""
import threading
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 a4e2660fb4e..6140cad3270 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/__init__.py
@@ -1,20 +1,20 @@
-# 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.
-"""gRPC's experimental APIs.
-
-These APIs are subject to be removed during any minor version release.
-"""
+# 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.
+"""gRPC's experimental APIs.
+
+These APIs are subject to be removed during any minor version release.
+"""
import copy
import functools
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/gevent.py b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/gevent.py
index 159d612b4ed..998d05999fc 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/gevent.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/gevent.py
@@ -1,27 +1,27 @@
-# 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.
-"""gRPC's Python gEvent APIs."""
-
-from grpc._cython import cygrpc as _cygrpc
-
-
-def init_gevent():
- """Patches gRPC's libraries to be compatible with gevent.
-
- This must be called AFTER the python standard lib has been patched,
- but BEFORE creating and gRPC objects.
-
- In order for progress to be made, the application must drive the event loop.
- """
- _cygrpc.init_grpc_gevent()
+# 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.
+"""gRPC's Python gEvent APIs."""
+
+from grpc._cython import cygrpc as _cygrpc
+
+
+def init_gevent():
+ """Patches gRPC's libraries to be compatible with gevent.
+
+ This must be called AFTER the python standard lib has been patched,
+ but BEFORE creating and gRPC objects.
+
+ In order for progress to be made, the application must drive the event loop.
+ """
+ _cygrpc.init_grpc_gevent()
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/framework/common/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/framework/common/cardinality.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/cardinality.py
index c98735622d7..0f7b6f0a94e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/cardinality.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/cardinality.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 an enum for classifying RPC methods by streaming semantics."""
import enum
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/style.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/style.py
index f6138d417ff..c051b278011 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/style.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/common/style.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 an enum for classifying RPC methods by control flow semantics."""
import enum
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/framework/foundation/abandonment.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/abandonment.py
index 660ce991c41..1c91cc39f0f 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/abandonment.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/abandonment.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 indicating abandonment of computation."""
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py
index 24daf3406f8..f7f7ba3814f 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 working with callables."""
import abc
@@ -52,8 +52,8 @@ class _EasyOutcome(
def _call_logging_exceptions(behavior, message, *args, **kwargs):
try:
- return _EasyOutcome(Outcome.Kind.RETURNED, behavior(*args, **kwargs),
- None)
+ return _EasyOutcome(Outcome.Kind.RETURNED, behavior(*args, **kwargs),
+ None)
except Exception as e: # pylint: disable=broad-except
_LOGGER.exception(message)
return _EasyOutcome(Outcome.Kind.RAISED, None, e)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/future.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/future.py
index d11679cc3d8..51fe7f67f75 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/future.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/future.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 Future interface.
Python doesn't have a Future interface in its standard library. In the absence
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py
index 421999fb1c3..edfee343caf 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 thread pool that logs exceptions raised by tasks executed within it."""
import logging
@@ -26,7 +26,7 @@ def _wrap(behavior):
def _wrapping(*args, **kwargs):
try:
return behavior(*args, **kwargs)
- except Exception:
+ except Exception:
_LOGGER.exception(
'Unexpected exception from %s executed in logging pool!',
behavior)
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream.py
index fd47977b89f..86a5367086e 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Interfaces related to streams of values or objects."""
import abc
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py
index 1faaf29bd7e..a24c27f467a 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Helpful utilities related to the stream module."""
import logging
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/framework/interfaces/base/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/framework/interfaces/base/base.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/base.py
index 82c44f91104..80dd79d4ab5 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/base.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/base.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 base interface of RPC Framework.
Implementations of this interface support the conduct of "operations":
@@ -31,29 +31,29 @@ import six
# abandonment is referenced from specification in this module.
from grpc.framework.foundation import abandonment # pylint: disable=unused-import
-# pylint: disable=too-many-arguments
-
+# pylint: disable=too-many-arguments
+
class NoSuchMethodError(Exception):
"""Indicates that an unrecognized operation has been called.
- Attributes:
+ Attributes:
code: A code value to communicate to the other side of the operation
along with indication of operation termination. May be None.
details: A details value to communicate to the other side of the
operation along with indication of operation termination. May be None.
"""
-
- def __init__(self, code, details):
- """Constructor.
-
- Args:
- code: A code value to communicate to the other side of the operation
- along with indication of operation termination. May be None.
- details: A details value to communicate to the other side of the
- operation along with indication of operation termination. May be None.
- """
- super(NoSuchMethodError, self).__init__()
+
+ def __init__(self, code, details):
+ """Constructor.
+
+ Args:
+ code: A code value to communicate to the other side of the operation
+ along with indication of operation termination. May be None.
+ details: A details value to communicate to the other side of the
+ operation along with indication of operation termination. May be None.
+ """
+ super(NoSuchMethodError, self).__init__()
self.code = code
self.details = details
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/utilities.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/utilities.py
index 281db62b5d4..6e29a6d9bff 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/utilities.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/base/utilities.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 use with the base interface of RPC Framework."""
import collections
@@ -19,22 +19,22 @@ from grpc.framework.interfaces.base import base
class _Completion(base.Completion,
- collections.namedtuple('_Completion', (
- 'terminal_metadata',
- 'code',
- 'message',
- ))):
+ collections.namedtuple('_Completion', (
+ 'terminal_metadata',
+ 'code',
+ 'message',
+ ))):
"""A trivial implementation of base.Completion."""
class _Subscription(base.Subscription,
collections.namedtuple('_Subscription', (
- 'kind',
- 'termination_callback',
- 'allowance',
- 'operator',
- 'protocol_receiver',
- ))):
+ 'kind',
+ 'termination_callback',
+ 'allowance',
+ 'operator',
+ 'protocol_receiver',
+ ))):
"""A trivial implementation of base.Subscription."""
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc/framework/interfaces/face/face.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/face.py
index 5b47f11d0d7..83f2abb93e7 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/face.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/face.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Interfaces defining the Face layer of RPC Framework."""
import abc
@@ -27,9 +27,9 @@ from grpc.framework.foundation import abandonment # pylint: disable=unused-impo
from grpc.framework.foundation import future # pylint: disable=unused-import
from grpc.framework.foundation import stream # pylint: disable=unused-import
-# pylint: disable=too-many-arguments
-
+# pylint: disable=too-many-arguments
+
class NoSuchMethodError(Exception):
"""Raised by customer code to indicate an unrecognized method.
@@ -50,20 +50,20 @@ class NoSuchMethodError(Exception):
self.method = method
def __repr__(self):
- return 'face.NoSuchMethodError(%s, %s)' % (
- self.group,
- self.method,
- )
+ return 'face.NoSuchMethodError(%s, %s)' % (
+ self.group,
+ self.method,
+ )
class Abortion(
- collections.namedtuple('Abortion', (
- 'kind',
- 'initial_metadata',
- 'terminal_metadata',
- 'code',
- 'details',
- ))):
+ collections.namedtuple('Abortion', (
+ 'kind',
+ 'initial_metadata',
+ 'terminal_metadata',
+ 'code',
+ 'details',
+ ))):
"""A value describing RPC abortion.
Attributes:
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/utilities.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/utilities.py
index f27bd676155..6e9832811df 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/utilities.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/interfaces/face/utilities.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 RPC Framework's Face interface."""
import collections
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 67f985e1f46..ddd3422e92a 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc_core_dependencies.py.template`!!!
@@ -236,148 +236,148 @@ CORE_SOURCE_FILES = [
'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',
- '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_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/string.cc',
- '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/sync.cc',
+ 'src/core/lib/gpr/alloc.cc',
+ '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_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/string.cc',
+ '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/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_windows.cc',
- 'src/core/lib/gpr/tls_pthread.cc',
- '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/wrap_memcpy.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_windows.cc',
+ 'src/core/lib/gpr/tls_pthread.cc',
+ '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/wrap_memcpy.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/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/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/parser.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/call_combiner.cc',
'src/core/lib/iomgr/cfstream_handle.cc',
- 'src/core/lib/iomgr/combiner.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.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/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/ev_apple.cc',
- 'src/core/lib/iomgr/ev_epoll1_linux.cc',
- 'src/core/lib/iomgr/ev_epollex_linux.cc',
- 'src/core/lib/iomgr/ev_poll_posix.cc',
- 'src/core/lib/iomgr/ev_posix.cc',
- 'src/core/lib/iomgr/ev_windows.cc',
- 'src/core/lib/iomgr/exec_ctx.cc',
- 'src/core/lib/iomgr/executor.cc',
+ 'src/core/lib/iomgr/ev_epoll1_linux.cc',
+ 'src/core/lib/iomgr/ev_epollex_linux.cc',
+ 'src/core/lib/iomgr/ev_poll_posix.cc',
+ 'src/core/lib/iomgr/ev_posix.cc',
+ '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/fork_posix.cc',
- 'src/core/lib/iomgr/fork_windows.cc',
- '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/fork_posix.cc',
+ 'src/core/lib/iomgr/fork_windows.cc',
+ '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_posix.cc',
'src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc',
'src/core/lib/iomgr/internal_errqueue.cc',
- 'src/core/lib/iomgr/iocp_windows.cc',
- 'src/core/lib/iomgr/iomgr.cc',
- '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/iocp_windows.cc',
+ 'src/core/lib/iomgr/iomgr.cc',
+ '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_uv.cc',
- 'src/core/lib/iomgr/iomgr_windows.cc',
- 'src/core/lib/iomgr/is_epollexclusive_available.cc',
- 'src/core/lib/iomgr/load_file.cc',
- 'src/core/lib/iomgr/lockfree_event.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/load_file.cc',
+ 'src/core/lib/iomgr/lockfree_event.cc',
'src/core/lib/iomgr/parse_address.cc',
'src/core/lib/iomgr/poller/eventmanager_libuv.cc',
- 'src/core/lib/iomgr/polling_entity.cc',
- 'src/core/lib/iomgr/pollset.cc',
- 'src/core/lib/iomgr/pollset_custom.cc',
- 'src/core/lib/iomgr/pollset_set.cc',
- 'src/core/lib/iomgr/pollset_set_custom.cc',
- 'src/core/lib/iomgr/pollset_set_windows.cc',
- 'src/core/lib/iomgr/pollset_uv.cc',
- 'src/core/lib/iomgr/pollset_windows.cc',
- 'src/core/lib/iomgr/resolve_address.cc',
- 'src/core/lib/iomgr/resolve_address_custom.cc',
- '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/sockaddr_utils.cc',
- 'src/core/lib/iomgr/socket_factory_posix.cc',
- 'src/core/lib/iomgr/socket_mutator.cc',
- '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_uv.cc',
- '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/polling_entity.cc',
+ 'src/core/lib/iomgr/pollset.cc',
+ 'src/core/lib/iomgr/pollset_custom.cc',
+ 'src/core/lib/iomgr/pollset_set.cc',
+ 'src/core/lib/iomgr/pollset_set_custom.cc',
+ 'src/core/lib/iomgr/pollset_set_windows.cc',
+ 'src/core/lib/iomgr/pollset_uv.cc',
+ 'src/core/lib/iomgr/pollset_windows.cc',
+ 'src/core/lib/iomgr/resolve_address.cc',
+ 'src/core/lib/iomgr/resolve_address_custom.cc',
+ '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/sockaddr_utils.cc',
+ 'src/core/lib/iomgr/socket_factory_posix.cc',
+ 'src/core/lib/iomgr/socket_mutator.cc',
+ '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_uv.cc',
+ '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_custom.cc',
- 'src/core/lib/iomgr/tcp_client_posix.cc',
- 'src/core/lib/iomgr/tcp_client_windows.cc',
- 'src/core/lib/iomgr/tcp_custom.cc',
- 'src/core/lib/iomgr/tcp_posix.cc',
- 'src/core/lib/iomgr/tcp_server.cc',
- 'src/core/lib/iomgr/tcp_server_custom.cc',
- 'src/core/lib/iomgr/tcp_server_posix.cc',
- '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/time_averaged_stats.cc',
- 'src/core/lib/iomgr/timer.cc',
- 'src/core/lib/iomgr/timer_custom.cc',
- 'src/core/lib/iomgr/timer_generic.cc',
- 'src/core/lib/iomgr/timer_heap.cc',
- 'src/core/lib/iomgr/timer_manager.cc',
- 'src/core/lib/iomgr/timer_uv.cc',
- 'src/core/lib/iomgr/udp_server.cc',
- 'src/core/lib/iomgr/unix_sockets_posix.cc',
- '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_posix.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',
+ 'src/core/lib/iomgr/tcp_custom.cc',
+ 'src/core/lib/iomgr/tcp_posix.cc',
+ 'src/core/lib/iomgr/tcp_server.cc',
+ 'src/core/lib/iomgr/tcp_server_custom.cc',
+ 'src/core/lib/iomgr/tcp_server_posix.cc',
+ '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/time_averaged_stats.cc',
+ 'src/core/lib/iomgr/timer.cc',
+ 'src/core/lib/iomgr/timer_custom.cc',
+ 'src/core/lib/iomgr/timer_generic.cc',
+ 'src/core/lib/iomgr/timer_heap.cc',
+ 'src/core/lib/iomgr/timer_manager.cc',
+ 'src/core/lib/iomgr/timer_uv.cc',
+ 'src/core/lib/iomgr/udp_server.cc',
+ 'src/core/lib/iomgr/unix_sockets_posix.cc',
+ '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_posix.cc',
'src/core/lib/iomgr/work_serializer.cc',
- 'src/core/lib/json/json_reader.cc',
+ 'src/core/lib/json/json_reader.cc',
'src/core/lib/json/json_util.cc',
- 'src/core/lib/json/json_writer.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/security/authorization/authorization_engine.cc',
@@ -425,75 +425,75 @@ CORE_SOURCE_FILES = [
'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',
- 'src/core/lib/slice/slice_buffer.cc',
- 'src/core/lib/slice/slice_intern.cc',
- 'src/core/lib/slice/slice_string_helpers.cc',
- 'src/core/lib/surface/api_trace.cc',
- '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_details.cc',
- 'src/core/lib/surface/call_log_batch.cc',
- 'src/core/lib/surface/channel.cc',
- 'src/core/lib/surface/channel_init.cc',
- 'src/core/lib/surface/channel_ping.cc',
- 'src/core/lib/surface/channel_stack_type.cc',
- '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/slice/b64.cc',
+ 'src/core/lib/slice/percent_encoding.cc',
+ '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_string_helpers.cc',
+ 'src/core/lib/surface/api_trace.cc',
+ '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_details.cc',
+ 'src/core/lib/surface/call_log_batch.cc',
+ 'src/core/lib/surface/channel.cc',
+ 'src/core/lib/surface/channel_init.cc',
+ 'src/core/lib/surface/channel_ping.cc',
+ 'src/core/lib/surface/channel_stack_type.cc',
+ '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/lame_client.cc',
- 'src/core/lib/surface/metadata_array.cc',
- 'src/core/lib/surface/server.cc',
- 'src/core/lib/surface/validate_metadata.cc',
- 'src/core/lib/surface/version.cc',
+ 'src/core/lib/surface/lame_client.cc',
+ 'src/core/lib/surface/metadata_array.cc',
+ 'src/core/lib/surface/server.cc',
+ 'src/core/lib/surface/validate_metadata.cc',
+ 'src/core/lib/surface/version.cc',
'src/core/lib/transport/authority_override.cc',
- 'src/core/lib/transport/bdp_estimator.cc',
- 'src/core/lib/transport/byte_stream.cc',
- 'src/core/lib/transport/connectivity_state.cc',
- 'src/core/lib/transport/error_utils.cc',
- 'src/core/lib/transport/metadata.cc',
- 'src/core/lib/transport/metadata_batch.cc',
- 'src/core/lib/transport/pid_controller.cc',
- 'src/core/lib/transport/static_metadata.cc',
- 'src/core/lib/transport/status_conversion.cc',
- 'src/core/lib/transport/status_metadata.cc',
- 'src/core/lib/transport/timeout_encoding.cc',
- 'src/core/lib/transport/transport.cc',
- 'src/core/lib/transport/transport_op_string.cc',
+ 'src/core/lib/transport/bdp_estimator.cc',
+ 'src/core/lib/transport/byte_stream.cc',
+ 'src/core/lib/transport/connectivity_state.cc',
+ 'src/core/lib/transport/error_utils.cc',
+ 'src/core/lib/transport/metadata.cc',
+ 'src/core/lib/transport/metadata_batch.cc',
+ 'src/core/lib/transport/pid_controller.cc',
+ 'src/core/lib/transport/static_metadata.cc',
+ 'src/core/lib/transport/status_conversion.cc',
+ 'src/core/lib/transport/status_metadata.cc',
+ 'src/core/lib/transport/timeout_encoding.cc',
+ '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/tsi/alts/crypt/aes_gcm.cc',
- 'src/core/tsi/alts/crypt/gsec.cc',
- 'src/core/tsi/alts/frame_protector/alts_counter.cc',
- 'src/core/tsi/alts/frame_protector/alts_crypter.cc',
- 'src/core/tsi/alts/frame_protector/alts_frame_protector.cc',
- 'src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc',
- '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/handshaker/alts_handshaker_client.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',
+ 'src/core/tsi/alts/frame_protector/alts_crypter.cc',
+ 'src/core/tsi/alts/frame_protector/alts_frame_protector.cc',
+ 'src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc',
+ '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/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_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/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',
- 'src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc',
- 'src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc',
- 'src/core/tsi/fake_transport_security.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',
+ 'src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc',
+ 'src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc',
+ 'src/core/tsi/fake_transport_security.cc',
'src/core/tsi/local_transport_security.cc',
- '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_openssl.cc',
- 'src/core/tsi/ssl_transport_security.cc',
+ '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_openssl.cc',
+ 'src/core/tsi/ssl_transport_security.cc',
'src/core/tsi/transport_security.cc',
- 'src/core/tsi/transport_security_grpc.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',
'third_party/abseil-cpp/y_absl/base/internal/exponential_biased.cc',
@@ -837,56 +837,56 @@ CORE_SOURCE_FILES = [
'third_party/boringssl-with-bazel/src/ssl/tls13_server.cc',
'third_party/boringssl-with-bazel/src/ssl/tls_method.cc',
'third_party/boringssl-with-bazel/src/ssl/tls_record.cc',
- 'third_party/cares/cares/ares__close_sockets.c',
- 'third_party/cares/cares/ares__get_hostent.c',
- 'third_party/cares/cares/ares__read_line.c',
- 'third_party/cares/cares/ares__timeval.c',
- 'third_party/cares/cares/ares_cancel.c',
- 'third_party/cares/cares/ares_create_query.c',
- 'third_party/cares/cares/ares_data.c',
- 'third_party/cares/cares/ares_destroy.c',
- 'third_party/cares/cares/ares_expand_name.c',
- 'third_party/cares/cares/ares_expand_string.c',
- 'third_party/cares/cares/ares_fds.c',
- 'third_party/cares/cares/ares_free_hostent.c',
- 'third_party/cares/cares/ares_free_string.c',
- 'third_party/cares/cares/ares_getenv.c',
- 'third_party/cares/cares/ares_gethostbyaddr.c',
- 'third_party/cares/cares/ares_gethostbyname.c',
- 'third_party/cares/cares/ares_getnameinfo.c',
- 'third_party/cares/cares/ares_getopt.c',
- 'third_party/cares/cares/ares_getsock.c',
- 'third_party/cares/cares/ares_init.c',
- 'third_party/cares/cares/ares_library_init.c',
- 'third_party/cares/cares/ares_llist.c',
- 'third_party/cares/cares/ares_mkquery.c',
- 'third_party/cares/cares/ares_nowarn.c',
- 'third_party/cares/cares/ares_options.c',
- 'third_party/cares/cares/ares_parse_a_reply.c',
- 'third_party/cares/cares/ares_parse_aaaa_reply.c',
- 'third_party/cares/cares/ares_parse_mx_reply.c',
- 'third_party/cares/cares/ares_parse_naptr_reply.c',
- 'third_party/cares/cares/ares_parse_ns_reply.c',
- 'third_party/cares/cares/ares_parse_ptr_reply.c',
- 'third_party/cares/cares/ares_parse_soa_reply.c',
- 'third_party/cares/cares/ares_parse_srv_reply.c',
- 'third_party/cares/cares/ares_parse_txt_reply.c',
- 'third_party/cares/cares/ares_platform.c',
- 'third_party/cares/cares/ares_process.c',
- 'third_party/cares/cares/ares_query.c',
- 'third_party/cares/cares/ares_search.c',
- 'third_party/cares/cares/ares_send.c',
- '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__close_sockets.c',
+ 'third_party/cares/cares/ares__get_hostent.c',
+ 'third_party/cares/cares/ares__read_line.c',
+ 'third_party/cares/cares/ares__timeval.c',
+ 'third_party/cares/cares/ares_cancel.c',
+ 'third_party/cares/cares/ares_create_query.c',
+ 'third_party/cares/cares/ares_data.c',
+ 'third_party/cares/cares/ares_destroy.c',
+ 'third_party/cares/cares/ares_expand_name.c',
+ 'third_party/cares/cares/ares_expand_string.c',
+ 'third_party/cares/cares/ares_fds.c',
+ 'third_party/cares/cares/ares_free_hostent.c',
+ 'third_party/cares/cares/ares_free_string.c',
+ 'third_party/cares/cares/ares_getenv.c',
+ 'third_party/cares/cares/ares_gethostbyaddr.c',
+ 'third_party/cares/cares/ares_gethostbyname.c',
+ 'third_party/cares/cares/ares_getnameinfo.c',
+ 'third_party/cares/cares/ares_getopt.c',
+ 'third_party/cares/cares/ares_getsock.c',
+ 'third_party/cares/cares/ares_init.c',
+ 'third_party/cares/cares/ares_library_init.c',
+ 'third_party/cares/cares/ares_llist.c',
+ 'third_party/cares/cares/ares_mkquery.c',
+ 'third_party/cares/cares/ares_nowarn.c',
+ 'third_party/cares/cares/ares_options.c',
+ 'third_party/cares/cares/ares_parse_a_reply.c',
+ 'third_party/cares/cares/ares_parse_aaaa_reply.c',
+ 'third_party/cares/cares/ares_parse_mx_reply.c',
+ 'third_party/cares/cares/ares_parse_naptr_reply.c',
+ 'third_party/cares/cares/ares_parse_ns_reply.c',
+ 'third_party/cares/cares/ares_parse_ptr_reply.c',
+ 'third_party/cares/cares/ares_parse_soa_reply.c',
+ 'third_party/cares/cares/ares_parse_srv_reply.c',
+ 'third_party/cares/cares/ares_parse_txt_reply.c',
+ 'third_party/cares/cares/ares_platform.c',
+ 'third_party/cares/cares/ares_process.c',
+ 'third_party/cares/cares/ares_query.c',
+ 'third_party/cares/cares/ares_search.c',
+ 'third_party/cares/cares/ares_send.c',
+ '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_timeout.c',
- 'third_party/cares/cares/ares_version.c',
- 'third_party/cares/cares/ares_writev.c',
- 'third_party/cares/cares/bitncmp.c',
- 'third_party/cares/cares/inet_net_pton.c',
- 'third_party/cares/cares/inet_ntop.c',
- 'third_party/cares/cares/windows_port.c',
+ 'third_party/cares/cares/ares_timeout.c',
+ 'third_party/cares/cares/ares_version.c',
+ 'third_party/cares/cares/ares_writev.c',
+ 'third_party/cares/cares/bitncmp.c',
+ 'third_party/cares/cares/inet_net_pton.c',
+ 'third_party/cares/cares/inet_ntop.c',
+ 'third_party/cares/cares/windows_port.c',
'third_party/re2/re2/bitstate.cc',
'third_party/re2/re2/compile.cc',
'third_party/re2/re2/dfa.cc',
diff --git a/contrib/libs/grpc/src/python/grpcio/grpc_version.py b/contrib/libs/grpc/src/python/grpcio/grpc_version.py
index 9237f14e2fc..34e666020e4 100644
--- a/contrib/libs/grpc/src/python/grpcio/grpc_version.py
+++ b/contrib/libs/grpc/src/python/grpcio/grpc_version.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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/grpc_version.py.template`!!!
diff --git a/contrib/libs/grpc/src/python/grpcio/support.py b/contrib/libs/grpc/src/python/grpcio/support.py
index 217f3cb9ed5..1fe82091677 100644
--- a/contrib/libs/grpc/src/python/grpcio/support.py
+++ b/contrib/libs/grpc/src/python/grpcio/support.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 os.path
@@ -101,7 +101,7 @@ def diagnose_attribute_error(build_ext, error):
_ERROR_DIAGNOSES = {
errors.CompileError: diagnose_compile_error,
- AttributeError: diagnose_attribute_error,
+ AttributeError: diagnose_attribute_error,
}
@@ -109,10 +109,10 @@ def diagnose_build_ext_error(build_ext, error, formatted):
diagnostic = _ERROR_DIAGNOSES.get(type(error))
if diagnostic is None:
raise commands.CommandError(
- "\n\nWe could not diagnose your build failure. If you are unable to "
- "proceed, please file an issue at http://www.github.com/grpc/grpc "
- "with `[Python install]` in the title; please attach the whole log "
- "(including everything that may have appeared above the Python "
- "backtrace).\n\n{}".format(formatted))
+ "\n\nWe could not diagnose your build failure. If you are unable to "
+ "proceed, please file an issue at http://www.github.com/grpc/grpc "
+ "with `[Python install]` in the title; please attach the whole log "
+ "(including everything that may have appeared above the Python "
+ "backtrace).\n\n{}".format(formatted))
else:
diagnostic(build_ext, error)
diff --git a/contrib/libs/grpc/src/python/grpcio/ya.make b/contrib/libs/grpc/src/python/grpcio/ya.make
index 5cdb0230c41..e0fb3ebbc16 100644
--- a/contrib/libs/grpc/src/python/grpcio/ya.make
+++ b/contrib/libs/grpc/src/python/grpcio/ya.make
@@ -22,63 +22,63 @@ IF (PYTHON2)
)
ENDIF()
-ADDINCL(
+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)
+ # https://github.com/grpc/grpc/blob/v1.15.1/tools/bazel.rc#L43
+ CXXFLAGS(-fno-sanitize=function)
ENDIF()
+
+NO_LINT()
-NO_LINT()
-
-NO_COMPILER_WARNINGS()
+NO_COMPILER_WARNINGS()
PY_SRCS(
TOP_LEVEL
- grpc/__init__.py
+ grpc/__init__.py
grpc/_auth.py
grpc/_channel.py
grpc/_common.py
grpc/_compression.py
- grpc/_cython/__init__.py
+ grpc/_cython/__init__.py
grpc/_cython/_cygrpc/__init__.py
- grpc/_cython/cygrpc.pyx
- grpc/_grpcio_metadata.py
- grpc/_interceptor.py
- grpc/_plugin_wrapping.py
+ grpc/_cython/cygrpc.pyx
+ grpc/_grpcio_metadata.py
+ grpc/_interceptor.py
+ grpc/_plugin_wrapping.py
grpc/_runtime_protos.py
- grpc/_server.py
- grpc/_utilities.py
- grpc/beta/__init__.py
- grpc/beta/_client_adaptations.py
- grpc/beta/_metadata.py
- grpc/beta/_server_adaptations.py
- grpc/beta/implementations.py
- grpc/beta/interfaces.py
- grpc/beta/utilities.py
- grpc/experimental/__init__.py
- grpc/experimental/gevent.py
+ grpc/_server.py
+ grpc/_utilities.py
+ grpc/beta/__init__.py
+ grpc/beta/_client_adaptations.py
+ grpc/beta/_metadata.py
+ grpc/beta/_server_adaptations.py
+ grpc/beta/implementations.py
+ grpc/beta/interfaces.py
+ grpc/beta/utilities.py
+ grpc/experimental/__init__.py
+ grpc/experimental/gevent.py
grpc/experimental/session_cache.py
- grpc/framework/__init__.py
- grpc/framework/common/__init__.py
+ grpc/framework/__init__.py
+ grpc/framework/common/__init__.py
grpc/framework/common/cardinality.py
grpc/framework/common/style.py
- grpc/framework/foundation/__init__.py
+ grpc/framework/foundation/__init__.py
grpc/framework/foundation/abandonment.py
grpc/framework/foundation/callable_util.py
grpc/framework/foundation/future.py
grpc/framework/foundation/logging_pool.py
grpc/framework/foundation/stream.py
grpc/framework/foundation/stream_util.py
- grpc/framework/interfaces/__init__.py
- grpc/framework/interfaces/base/__init__.py
+ grpc/framework/interfaces/__init__.py
+ grpc/framework/interfaces/base/__init__.py
grpc/framework/interfaces/base/base.py
grpc/framework/interfaces/base/utilities.py
- grpc/framework/interfaces/face/__init__.py
+ grpc/framework/interfaces/face/__init__.py
grpc/framework/interfaces/face/face.py
grpc/framework/interfaces/face/utilities.py
)
diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/__init__.py b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_health_checking/grpc_health/v1/__init__.py b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/__init__.py
index 5fb4f3c3cfd..7de13e8c468 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_health_checking/grpc_health/v1/health.py b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py
index f7ee639ec8a..08e1683ce58 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
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Reference implementation for health checking in gRPC Python."""
import collections
diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_version.py b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_version.py
index f676be10684..d29735b19d9 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_version.py
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_version.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_health_checking/grpc_version.py.template`!!!
diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py b/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py
index 874dec7343a..d8b64f191e7 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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."""
import os
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 fa1fbbd55ad..efab8cf7003 100644
--- a/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py
@@ -1,16 +1,16 @@
-# Copyright 2015 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Setup module for the GRPC Python package's optional health checking."""
import os
@@ -23,67 +23,67 @@ _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__)))
-# Break import-style to ensure we can actually find our local modules.
+# Break import-style to ensure we can actually find our local modules.
import grpc_version
-
-class _NoOpCommand(setuptools.Command):
- """No-op command."""
-
- description = ''
- user_options = []
-
- def initialize_options(self):
- pass
-
- def finalize_options(self):
- pass
-
- def run(self):
- pass
-
-
-CLASSIFIERS = [
- 'Development Status :: 5 - Production/Stable',
- 'Programming Language :: Python',
- 'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.7',
- 'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.4',
- 'Programming Language :: Python :: 3.5',
- 'Programming Language :: Python :: 3.6',
+
+class _NoOpCommand(setuptools.Command):
+ """No-op command."""
+
+ description = ''
+ user_options = []
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ pass
+
+
+CLASSIFIERS = [
+ 'Development Status :: 5 - Production/Stable',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ '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.9',
- 'License :: OSI Approved :: Apache Software License',
-]
-
+ 'License :: OSI Approved :: Apache Software License',
+]
+
PACKAGE_DIRECTORIES = {
'': '.',
}
-INSTALL_REQUIRES = (
+INSTALL_REQUIRES = (
'protobuf>=3.6.0',
- 'grpcio>={version}'.format(version=grpc_version.VERSION),
-)
+ 'grpcio>={version}'.format(version=grpc_version.VERSION),
+)
-try:
- import health_commands as _health_commands
- # we are in the build environment, otherwise the above import fails
+try:
+ import health_commands as _health_commands
+ # we are in the build environment, otherwise the above import fails
SETUP_REQUIRES = ('grpcio-tools=={version}'.format(
version=grpc_version.VERSION),)
- COMMAND_CLASS = {
- # Run preprocess from the repository *before* doing any packaging!
+ COMMAND_CLASS = {
+ # Run preprocess from the repository *before* doing any packaging!
'preprocess': _health_commands.Preprocess,
- 'build_package_protos': _health_commands.BuildPackageProtos,
- }
-except ImportError:
- SETUP_REQUIRES = ()
- COMMAND_CLASS = {
- # wire up commands to no-op not to break the external dependencies
- 'preprocess': _NoOpCommand,
- 'build_package_protos': _NoOpCommand,
- }
+ 'build_package_protos': _health_commands.BuildPackageProtos,
+ }
+except ImportError:
+ SETUP_REQUIRES = ()
+ COMMAND_CLASS = {
+ # wire up commands to no-op not to break the external dependencies
+ 'preprocess': _NoOpCommand,
+ 'build_package_protos': _NoOpCommand,
+ }
setuptools.setup(name='grpcio-health-checking',
version=grpc_version.VERSION,
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/README.rst b/contrib/libs/grpc/src/python/grpcio_reflection/README.rst
index 56f9953373b..327c835cc21 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/README.rst
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/README.rst
@@ -1,8 +1,8 @@
-gRPC Python Reflection package
-==============================
-
-Reference package for reflection in GRPC Python.
-
+gRPC Python Reflection package
+==============================
+
+Reference package for reflection in GRPC Python.
+
Supported Python Versions
-------------------------
Python >= 3.5
@@ -11,8 +11,8 @@ 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`.
-
+Dependencies
+------------
+
+Depends on the `grpcio` package, available from PyPI via `pip install grpcio`.
+
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/__init__.py b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/__init__.py
index 5772620b602..d26af32a0ee 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_reflection/grpc_reflection/v1alpha/__init__.py b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/__init__.py
index 5772620b602..d26af32a0ee 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/__init__.py
@@ -1,13 +1,13 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_reflection/grpc_reflection/v1alpha/reflection.py b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py
index b302cea2419..2f91c772d63 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Reference implementation for reflection in gRPC Python."""
import sys
@@ -29,7 +29,7 @@ class ReflectionServicer(BaseReflectionServicer):
"""Servicer handling RPCs for service statuses."""
def ServerReflectionInfo(self, request_iterator, context):
- # pylint: disable=unused-argument
+ # pylint: disable=unused-argument
for request in request_iterator:
if request.HasField('file_by_filename'):
yield self._file_by_filename(request.file_by_filename)
@@ -41,7 +41,7 @@ class ReflectionServicer(BaseReflectionServicer):
request.file_containing_extension.containing_type,
request.file_containing_extension.extension_number)
elif request.HasField('all_extension_numbers_of_type'):
- yield self._all_extension_numbers_of_type(
+ yield self._all_extension_numbers_of_type(
request.all_extension_numbers_of_type)
elif request.HasField('list_services'):
yield self._list_services()
@@ -51,11 +51,11 @@ class ReflectionServicer(BaseReflectionServicer):
error_code=grpc.StatusCode.INVALID_ARGUMENT.value[0],
error_message=grpc.StatusCode.INVALID_ARGUMENT.value[1].
encode(),
- ))
-
-
+ ))
+
+
_enable_server_reflection_doc = """Enables server reflection on a server.
-
+
Args:
service_names: Iterable of fully-qualified service names available.
server: grpc.Server to which reflection service will be added.
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_version.py b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_version.py
index 676511118a4..3897f1424cd 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_version.py
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_version.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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_reflection/grpc_version.py.template`!!!
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py b/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py
index 311ca4c4dba..c5c31dfece5 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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."""
import os
@@ -19,7 +19,7 @@ import shutil
import setuptools
ROOT_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
-REFLECTION_PROTO = os.path.join(
+REFLECTION_PROTO = os.path.join(
ROOT_DIR, '../../proto/grpc/reflection/v1alpha/reflection.proto')
LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE')
@@ -38,9 +38,9 @@ class Preprocess(setuptools.Command):
pass
def run(self):
- if os.path.isfile(REFLECTION_PROTO):
+ if os.path.isfile(REFLECTION_PROTO):
shutil.copyfile(
- REFLECTION_PROTO,
+ REFLECTION_PROTO,
os.path.join(ROOT_DIR,
'grpc_reflection/v1alpha/reflection.proto'))
if os.path.isfile(LICENSE):
diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/setup.py b/contrib/libs/grpc/src/python/grpcio_reflection/setup.py
index 2d0a3fcdaaf..db1a9a333be 100644
--- a/contrib/libs/grpc/src/python/grpcio_reflection/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_reflection/setup.py
@@ -1,16 +1,16 @@
-# Copyright 2016 gRPC authors.
+# 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
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
"""Setup module for the GRPC Python package's optional reflection."""
import os
@@ -24,67 +24,67 @@ _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__)))
-# Break import-style to ensure we can actually find our local modules.
+# Break import-style to ensure we can actually find our local modules.
import grpc_version
-
-class _NoOpCommand(setuptools.Command):
- """No-op command."""
-
- description = ''
- user_options = []
-
- def initialize_options(self):
- pass
-
- def finalize_options(self):
- pass
-
- def run(self):
- pass
-
-
-CLASSIFIERS = [
- 'Development Status :: 5 - Production/Stable',
- 'Programming Language :: Python',
- 'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.7',
- 'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.4',
- 'Programming Language :: Python :: 3.5',
- 'Programming Language :: Python :: 3.6',
+
+class _NoOpCommand(setuptools.Command):
+ """No-op command."""
+
+ description = ''
+ user_options = []
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ pass
+
+
+CLASSIFIERS = [
+ 'Development Status :: 5 - Production/Stable',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ '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.9',
- 'License :: OSI Approved :: Apache Software License',
-]
-
+ 'License :: OSI Approved :: Apache Software License',
+]
+
PACKAGE_DIRECTORIES = {
'': '.',
}
-INSTALL_REQUIRES = (
+INSTALL_REQUIRES = (
'protobuf>=3.6.0',
- 'grpcio>={version}'.format(version=grpc_version.VERSION),
-)
+ 'grpcio>={version}'.format(version=grpc_version.VERSION),
+)
-try:
- import reflection_commands as _reflection_commands
- # we are in the build environment, otherwise the above import fails
+try:
+ import reflection_commands as _reflection_commands
+ # we are in the build environment, otherwise the above import fails
SETUP_REQUIRES = ('grpcio-tools=={version}'.format(
version=grpc_version.VERSION),)
- COMMAND_CLASS = {
- # Run preprocess from the repository *before* doing any packaging!
+ COMMAND_CLASS = {
+ # Run preprocess from the repository *before* doing any packaging!
'preprocess': _reflection_commands.Preprocess,
- 'build_package_protos': _reflection_commands.BuildPackageProtos,
- }
-except ImportError:
- SETUP_REQUIRES = ()
- COMMAND_CLASS = {
- # wire up commands to no-op not to break the external dependencies
- 'preprocess': _NoOpCommand,
- 'build_package_protos': _NoOpCommand,
- }
+ 'build_package_protos': _reflection_commands.BuildPackageProtos,
+ }
+except ImportError:
+ SETUP_REQUIRES = ()
+ COMMAND_CLASS = {
+ # wire up commands to no-op not to break the external dependencies
+ 'preprocess': _NoOpCommand,
+ 'build_package_protos': _NoOpCommand,
+ }
setuptools.setup(name='grpcio-reflection',
version=grpc_version.VERSION,
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py
index 65fdd1b8ca4..af4a2e2b0bf 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py
@@ -1,697 +1,697 @@
-# 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.
-"""Objects for use in testing gRPC Python-using application code."""
-
-import abc
+# 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.
+"""Objects for use in testing gRPC Python-using application code."""
+
+import abc
import six
-
-from google.protobuf import descriptor
-
-import grpc
-
-
-class UnaryUnaryChannelRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a unary-unary RPC invoked by a system under test.
-
- Enables users to "play server" for the RPC.
- """
-
- @abc.abstractmethod
- def send_initial_metadata(self, initial_metadata):
- """Sends the RPC's initial metadata to the system under test.
-
- Args:
- initial_metadata: The RPC's initial metadata to be "sent" to
- the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancelled(self):
- """Blocks until the system under test has cancelled the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def terminate(self, response, trailing_metadata, code, details):
- """Terminates the RPC.
-
- Args:
- response: The response for the RPC.
- trailing_metadata: The RPC's trailing metadata.
- code: The RPC's status code.
- details: The RPC's status details.
- """
- raise NotImplementedError()
-
-
-class UnaryStreamChannelRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a unary-stream RPC invoked by a system under test.
-
- Enables users to "play server" for the RPC.
- """
-
- @abc.abstractmethod
- def send_initial_metadata(self, initial_metadata):
- """Sends the RPC's initial metadata to the system under test.
-
- Args:
- initial_metadata: The RPC's initial metadata to be "sent" to
- the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def send_response(self, response):
- """Sends a response to the system under test.
-
- Args:
- response: A response message to be "sent" to the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancelled(self):
- """Blocks until the system under test has cancelled the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def terminate(self, trailing_metadata, code, details):
- """Terminates the RPC.
-
- Args:
- trailing_metadata: The RPC's trailing metadata.
- code: The RPC's status code.
- details: The RPC's status details.
- """
- raise NotImplementedError()
-
-
-class StreamUnaryChannelRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a stream-unary RPC invoked by a system under test.
-
- Enables users to "play server" for the RPC.
- """
-
- @abc.abstractmethod
- def send_initial_metadata(self, initial_metadata):
- """Sends the RPC's initial metadata to the system under test.
-
- Args:
- initial_metadata: The RPC's initial metadata to be "sent" to
- the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_request(self):
- """Draws one of the requests added to the RPC by the system under test.
-
- This method blocks until the system under test has added to the RPC
- the request to be returned.
-
- Successive calls to this method return requests in the same order in
- which the system under test added them to the RPC.
-
- Returns:
- A request message added to the RPC by the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def requests_closed(self):
- """Blocks until the system under test has closed the request stream."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancelled(self):
- """Blocks until the system under test has cancelled the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def terminate(self, response, trailing_metadata, code, details):
- """Terminates the RPC.
-
- Args:
- response: The response for the RPC.
- trailing_metadata: The RPC's trailing metadata.
- code: The RPC's status code.
- details: The RPC's status details.
- """
- raise NotImplementedError()
-
-
-class StreamStreamChannelRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a stream-stream RPC invoked by a system under test.
-
- Enables users to "play server" for the RPC.
- """
-
- @abc.abstractmethod
- def send_initial_metadata(self, initial_metadata):
- """Sends the RPC's initial metadata to the system under test.
-
- Args:
- initial_metadata: The RPC's initial metadata to be "sent" to the
- system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_request(self):
- """Draws one of the requests added to the RPC by the system under test.
-
- This method blocks until the system under test has added to the RPC
- the request to be returned.
-
- Successive calls to this method return requests in the same order in
- which the system under test added them to the RPC.
-
- Returns:
- A request message added to the RPC by the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def send_response(self, response):
- """Sends a response to the system under test.
-
- Args:
- response: A response messages to be "sent" to the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def requests_closed(self):
- """Blocks until the system under test has closed the request stream."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancelled(self):
- """Blocks until the system under test has cancelled the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def terminate(self, trailing_metadata, code, details):
- """Terminates the RPC.
-
- Args:
- trailing_metadata: The RPC's trailing metadata.
- code: The RPC's status code.
- details: The RPC's status details.
- """
- raise NotImplementedError()
-
-
-class Channel(six.with_metaclass(abc.ABCMeta, grpc.Channel)):
- """A grpc.Channel double with which to test a system that invokes RPCs."""
-
- @abc.abstractmethod
- def take_unary_unary(self, method_descriptor):
- """Draws an RPC currently being made by the system under test.
-
- If the given descriptor does not identify any RPC currently being made
- by the system under test, this method blocks until the system under
- test invokes such an RPC.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a
- unary-unary RPC method.
-
- Returns:
- A (invocation_metadata, request, unary_unary_channel_rpc) tuple of
- the RPC's invocation metadata, its request, and a
- UnaryUnaryChannelRpc with which to "play server" for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_unary_stream(self, method_descriptor):
- """Draws an RPC currently being made by the system under test.
-
- If the given descriptor does not identify any RPC currently being made
- by the system under test, this method blocks until the system under
- test invokes such an RPC.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a
- unary-stream RPC method.
-
- Returns:
- A (invocation_metadata, request, unary_stream_channel_rpc) tuple of
- the RPC's invocation metadata, its request, and a
- UnaryStreamChannelRpc with which to "play server" for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_stream_unary(self, method_descriptor):
- """Draws an RPC currently being made by the system under test.
-
- If the given descriptor does not identify any RPC currently being made
- by the system under test, this method blocks until the system under
- test invokes such an RPC.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a
- stream-unary RPC method.
-
- Returns:
- A (invocation_metadata, stream_unary_channel_rpc) tuple of the RPC's
- invocation metadata and a StreamUnaryChannelRpc with which to "play
- server" for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_stream_stream(self, method_descriptor):
- """Draws an RPC currently being made by the system under test.
-
- If the given descriptor does not identify any RPC currently being made
- by the system under test, this method blocks until the system under
- test invokes such an RPC.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a
- stream-stream RPC method.
-
- Returns:
- A (invocation_metadata, stream_stream_channel_rpc) tuple of the RPC's
- invocation metadata and a StreamStreamChannelRpc with which to
- "play server" for the RPC.
- """
- raise NotImplementedError()
-
-
-class UnaryUnaryServerRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a unary-unary RPC serviced by a system under test.
-
- Enables users to "play client" for the RPC.
- """
-
- @abc.abstractmethod
- def initial_metadata(self):
- """Accesses the initial metadata emitted by the system under test.
-
- This method blocks until the system under test has added initial
- metadata to the RPC (or has provided one or more response messages or
- has terminated the RPC, either of which will cause gRPC Python to
- synthesize initial metadata for the RPC).
-
- Returns:
- The initial metadata for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancel(self):
- """Cancels the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def termination(self):
- """Blocks until the system under test has terminated the RPC.
-
- Returns:
- A (response, trailing_metadata, code, details) sequence with the RPC's
- response, trailing metadata, code, and details.
- """
- raise NotImplementedError()
-
-
-class UnaryStreamServerRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a unary-stream RPC serviced by a system under test.
-
- Enables users to "play client" for the RPC.
- """
-
- @abc.abstractmethod
- def initial_metadata(self):
- """Accesses the initial metadata emitted by the system under test.
-
- This method blocks until the system under test has added initial
- metadata to the RPC (or has provided one or more response messages or
- has terminated the RPC, either of which will cause gRPC Python to
- synthesize initial metadata for the RPC).
-
- Returns:
- The initial metadata for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_response(self):
- """Draws one of the responses added to the RPC by the system under test.
-
- Successive calls to this method return responses in the same order in
- which the system under test added them to the RPC.
-
- Returns:
- A response message added to the RPC by the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancel(self):
- """Cancels the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def termination(self):
- """Blocks until the system under test has terminated the RPC.
-
- Returns:
- A (trailing_metadata, code, details) sequence with the RPC's trailing
- metadata, code, and details.
- """
- raise NotImplementedError()
-
-
-class StreamUnaryServerRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a stream-unary RPC serviced by a system under test.
-
- Enables users to "play client" for the RPC.
- """
-
- @abc.abstractmethod
- def initial_metadata(self):
- """Accesses the initial metadata emitted by the system under test.
-
- This method blocks until the system under test has added initial
- metadata to the RPC (or has provided one or more response messages or
- has terminated the RPC, either of which will cause gRPC Python to
- synthesize initial metadata for the RPC).
-
- Returns:
- The initial metadata for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def send_request(self, request):
- """Sends a request to the system under test.
-
- Args:
- request: A request message for the RPC to be "sent" to the system
- under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def requests_closed(self):
- """Indicates the end of the RPC's request stream."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancel(self):
- """Cancels the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def termination(self):
- """Blocks until the system under test has terminated the RPC.
-
- Returns:
- A (response, trailing_metadata, code, details) sequence with the RPC's
- response, trailing metadata, code, and details.
- """
- raise NotImplementedError()
-
-
-class StreamStreamServerRpc(six.with_metaclass(abc.ABCMeta)):
- """Fixture for a stream-stream RPC serviced by a system under test.
-
- Enables users to "play client" for the RPC.
- """
-
- @abc.abstractmethod
- def initial_metadata(self):
- """Accesses the initial metadata emitted by the system under test.
-
- This method blocks until the system under test has added initial
- metadata to the RPC (or has provided one or more response messages or
- has terminated the RPC, either of which will cause gRPC Python to
- synthesize initial metadata for the RPC).
-
- Returns:
- The initial metadata for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def send_request(self, request):
- """Sends a request to the system under test.
-
- Args:
- request: A request message for the RPC to be "sent" to the system
- under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def requests_closed(self):
- """Indicates the end of the RPC's request stream."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_response(self):
- """Draws one of the responses added to the RPC by the system under test.
-
- Successive calls to this method return responses in the same order in
- which the system under test added them to the RPC.
-
- Returns:
- A response message added to the RPC by the system under test.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancel(self):
- """Cancels the RPC."""
- raise NotImplementedError()
-
- @abc.abstractmethod
- def termination(self):
- """Blocks until the system under test has terminated the RPC.
-
- Returns:
- A (trailing_metadata, code, details) sequence with the RPC's trailing
- metadata, code, and details.
- """
- raise NotImplementedError()
-
-
-class Server(six.with_metaclass(abc.ABCMeta)):
- """A server with which to test a system that services RPCs."""
-
- @abc.abstractmethod
- def invoke_unary_unary(self, method_descriptor, invocation_metadata,
- request, timeout):
- """Invokes an RPC to be serviced by the system under test.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a unary-unary
- RPC method.
- invocation_metadata: The RPC's invocation metadata.
- request: The RPC's request.
- timeout: A duration of time in seconds for the RPC or None to
- indicate that the RPC has no time limit.
-
- Returns:
- A UnaryUnaryServerRpc with which to "play client" for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def invoke_unary_stream(self, method_descriptor, invocation_metadata,
- request, timeout):
- """Invokes an RPC to be serviced by the system under test.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a unary-stream
- RPC method.
- invocation_metadata: The RPC's invocation metadata.
- request: The RPC's request.
- timeout: A duration of time in seconds for the RPC or None to
- indicate that the RPC has no time limit.
-
- Returns:
- A UnaryStreamServerRpc with which to "play client" for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def invoke_stream_unary(self, method_descriptor, invocation_metadata,
- timeout):
- """Invokes an RPC to be serviced by the system under test.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a stream-unary
- RPC method.
- invocation_metadata: The RPC's invocation metadata.
- timeout: A duration of time in seconds for the RPC or None to
- indicate that the RPC has no time limit.
-
- Returns:
- A StreamUnaryServerRpc with which to "play client" for the RPC.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def invoke_stream_stream(self, method_descriptor, invocation_metadata,
- timeout):
- """Invokes an RPC to be serviced by the system under test.
-
- Args:
- method_descriptor: A descriptor.MethodDescriptor describing a stream-stream
- RPC method.
- invocation_metadata: The RPC's invocation metadata.
- timeout: A duration of time in seconds for the RPC or None to
- indicate that the RPC has no time limit.
-
- Returns:
- A StreamStreamServerRpc with which to "play client" for the RPC.
- """
- raise NotImplementedError()
-
-
-class Time(six.with_metaclass(abc.ABCMeta)):
- """A simulation of time.
-
- Implementations needn't be connected with real time as provided by the
- Python interpreter, but as long as systems under test use
- RpcContext.is_active and RpcContext.time_remaining for querying RPC liveness
- implementations may be used to change passage of time in tests.
- """
-
- @abc.abstractmethod
- def time(self):
- """Accesses the current test time.
-
- Returns:
- The current test time (over which this object has authority).
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def call_in(self, behavior, delay):
- """Adds a behavior to be called after some time.
-
- Args:
- behavior: A behavior to be called with no arguments.
- delay: A duration of time in seconds after which to call the behavior.
-
- Returns:
- A grpc.Future with which the call of the behavior may be cancelled
- before it is executed.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def call_at(self, behavior, time):
- """Adds a behavior to be called at a specific time.
-
- Args:
- behavior: A behavior to be called with no arguments.
- time: The test time at which to call the behavior.
-
- Returns:
- A grpc.Future with which the call of the behavior may be cancelled
- before it is executed.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def sleep_for(self, duration):
- """Blocks for some length of test time.
-
- Args:
- duration: A duration of test time in seconds for which to block.
- """
- raise NotImplementedError()
-
- @abc.abstractmethod
- def sleep_until(self, time):
- """Blocks until some test time.
-
- Args:
- time: The test time until which to block.
- """
- raise NotImplementedError()
-
-
-def strict_real_time():
- """Creates a Time backed by the Python interpreter's time.
-
- The returned instance will be "strict" with respect to callbacks
- submitted to it: it will ensure that all callbacks registered to
- be called at time t have been called before it describes the time
- as having advanced beyond t.
-
- Returns:
- A Time backed by the "system" (Python interpreter's) time.
- """
- from grpc_testing import _time
- return _time.StrictRealTime()
-
-
-def strict_fake_time(now):
- """Creates a Time that can be manipulated by test code.
-
- The returned instance maintains an internal representation of time
- independent of real time. This internal representation only advances
- when user code calls the instance's sleep_for and sleep_until methods.
-
- The returned instance will be "strict" with respect to callbacks
- submitted to it: it will ensure that all callbacks registered to
- be called at time t have been called before it describes the time
- as having advanced beyond t.
-
- Returns:
- A Time that simulates the passage of time.
- """
- from grpc_testing import _time
- return _time.StrictFakeTime(now)
-
-
-def channel(service_descriptors, time):
- """Creates a Channel for use in tests of a gRPC Python-using system.
-
- Args:
- service_descriptors: An iterable of descriptor.ServiceDescriptors
- describing the RPCs that will be made on the returned Channel by the
- system under test.
- time: A Time to be used for tests.
-
- Returns:
- A Channel for use in tests.
- """
- from grpc_testing import _channel
- return _channel.testing_channel(service_descriptors, time)
-
-
-def server_from_dictionary(descriptors_to_servicers, time):
- """Creates a Server for use in tests of a gRPC Python-using system.
-
- Args:
- descriptors_to_servicers: A dictionary from descriptor.ServiceDescriptors
- defining RPC services to servicer objects (usually instances of classes
- that implement "Servicer" interfaces defined in generated "_pb2_grpc"
- modules) implementing those services.
- time: A Time to be used for tests.
-
- Returns:
- A Server for use in tests.
- """
- from grpc_testing import _server
- return _server.server_from_dictionary(descriptors_to_servicers, time)
+
+from google.protobuf import descriptor
+
+import grpc
+
+
+class UnaryUnaryChannelRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a unary-unary RPC invoked by a system under test.
+
+ Enables users to "play server" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def send_initial_metadata(self, initial_metadata):
+ """Sends the RPC's initial metadata to the system under test.
+
+ Args:
+ initial_metadata: The RPC's initial metadata to be "sent" to
+ the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancelled(self):
+ """Blocks until the system under test has cancelled the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def terminate(self, response, trailing_metadata, code, details):
+ """Terminates the RPC.
+
+ Args:
+ response: The response for the RPC.
+ trailing_metadata: The RPC's trailing metadata.
+ code: The RPC's status code.
+ details: The RPC's status details.
+ """
+ raise NotImplementedError()
+
+
+class UnaryStreamChannelRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a unary-stream RPC invoked by a system under test.
+
+ Enables users to "play server" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def send_initial_metadata(self, initial_metadata):
+ """Sends the RPC's initial metadata to the system under test.
+
+ Args:
+ initial_metadata: The RPC's initial metadata to be "sent" to
+ the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def send_response(self, response):
+ """Sends a response to the system under test.
+
+ Args:
+ response: A response message to be "sent" to the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancelled(self):
+ """Blocks until the system under test has cancelled the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def terminate(self, trailing_metadata, code, details):
+ """Terminates the RPC.
+
+ Args:
+ trailing_metadata: The RPC's trailing metadata.
+ code: The RPC's status code.
+ details: The RPC's status details.
+ """
+ raise NotImplementedError()
+
+
+class StreamUnaryChannelRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a stream-unary RPC invoked by a system under test.
+
+ Enables users to "play server" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def send_initial_metadata(self, initial_metadata):
+ """Sends the RPC's initial metadata to the system under test.
+
+ Args:
+ initial_metadata: The RPC's initial metadata to be "sent" to
+ the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_request(self):
+ """Draws one of the requests added to the RPC by the system under test.
+
+ This method blocks until the system under test has added to the RPC
+ the request to be returned.
+
+ Successive calls to this method return requests in the same order in
+ which the system under test added them to the RPC.
+
+ Returns:
+ A request message added to the RPC by the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def requests_closed(self):
+ """Blocks until the system under test has closed the request stream."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancelled(self):
+ """Blocks until the system under test has cancelled the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def terminate(self, response, trailing_metadata, code, details):
+ """Terminates the RPC.
+
+ Args:
+ response: The response for the RPC.
+ trailing_metadata: The RPC's trailing metadata.
+ code: The RPC's status code.
+ details: The RPC's status details.
+ """
+ raise NotImplementedError()
+
+
+class StreamStreamChannelRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a stream-stream RPC invoked by a system under test.
+
+ Enables users to "play server" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def send_initial_metadata(self, initial_metadata):
+ """Sends the RPC's initial metadata to the system under test.
+
+ Args:
+ initial_metadata: The RPC's initial metadata to be "sent" to the
+ system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_request(self):
+ """Draws one of the requests added to the RPC by the system under test.
+
+ This method blocks until the system under test has added to the RPC
+ the request to be returned.
+
+ Successive calls to this method return requests in the same order in
+ which the system under test added them to the RPC.
+
+ Returns:
+ A request message added to the RPC by the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def send_response(self, response):
+ """Sends a response to the system under test.
+
+ Args:
+ response: A response messages to be "sent" to the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def requests_closed(self):
+ """Blocks until the system under test has closed the request stream."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancelled(self):
+ """Blocks until the system under test has cancelled the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def terminate(self, trailing_metadata, code, details):
+ """Terminates the RPC.
+
+ Args:
+ trailing_metadata: The RPC's trailing metadata.
+ code: The RPC's status code.
+ details: The RPC's status details.
+ """
+ raise NotImplementedError()
+
+
+class Channel(six.with_metaclass(abc.ABCMeta, grpc.Channel)):
+ """A grpc.Channel double with which to test a system that invokes RPCs."""
+
+ @abc.abstractmethod
+ def take_unary_unary(self, method_descriptor):
+ """Draws an RPC currently being made by the system under test.
+
+ If the given descriptor does not identify any RPC currently being made
+ by the system under test, this method blocks until the system under
+ test invokes such an RPC.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a
+ unary-unary RPC method.
+
+ Returns:
+ A (invocation_metadata, request, unary_unary_channel_rpc) tuple of
+ the RPC's invocation metadata, its request, and a
+ UnaryUnaryChannelRpc with which to "play server" for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_unary_stream(self, method_descriptor):
+ """Draws an RPC currently being made by the system under test.
+
+ If the given descriptor does not identify any RPC currently being made
+ by the system under test, this method blocks until the system under
+ test invokes such an RPC.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a
+ unary-stream RPC method.
+
+ Returns:
+ A (invocation_metadata, request, unary_stream_channel_rpc) tuple of
+ the RPC's invocation metadata, its request, and a
+ UnaryStreamChannelRpc with which to "play server" for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_stream_unary(self, method_descriptor):
+ """Draws an RPC currently being made by the system under test.
+
+ If the given descriptor does not identify any RPC currently being made
+ by the system under test, this method blocks until the system under
+ test invokes such an RPC.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a
+ stream-unary RPC method.
+
+ Returns:
+ A (invocation_metadata, stream_unary_channel_rpc) tuple of the RPC's
+ invocation metadata and a StreamUnaryChannelRpc with which to "play
+ server" for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_stream_stream(self, method_descriptor):
+ """Draws an RPC currently being made by the system under test.
+
+ If the given descriptor does not identify any RPC currently being made
+ by the system under test, this method blocks until the system under
+ test invokes such an RPC.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a
+ stream-stream RPC method.
+
+ Returns:
+ A (invocation_metadata, stream_stream_channel_rpc) tuple of the RPC's
+ invocation metadata and a StreamStreamChannelRpc with which to
+ "play server" for the RPC.
+ """
+ raise NotImplementedError()
+
+
+class UnaryUnaryServerRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a unary-unary RPC serviced by a system under test.
+
+ Enables users to "play client" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def initial_metadata(self):
+ """Accesses the initial metadata emitted by the system under test.
+
+ This method blocks until the system under test has added initial
+ metadata to the RPC (or has provided one or more response messages or
+ has terminated the RPC, either of which will cause gRPC Python to
+ synthesize initial metadata for the RPC).
+
+ Returns:
+ The initial metadata for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancel(self):
+ """Cancels the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def termination(self):
+ """Blocks until the system under test has terminated the RPC.
+
+ Returns:
+ A (response, trailing_metadata, code, details) sequence with the RPC's
+ response, trailing metadata, code, and details.
+ """
+ raise NotImplementedError()
+
+
+class UnaryStreamServerRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a unary-stream RPC serviced by a system under test.
+
+ Enables users to "play client" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def initial_metadata(self):
+ """Accesses the initial metadata emitted by the system under test.
+
+ This method blocks until the system under test has added initial
+ metadata to the RPC (or has provided one or more response messages or
+ has terminated the RPC, either of which will cause gRPC Python to
+ synthesize initial metadata for the RPC).
+
+ Returns:
+ The initial metadata for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_response(self):
+ """Draws one of the responses added to the RPC by the system under test.
+
+ Successive calls to this method return responses in the same order in
+ which the system under test added them to the RPC.
+
+ Returns:
+ A response message added to the RPC by the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancel(self):
+ """Cancels the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def termination(self):
+ """Blocks until the system under test has terminated the RPC.
+
+ Returns:
+ A (trailing_metadata, code, details) sequence with the RPC's trailing
+ metadata, code, and details.
+ """
+ raise NotImplementedError()
+
+
+class StreamUnaryServerRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a stream-unary RPC serviced by a system under test.
+
+ Enables users to "play client" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def initial_metadata(self):
+ """Accesses the initial metadata emitted by the system under test.
+
+ This method blocks until the system under test has added initial
+ metadata to the RPC (or has provided one or more response messages or
+ has terminated the RPC, either of which will cause gRPC Python to
+ synthesize initial metadata for the RPC).
+
+ Returns:
+ The initial metadata for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def send_request(self, request):
+ """Sends a request to the system under test.
+
+ Args:
+ request: A request message for the RPC to be "sent" to the system
+ under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def requests_closed(self):
+ """Indicates the end of the RPC's request stream."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancel(self):
+ """Cancels the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def termination(self):
+ """Blocks until the system under test has terminated the RPC.
+
+ Returns:
+ A (response, trailing_metadata, code, details) sequence with the RPC's
+ response, trailing metadata, code, and details.
+ """
+ raise NotImplementedError()
+
+
+class StreamStreamServerRpc(six.with_metaclass(abc.ABCMeta)):
+ """Fixture for a stream-stream RPC serviced by a system under test.
+
+ Enables users to "play client" for the RPC.
+ """
+
+ @abc.abstractmethod
+ def initial_metadata(self):
+ """Accesses the initial metadata emitted by the system under test.
+
+ This method blocks until the system under test has added initial
+ metadata to the RPC (or has provided one or more response messages or
+ has terminated the RPC, either of which will cause gRPC Python to
+ synthesize initial metadata for the RPC).
+
+ Returns:
+ The initial metadata for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def send_request(self, request):
+ """Sends a request to the system under test.
+
+ Args:
+ request: A request message for the RPC to be "sent" to the system
+ under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def requests_closed(self):
+ """Indicates the end of the RPC's request stream."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_response(self):
+ """Draws one of the responses added to the RPC by the system under test.
+
+ Successive calls to this method return responses in the same order in
+ which the system under test added them to the RPC.
+
+ Returns:
+ A response message added to the RPC by the system under test.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancel(self):
+ """Cancels the RPC."""
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def termination(self):
+ """Blocks until the system under test has terminated the RPC.
+
+ Returns:
+ A (trailing_metadata, code, details) sequence with the RPC's trailing
+ metadata, code, and details.
+ """
+ raise NotImplementedError()
+
+
+class Server(six.with_metaclass(abc.ABCMeta)):
+ """A server with which to test a system that services RPCs."""
+
+ @abc.abstractmethod
+ def invoke_unary_unary(self, method_descriptor, invocation_metadata,
+ request, timeout):
+ """Invokes an RPC to be serviced by the system under test.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a unary-unary
+ RPC method.
+ invocation_metadata: The RPC's invocation metadata.
+ request: The RPC's request.
+ timeout: A duration of time in seconds for the RPC or None to
+ indicate that the RPC has no time limit.
+
+ Returns:
+ A UnaryUnaryServerRpc with which to "play client" for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def invoke_unary_stream(self, method_descriptor, invocation_metadata,
+ request, timeout):
+ """Invokes an RPC to be serviced by the system under test.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a unary-stream
+ RPC method.
+ invocation_metadata: The RPC's invocation metadata.
+ request: The RPC's request.
+ timeout: A duration of time in seconds for the RPC or None to
+ indicate that the RPC has no time limit.
+
+ Returns:
+ A UnaryStreamServerRpc with which to "play client" for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def invoke_stream_unary(self, method_descriptor, invocation_metadata,
+ timeout):
+ """Invokes an RPC to be serviced by the system under test.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a stream-unary
+ RPC method.
+ invocation_metadata: The RPC's invocation metadata.
+ timeout: A duration of time in seconds for the RPC or None to
+ indicate that the RPC has no time limit.
+
+ Returns:
+ A StreamUnaryServerRpc with which to "play client" for the RPC.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def invoke_stream_stream(self, method_descriptor, invocation_metadata,
+ timeout):
+ """Invokes an RPC to be serviced by the system under test.
+
+ Args:
+ method_descriptor: A descriptor.MethodDescriptor describing a stream-stream
+ RPC method.
+ invocation_metadata: The RPC's invocation metadata.
+ timeout: A duration of time in seconds for the RPC or None to
+ indicate that the RPC has no time limit.
+
+ Returns:
+ A StreamStreamServerRpc with which to "play client" for the RPC.
+ """
+ raise NotImplementedError()
+
+
+class Time(six.with_metaclass(abc.ABCMeta)):
+ """A simulation of time.
+
+ Implementations needn't be connected with real time as provided by the
+ Python interpreter, but as long as systems under test use
+ RpcContext.is_active and RpcContext.time_remaining for querying RPC liveness
+ implementations may be used to change passage of time in tests.
+ """
+
+ @abc.abstractmethod
+ def time(self):
+ """Accesses the current test time.
+
+ Returns:
+ The current test time (over which this object has authority).
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def call_in(self, behavior, delay):
+ """Adds a behavior to be called after some time.
+
+ Args:
+ behavior: A behavior to be called with no arguments.
+ delay: A duration of time in seconds after which to call the behavior.
+
+ Returns:
+ A grpc.Future with which the call of the behavior may be cancelled
+ before it is executed.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def call_at(self, behavior, time):
+ """Adds a behavior to be called at a specific time.
+
+ Args:
+ behavior: A behavior to be called with no arguments.
+ time: The test time at which to call the behavior.
+
+ Returns:
+ A grpc.Future with which the call of the behavior may be cancelled
+ before it is executed.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def sleep_for(self, duration):
+ """Blocks for some length of test time.
+
+ Args:
+ duration: A duration of test time in seconds for which to block.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def sleep_until(self, time):
+ """Blocks until some test time.
+
+ Args:
+ time: The test time until which to block.
+ """
+ raise NotImplementedError()
+
+
+def strict_real_time():
+ """Creates a Time backed by the Python interpreter's time.
+
+ The returned instance will be "strict" with respect to callbacks
+ submitted to it: it will ensure that all callbacks registered to
+ be called at time t have been called before it describes the time
+ as having advanced beyond t.
+
+ Returns:
+ A Time backed by the "system" (Python interpreter's) time.
+ """
+ from grpc_testing import _time
+ return _time.StrictRealTime()
+
+
+def strict_fake_time(now):
+ """Creates a Time that can be manipulated by test code.
+
+ The returned instance maintains an internal representation of time
+ independent of real time. This internal representation only advances
+ when user code calls the instance's sleep_for and sleep_until methods.
+
+ The returned instance will be "strict" with respect to callbacks
+ submitted to it: it will ensure that all callbacks registered to
+ be called at time t have been called before it describes the time
+ as having advanced beyond t.
+
+ Returns:
+ A Time that simulates the passage of time.
+ """
+ from grpc_testing import _time
+ return _time.StrictFakeTime(now)
+
+
+def channel(service_descriptors, time):
+ """Creates a Channel for use in tests of a gRPC Python-using system.
+
+ Args:
+ service_descriptors: An iterable of descriptor.ServiceDescriptors
+ describing the RPCs that will be made on the returned Channel by the
+ system under test.
+ time: A Time to be used for tests.
+
+ Returns:
+ A Channel for use in tests.
+ """
+ from grpc_testing import _channel
+ return _channel.testing_channel(service_descriptors, time)
+
+
+def server_from_dictionary(descriptors_to_servicers, time):
+ """Creates a Server for use in tests of a gRPC Python-using system.
+
+ Args:
+ descriptors_to_servicers: A dictionary from descriptor.ServiceDescriptors
+ defining RPC services to servicer objects (usually instances of classes
+ that implement "Servicer" interfaces defined in generated "_pb2_grpc"
+ modules) implementing those services.
+ time: A Time to be used for tests.
+
+ Returns:
+ A Server for use in tests.
+ """
+ from grpc_testing import _server
+ return _server.server_from_dictionary(descriptors_to_servicers, time)
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/__init__.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/__init__.py
index 7a64cda889a..ad1dc25f5b6 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/__init__.py
@@ -1,25 +1,25 @@
-# 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 grpc_testing._channel import _channel
-from grpc_testing._channel import _channel_state
-
-
-# descriptors is reserved for later use.
-# pylint: disable=unused-argument
-def testing_channel(descriptors, time):
- return _channel.TestingChannel(time, _channel_state.State())
-
-
-# pylint: enable=unused-argument
+# 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 grpc_testing._channel import _channel
+from grpc_testing._channel import _channel_state
+
+
+# descriptors is reserved for later use.
+# pylint: disable=unused-argument
+def testing_channel(descriptors, time):
+ return _channel.TestingChannel(time, _channel_state.State())
+
+
+# pylint: enable=unused-argument
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel.py
index 0c1941e6bea..e4ad66c5cbd 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel.py
@@ -1,87 +1,87 @@
-# 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 grpc_testing._channel import _channel_rpc
-from grpc_testing._channel import _multi_callable
-
-
-# All serializer and deserializer parameters are not (yet) used by this
-# test infrastructure.
-# pylint: disable=unused-argument
-class TestingChannel(grpc_testing.Channel):
-
- def __init__(self, time, state):
- self._time = time
- self._state = state
-
- def subscribe(self, callback, try_to_connect=False):
- raise NotImplementedError()
-
- def unsubscribe(self, callback):
- raise NotImplementedError()
-
- def unary_unary(self,
- method,
- request_serializer=None,
- response_deserializer=None):
- return _multi_callable.UnaryUnary(method, self._state)
-
- def unary_stream(self,
- method,
- request_serializer=None,
- response_deserializer=None):
- return _multi_callable.UnaryStream(method, self._state)
-
- def stream_unary(self,
- method,
- request_serializer=None,
- response_deserializer=None):
- return _multi_callable.StreamUnary(method, self._state)
-
- def stream_stream(self,
- method,
- request_serializer=None,
- response_deserializer=None):
- return _multi_callable.StreamStream(method, self._state)
-
- def _close(self):
- # TODO(https://github.com/grpc/grpc/issues/12531): Decide what
- # action to take here, if any?
- pass
-
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- self._close()
- return False
-
- def close(self):
- self._close()
-
- def take_unary_unary(self, method_descriptor):
- return _channel_rpc.unary_unary(self._state, method_descriptor)
-
- def take_unary_stream(self, method_descriptor):
- return _channel_rpc.unary_stream(self._state, method_descriptor)
-
- def take_stream_unary(self, method_descriptor):
- return _channel_rpc.stream_unary(self._state, method_descriptor)
-
- def take_stream_stream(self, method_descriptor):
- return _channel_rpc.stream_stream(self._state, method_descriptor)
-
-
-# pylint: enable=unused-argument
+# 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 grpc_testing._channel import _channel_rpc
+from grpc_testing._channel import _multi_callable
+
+
+# All serializer and deserializer parameters are not (yet) used by this
+# test infrastructure.
+# pylint: disable=unused-argument
+class TestingChannel(grpc_testing.Channel):
+
+ def __init__(self, time, state):
+ self._time = time
+ self._state = state
+
+ def subscribe(self, callback, try_to_connect=False):
+ raise NotImplementedError()
+
+ def unsubscribe(self, callback):
+ raise NotImplementedError()
+
+ def unary_unary(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ return _multi_callable.UnaryUnary(method, self._state)
+
+ def unary_stream(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ return _multi_callable.UnaryStream(method, self._state)
+
+ def stream_unary(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ return _multi_callable.StreamUnary(method, self._state)
+
+ def stream_stream(self,
+ method,
+ request_serializer=None,
+ response_deserializer=None):
+ return _multi_callable.StreamStream(method, self._state)
+
+ def _close(self):
+ # TODO(https://github.com/grpc/grpc/issues/12531): Decide what
+ # action to take here, if any?
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self._close()
+ return False
+
+ def close(self):
+ self._close()
+
+ def take_unary_unary(self, method_descriptor):
+ return _channel_rpc.unary_unary(self._state, method_descriptor)
+
+ def take_unary_stream(self, method_descriptor):
+ return _channel_rpc.unary_stream(self._state, method_descriptor)
+
+ def take_stream_unary(self, method_descriptor):
+ return _channel_rpc.stream_unary(self._state, method_descriptor)
+
+ def take_stream_stream(self, method_descriptor):
+ return _channel_rpc.stream_stream(self._state, method_descriptor)
+
+
+# pylint: enable=unused-argument
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_rpc.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_rpc.py
index 54499b3b55f..bfb35d07584 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_rpc.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_rpc.py
@@ -1,119 +1,119 @@
-# 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
-
-
-class _UnaryUnary(grpc_testing.UnaryUnaryChannelRpc):
-
- def __init__(self, rpc_state):
- self._rpc_state = rpc_state
-
- def send_initial_metadata(self, initial_metadata):
- self._rpc_state.send_initial_metadata(initial_metadata)
-
- def cancelled(self):
- self._rpc_state.cancelled()
-
- def terminate(self, response, trailing_metadata, code, details):
- self._rpc_state.terminate_with_response(response, trailing_metadata,
- code, details)
-
-
-class _UnaryStream(grpc_testing.UnaryStreamChannelRpc):
-
- def __init__(self, rpc_state):
- self._rpc_state = rpc_state
-
- def send_initial_metadata(self, initial_metadata):
- self._rpc_state.send_initial_metadata(initial_metadata)
-
- def send_response(self, response):
- self._rpc_state.send_response(response)
-
- def cancelled(self):
- self._rpc_state.cancelled()
-
- def terminate(self, trailing_metadata, code, details):
- self._rpc_state.terminate(trailing_metadata, code, details)
-
-
-class _StreamUnary(grpc_testing.StreamUnaryChannelRpc):
-
- def __init__(self, rpc_state):
- self._rpc_state = rpc_state
-
- def send_initial_metadata(self, initial_metadata):
- self._rpc_state.send_initial_metadata(initial_metadata)
-
- def take_request(self):
- return self._rpc_state.take_request()
-
- def requests_closed(self):
- return self._rpc_state.requests_closed()
-
- def cancelled(self):
- self._rpc_state.cancelled()
-
- def terminate(self, response, trailing_metadata, code, details):
- self._rpc_state.terminate_with_response(response, trailing_metadata,
- code, details)
-
-
-class _StreamStream(grpc_testing.StreamStreamChannelRpc):
-
- def __init__(self, rpc_state):
- self._rpc_state = rpc_state
-
- def send_initial_metadata(self, initial_metadata):
- self._rpc_state.send_initial_metadata(initial_metadata)
-
- def take_request(self):
- return self._rpc_state.take_request()
-
- def send_response(self, response):
- self._rpc_state.send_response(response)
-
- def requests_closed(self):
- return self._rpc_state.requests_closed()
-
- def cancelled(self):
- self._rpc_state.cancelled()
-
- def terminate(self, trailing_metadata, code, details):
- self._rpc_state.terminate(trailing_metadata, code, details)
-
-
-def unary_unary(channel_state, method_descriptor):
- rpc_state = channel_state.take_rpc_state(method_descriptor)
- invocation_metadata, request = (
- rpc_state.take_invocation_metadata_and_request())
- return invocation_metadata, request, _UnaryUnary(rpc_state)
-
-
-def unary_stream(channel_state, method_descriptor):
- rpc_state = channel_state.take_rpc_state(method_descriptor)
- invocation_metadata, request = (
- rpc_state.take_invocation_metadata_and_request())
- return invocation_metadata, request, _UnaryStream(rpc_state)
-
-
-def stream_unary(channel_state, method_descriptor):
- rpc_state = channel_state.take_rpc_state(method_descriptor)
- return rpc_state.take_invocation_metadata(), _StreamUnary(rpc_state)
-
-
-def stream_stream(channel_state, method_descriptor):
- rpc_state = channel_state.take_rpc_state(method_descriptor)
- return rpc_state.take_invocation_metadata(), _StreamStream(rpc_state)
+# 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
+
+
+class _UnaryUnary(grpc_testing.UnaryUnaryChannelRpc):
+
+ def __init__(self, rpc_state):
+ self._rpc_state = rpc_state
+
+ def send_initial_metadata(self, initial_metadata):
+ self._rpc_state.send_initial_metadata(initial_metadata)
+
+ def cancelled(self):
+ self._rpc_state.cancelled()
+
+ def terminate(self, response, trailing_metadata, code, details):
+ self._rpc_state.terminate_with_response(response, trailing_metadata,
+ code, details)
+
+
+class _UnaryStream(grpc_testing.UnaryStreamChannelRpc):
+
+ def __init__(self, rpc_state):
+ self._rpc_state = rpc_state
+
+ def send_initial_metadata(self, initial_metadata):
+ self._rpc_state.send_initial_metadata(initial_metadata)
+
+ def send_response(self, response):
+ self._rpc_state.send_response(response)
+
+ def cancelled(self):
+ self._rpc_state.cancelled()
+
+ def terminate(self, trailing_metadata, code, details):
+ self._rpc_state.terminate(trailing_metadata, code, details)
+
+
+class _StreamUnary(grpc_testing.StreamUnaryChannelRpc):
+
+ def __init__(self, rpc_state):
+ self._rpc_state = rpc_state
+
+ def send_initial_metadata(self, initial_metadata):
+ self._rpc_state.send_initial_metadata(initial_metadata)
+
+ def take_request(self):
+ return self._rpc_state.take_request()
+
+ def requests_closed(self):
+ return self._rpc_state.requests_closed()
+
+ def cancelled(self):
+ self._rpc_state.cancelled()
+
+ def terminate(self, response, trailing_metadata, code, details):
+ self._rpc_state.terminate_with_response(response, trailing_metadata,
+ code, details)
+
+
+class _StreamStream(grpc_testing.StreamStreamChannelRpc):
+
+ def __init__(self, rpc_state):
+ self._rpc_state = rpc_state
+
+ def send_initial_metadata(self, initial_metadata):
+ self._rpc_state.send_initial_metadata(initial_metadata)
+
+ def take_request(self):
+ return self._rpc_state.take_request()
+
+ def send_response(self, response):
+ self._rpc_state.send_response(response)
+
+ def requests_closed(self):
+ return self._rpc_state.requests_closed()
+
+ def cancelled(self):
+ self._rpc_state.cancelled()
+
+ def terminate(self, trailing_metadata, code, details):
+ self._rpc_state.terminate(trailing_metadata, code, details)
+
+
+def unary_unary(channel_state, method_descriptor):
+ rpc_state = channel_state.take_rpc_state(method_descriptor)
+ invocation_metadata, request = (
+ rpc_state.take_invocation_metadata_and_request())
+ return invocation_metadata, request, _UnaryUnary(rpc_state)
+
+
+def unary_stream(channel_state, method_descriptor):
+ rpc_state = channel_state.take_rpc_state(method_descriptor)
+ invocation_metadata, request = (
+ rpc_state.take_invocation_metadata_and_request())
+ return invocation_metadata, request, _UnaryStream(rpc_state)
+
+
+def stream_unary(channel_state, method_descriptor):
+ rpc_state = channel_state.take_rpc_state(method_descriptor)
+ return rpc_state.take_invocation_metadata(), _StreamUnary(rpc_state)
+
+
+def stream_stream(channel_state, method_descriptor):
+ rpc_state = channel_state.take_rpc_state(method_descriptor)
+ return rpc_state.take_invocation_metadata(), _StreamStream(rpc_state)
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_state.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_state.py
index 779d59e59ad..2095e01b972 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_state.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_channel_state.py
@@ -1,47 +1,47 @@
-# 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 collections
-import threading
-
-from grpc_testing import _common
-from grpc_testing._channel import _rpc_state
-
-
-class State(_common.ChannelHandler):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._rpc_states = collections.defaultdict(list)
-
- def invoke_rpc(self, method_full_rpc_name, invocation_metadata, requests,
- requests_closed, timeout):
- rpc_state = _rpc_state.State(invocation_metadata, requests,
- requests_closed)
- with self._condition:
- self._rpc_states[method_full_rpc_name].append(rpc_state)
- self._condition.notify_all()
- return rpc_state
-
- def take_rpc_state(self, method_descriptor):
- method_full_rpc_name = '/{}/{}'.format(
- method_descriptor.containing_service.full_name,
- method_descriptor.name)
- with self._condition:
- while True:
- method_rpc_states = self._rpc_states[method_full_rpc_name]
- if method_rpc_states:
- return method_rpc_states.pop(0)
- else:
- self._condition.wait()
+# 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 collections
+import threading
+
+from grpc_testing import _common
+from grpc_testing._channel import _rpc_state
+
+
+class State(_common.ChannelHandler):
+
+ def __init__(self):
+ self._condition = threading.Condition()
+ self._rpc_states = collections.defaultdict(list)
+
+ def invoke_rpc(self, method_full_rpc_name, invocation_metadata, requests,
+ requests_closed, timeout):
+ rpc_state = _rpc_state.State(invocation_metadata, requests,
+ requests_closed)
+ with self._condition:
+ self._rpc_states[method_full_rpc_name].append(rpc_state)
+ self._condition.notify_all()
+ return rpc_state
+
+ def take_rpc_state(self, method_descriptor):
+ method_full_rpc_name = '/{}/{}'.format(
+ method_descriptor.containing_service.full_name,
+ method_descriptor.name)
+ with self._condition:
+ while True:
+ method_rpc_states = self._rpc_states[method_full_rpc_name]
+ if method_rpc_states:
+ return method_rpc_states.pop(0)
+ else:
+ self._condition.wait()
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py
index d7205ca5793..a9aa242ab19 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py
@@ -1,324 +1,324 @@
-# 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 logging
-import threading
-
-import grpc
-
-_NOT_YET_OBSERVED = object()
+# 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 logging
+import threading
+
+import grpc
+
+_NOT_YET_OBSERVED = object()
logging.basicConfig()
_LOGGER = logging.getLogger(__name__)
-
-
-def _cancel(handler):
- return handler.cancel(grpc.StatusCode.CANCELLED, 'Locally cancelled!')
-
-
-def _is_active(handler):
- return handler.is_active()
-
-
-def _time_remaining(unused_handler):
- raise NotImplementedError()
-
-
-def _add_callback(handler, callback):
- return handler.add_callback(callback)
-
-
-def _initial_metadata(handler):
- return handler.initial_metadata()
-
-
-def _trailing_metadata(handler):
- trailing_metadata, unused_code, unused_details = handler.termination()
- return trailing_metadata
-
-
-def _code(handler):
- unused_trailing_metadata, code, unused_details = handler.termination()
- return code
-
-
-def _details(handler):
- unused_trailing_metadata, unused_code, details = handler.termination()
- return details
-
-
-class _Call(grpc.Call):
-
- def __init__(self, handler):
- self._handler = handler
-
- def cancel(self):
- _cancel(self._handler)
-
- def is_active(self):
- return _is_active(self._handler)
-
- def time_remaining(self):
- return _time_remaining(self._handler)
-
- def add_callback(self, callback):
- return _add_callback(self._handler, callback)
-
- def initial_metadata(self):
- return _initial_metadata(self._handler)
-
- def trailing_metadata(self):
- return _trailing_metadata(self._handler)
-
- def code(self):
- return _code(self._handler)
-
- def details(self):
- return _details(self._handler)
-
-
-class _RpcErrorCall(grpc.RpcError, grpc.Call):
-
- def __init__(self, handler):
- self._handler = handler
-
- def cancel(self):
- _cancel(self._handler)
-
- def is_active(self):
- return _is_active(self._handler)
-
- def time_remaining(self):
- return _time_remaining(self._handler)
-
- def add_callback(self, callback):
- return _add_callback(self._handler, callback)
-
- def initial_metadata(self):
- return _initial_metadata(self._handler)
-
- def trailing_metadata(self):
- return _trailing_metadata(self._handler)
-
- def code(self):
- return _code(self._handler)
-
- def details(self):
- return _details(self._handler)
-
-
-def _next(handler):
- read = handler.take_response()
- if read.code is None:
- return read.response
- elif read.code is grpc.StatusCode.OK:
- raise StopIteration()
- else:
- raise _RpcErrorCall(handler)
-
-
-class _HandlerExtras(object):
-
- def __init__(self):
- self.condition = threading.Condition()
- self.unary_response = _NOT_YET_OBSERVED
- self.cancelled = False
-
-
-def _with_extras_cancel(handler, extras):
- with extras.condition:
- if handler.cancel(grpc.StatusCode.CANCELLED, 'Locally cancelled!'):
- extras.cancelled = True
- return True
- else:
- return False
-
-
-def _extras_without_cancelled(extras):
- with extras.condition:
- return extras.cancelled
-
-
-def _running(handler):
- return handler.is_active()
-
-
-def _done(handler):
- return not handler.is_active()
-
-
-def _with_extras_unary_response(handler, extras):
- with extras.condition:
- if extras.unary_response is _NOT_YET_OBSERVED:
- read = handler.take_response()
- if read.code is None:
- extras.unary_response = read.response
- return read.response
- else:
- raise _RpcErrorCall(handler)
- else:
- return extras.unary_response
-
-
-def _exception(unused_handler):
- raise NotImplementedError('TODO!')
-
-
-def _traceback(unused_handler):
- raise NotImplementedError('TODO!')
-
-
-def _add_done_callback(handler, callback, future):
- adapted_callback = lambda: callback(future)
- if not handler.add_callback(adapted_callback):
- callback(future)
-
-
-class _FutureCall(grpc.Future, grpc.Call):
-
- def __init__(self, handler, extras):
- self._handler = handler
- self._extras = extras
-
- def cancel(self):
- return _with_extras_cancel(self._handler, self._extras)
-
- def cancelled(self):
- return _extras_without_cancelled(self._extras)
-
- def running(self):
- return _running(self._handler)
-
- def done(self):
- return _done(self._handler)
-
- def result(self):
- return _with_extras_unary_response(self._handler, self._extras)
-
- def exception(self):
- return _exception(self._handler)
-
- def traceback(self):
- return _traceback(self._handler)
-
- def add_done_callback(self, fn):
- _add_done_callback(self._handler, fn, self)
-
- def is_active(self):
- return _is_active(self._handler)
-
- def time_remaining(self):
- return _time_remaining(self._handler)
-
- def add_callback(self, callback):
- return _add_callback(self._handler, callback)
-
- def initial_metadata(self):
- return _initial_metadata(self._handler)
-
- def trailing_metadata(self):
- return _trailing_metadata(self._handler)
-
- def code(self):
- return _code(self._handler)
-
- def details(self):
- return _details(self._handler)
-
-
-def consume_requests(request_iterator, handler):
-
- def _consume():
- while True:
- try:
- request = next(request_iterator)
- added = handler.add_request(request)
- if not added:
- break
- except StopIteration:
- handler.close_requests()
- break
- except Exception: # pylint: disable=broad-except
- details = 'Exception iterating requests!'
+
+
+def _cancel(handler):
+ return handler.cancel(grpc.StatusCode.CANCELLED, 'Locally cancelled!')
+
+
+def _is_active(handler):
+ return handler.is_active()
+
+
+def _time_remaining(unused_handler):
+ raise NotImplementedError()
+
+
+def _add_callback(handler, callback):
+ return handler.add_callback(callback)
+
+
+def _initial_metadata(handler):
+ return handler.initial_metadata()
+
+
+def _trailing_metadata(handler):
+ trailing_metadata, unused_code, unused_details = handler.termination()
+ return trailing_metadata
+
+
+def _code(handler):
+ unused_trailing_metadata, code, unused_details = handler.termination()
+ return code
+
+
+def _details(handler):
+ unused_trailing_metadata, unused_code, details = handler.termination()
+ return details
+
+
+class _Call(grpc.Call):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def cancel(self):
+ _cancel(self._handler)
+
+ def is_active(self):
+ return _is_active(self._handler)
+
+ def time_remaining(self):
+ return _time_remaining(self._handler)
+
+ def add_callback(self, callback):
+ return _add_callback(self._handler, callback)
+
+ def initial_metadata(self):
+ return _initial_metadata(self._handler)
+
+ def trailing_metadata(self):
+ return _trailing_metadata(self._handler)
+
+ def code(self):
+ return _code(self._handler)
+
+ def details(self):
+ return _details(self._handler)
+
+
+class _RpcErrorCall(grpc.RpcError, grpc.Call):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def cancel(self):
+ _cancel(self._handler)
+
+ def is_active(self):
+ return _is_active(self._handler)
+
+ def time_remaining(self):
+ return _time_remaining(self._handler)
+
+ def add_callback(self, callback):
+ return _add_callback(self._handler, callback)
+
+ def initial_metadata(self):
+ return _initial_metadata(self._handler)
+
+ def trailing_metadata(self):
+ return _trailing_metadata(self._handler)
+
+ def code(self):
+ return _code(self._handler)
+
+ def details(self):
+ return _details(self._handler)
+
+
+def _next(handler):
+ read = handler.take_response()
+ if read.code is None:
+ return read.response
+ elif read.code is grpc.StatusCode.OK:
+ raise StopIteration()
+ else:
+ raise _RpcErrorCall(handler)
+
+
+class _HandlerExtras(object):
+
+ def __init__(self):
+ self.condition = threading.Condition()
+ self.unary_response = _NOT_YET_OBSERVED
+ self.cancelled = False
+
+
+def _with_extras_cancel(handler, extras):
+ with extras.condition:
+ if handler.cancel(grpc.StatusCode.CANCELLED, 'Locally cancelled!'):
+ extras.cancelled = True
+ return True
+ else:
+ return False
+
+
+def _extras_without_cancelled(extras):
+ with extras.condition:
+ return extras.cancelled
+
+
+def _running(handler):
+ return handler.is_active()
+
+
+def _done(handler):
+ return not handler.is_active()
+
+
+def _with_extras_unary_response(handler, extras):
+ with extras.condition:
+ if extras.unary_response is _NOT_YET_OBSERVED:
+ read = handler.take_response()
+ if read.code is None:
+ extras.unary_response = read.response
+ return read.response
+ else:
+ raise _RpcErrorCall(handler)
+ else:
+ return extras.unary_response
+
+
+def _exception(unused_handler):
+ raise NotImplementedError('TODO!')
+
+
+def _traceback(unused_handler):
+ raise NotImplementedError('TODO!')
+
+
+def _add_done_callback(handler, callback, future):
+ adapted_callback = lambda: callback(future)
+ if not handler.add_callback(adapted_callback):
+ callback(future)
+
+
+class _FutureCall(grpc.Future, grpc.Call):
+
+ def __init__(self, handler, extras):
+ self._handler = handler
+ self._extras = extras
+
+ def cancel(self):
+ return _with_extras_cancel(self._handler, self._extras)
+
+ def cancelled(self):
+ return _extras_without_cancelled(self._extras)
+
+ def running(self):
+ return _running(self._handler)
+
+ def done(self):
+ return _done(self._handler)
+
+ def result(self):
+ return _with_extras_unary_response(self._handler, self._extras)
+
+ def exception(self):
+ return _exception(self._handler)
+
+ def traceback(self):
+ return _traceback(self._handler)
+
+ def add_done_callback(self, fn):
+ _add_done_callback(self._handler, fn, self)
+
+ def is_active(self):
+ return _is_active(self._handler)
+
+ def time_remaining(self):
+ return _time_remaining(self._handler)
+
+ def add_callback(self, callback):
+ return _add_callback(self._handler, callback)
+
+ def initial_metadata(self):
+ return _initial_metadata(self._handler)
+
+ def trailing_metadata(self):
+ return _trailing_metadata(self._handler)
+
+ def code(self):
+ return _code(self._handler)
+
+ def details(self):
+ return _details(self._handler)
+
+
+def consume_requests(request_iterator, handler):
+
+ def _consume():
+ while True:
+ try:
+ request = next(request_iterator)
+ added = handler.add_request(request)
+ if not added:
+ break
+ except StopIteration:
+ handler.close_requests()
+ break
+ except Exception: # pylint: disable=broad-except
+ details = 'Exception iterating requests!'
_LOGGER.exception(details)
- handler.cancel(grpc.StatusCode.UNKNOWN, details)
-
- consumption = threading.Thread(target=_consume)
- consumption.start()
-
-
-def blocking_unary_response(handler):
- read = handler.take_response()
- if read.code is None:
- unused_trailing_metadata, code, unused_details = handler.termination()
- if code is grpc.StatusCode.OK:
- return read.response
- else:
- raise _RpcErrorCall(handler)
- else:
- raise _RpcErrorCall(handler)
-
-
-def blocking_unary_response_with_call(handler):
- read = handler.take_response()
- if read.code is None:
- unused_trailing_metadata, code, unused_details = handler.termination()
- if code is grpc.StatusCode.OK:
- return read.response, _Call(handler)
- else:
- raise _RpcErrorCall(handler)
- else:
- raise _RpcErrorCall(handler)
-
-
-def future_call(handler):
- return _FutureCall(handler, _HandlerExtras())
-
-
-class ResponseIteratorCall(grpc.Call):
-
- def __init__(self, handler):
- self._handler = handler
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return _next(self._handler)
-
- def next(self):
- return _next(self._handler)
-
- def cancel(self):
- _cancel(self._handler)
-
- def is_active(self):
- return _is_active(self._handler)
-
- def time_remaining(self):
- return _time_remaining(self._handler)
-
- def add_callback(self, callback):
- return _add_callback(self._handler, callback)
-
- def initial_metadata(self):
- return _initial_metadata(self._handler)
-
- def trailing_metadata(self):
- return _trailing_metadata(self._handler)
-
- def code(self):
- return _code(self._handler)
-
- def details(self):
- return _details(self._handler)
+ handler.cancel(grpc.StatusCode.UNKNOWN, details)
+
+ consumption = threading.Thread(target=_consume)
+ consumption.start()
+
+
+def blocking_unary_response(handler):
+ read = handler.take_response()
+ if read.code is None:
+ unused_trailing_metadata, code, unused_details = handler.termination()
+ if code is grpc.StatusCode.OK:
+ return read.response
+ else:
+ raise _RpcErrorCall(handler)
+ else:
+ raise _RpcErrorCall(handler)
+
+
+def blocking_unary_response_with_call(handler):
+ read = handler.take_response()
+ if read.code is None:
+ unused_trailing_metadata, code, unused_details = handler.termination()
+ if code is grpc.StatusCode.OK:
+ return read.response, _Call(handler)
+ else:
+ raise _RpcErrorCall(handler)
+ else:
+ raise _RpcErrorCall(handler)
+
+
+def future_call(handler):
+ return _FutureCall(handler, _HandlerExtras())
+
+
+class ResponseIteratorCall(grpc.Call):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return _next(self._handler)
+
+ def next(self):
+ return _next(self._handler)
+
+ def cancel(self):
+ _cancel(self._handler)
+
+ def is_active(self):
+ return _is_active(self._handler)
+
+ def time_remaining(self):
+ return _time_remaining(self._handler)
+
+ def add_callback(self, callback):
+ return _add_callback(self._handler, callback)
+
+ def initial_metadata(self):
+ return _initial_metadata(self._handler)
+
+ def trailing_metadata(self):
+ return _trailing_metadata(self._handler)
+
+ def code(self):
+ return _code(self._handler)
+
+ def details(self):
+ return _details(self._handler)
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_multi_callable.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_multi_callable.py
index 2b2f5761f56..e5558643958 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_multi_callable.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_multi_callable.py
@@ -1,118 +1,118 @@
-# 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
-from grpc_testing import _common
-from grpc_testing._channel import _invocation
-
-
-# All per-call credentials parameters are unused by this test infrastructure.
-# pylint: disable=unused-argument
-class UnaryUnary(grpc.UnaryUnaryMultiCallable):
-
- def __init__(self, method_full_rpc_name, channel_handler):
- self._method_full_rpc_name = method_full_rpc_name
- self._channel_handler = channel_handler
-
- def __call__(self, request, timeout=None, metadata=None, credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [request], True, timeout)
- return _invocation.blocking_unary_response(rpc_handler)
-
- def with_call(self, request, timeout=None, metadata=None, credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [request], True, timeout)
- return _invocation.blocking_unary_response_with_call(rpc_handler)
-
- def future(self, request, timeout=None, metadata=None, credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [request], True, timeout)
- return _invocation.future_call(rpc_handler)
-
-
-class UnaryStream(grpc.StreamStreamMultiCallable):
-
- def __init__(self, method_full_rpc_name, channel_handler):
- self._method_full_rpc_name = method_full_rpc_name
- self._channel_handler = channel_handler
-
- def __call__(self, request, timeout=None, metadata=None, credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [request], True, timeout)
- return _invocation.ResponseIteratorCall(rpc_handler)
-
-
-class StreamUnary(grpc.StreamUnaryMultiCallable):
-
- def __init__(self, method_full_rpc_name, channel_handler):
- self._method_full_rpc_name = method_full_rpc_name
- self._channel_handler = channel_handler
-
- def __call__(self,
- request_iterator,
- timeout=None,
- metadata=None,
- credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [], False, timeout)
- _invocation.consume_requests(request_iterator, rpc_handler)
- return _invocation.blocking_unary_response(rpc_handler)
-
- def with_call(self,
- request_iterator,
- timeout=None,
- metadata=None,
- credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [], False, timeout)
- _invocation.consume_requests(request_iterator, rpc_handler)
- return _invocation.blocking_unary_response_with_call(rpc_handler)
-
- def future(self,
- request_iterator,
- timeout=None,
- metadata=None,
- credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [], False, timeout)
- _invocation.consume_requests(request_iterator, rpc_handler)
- return _invocation.future_call(rpc_handler)
-
-
-class StreamStream(grpc.StreamStreamMultiCallable):
-
- def __init__(self, method_full_rpc_name, channel_handler):
- self._method_full_rpc_name = method_full_rpc_name
- self._channel_handler = channel_handler
-
- def __call__(self,
- request_iterator,
- timeout=None,
- metadata=None,
- credentials=None):
- rpc_handler = self._channel_handler.invoke_rpc(
- self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
- [], False, timeout)
- _invocation.consume_requests(request_iterator, rpc_handler)
- return _invocation.ResponseIteratorCall(rpc_handler)
-
-
-# pylint: enable=unused-argument
+# 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
+from grpc_testing import _common
+from grpc_testing._channel import _invocation
+
+
+# All per-call credentials parameters are unused by this test infrastructure.
+# pylint: disable=unused-argument
+class UnaryUnary(grpc.UnaryUnaryMultiCallable):
+
+ def __init__(self, method_full_rpc_name, channel_handler):
+ self._method_full_rpc_name = method_full_rpc_name
+ self._channel_handler = channel_handler
+
+ def __call__(self, request, timeout=None, metadata=None, credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [request], True, timeout)
+ return _invocation.blocking_unary_response(rpc_handler)
+
+ def with_call(self, request, timeout=None, metadata=None, credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [request], True, timeout)
+ return _invocation.blocking_unary_response_with_call(rpc_handler)
+
+ def future(self, request, timeout=None, metadata=None, credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [request], True, timeout)
+ return _invocation.future_call(rpc_handler)
+
+
+class UnaryStream(grpc.StreamStreamMultiCallable):
+
+ def __init__(self, method_full_rpc_name, channel_handler):
+ self._method_full_rpc_name = method_full_rpc_name
+ self._channel_handler = channel_handler
+
+ def __call__(self, request, timeout=None, metadata=None, credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [request], True, timeout)
+ return _invocation.ResponseIteratorCall(rpc_handler)
+
+
+class StreamUnary(grpc.StreamUnaryMultiCallable):
+
+ def __init__(self, method_full_rpc_name, channel_handler):
+ self._method_full_rpc_name = method_full_rpc_name
+ self._channel_handler = channel_handler
+
+ def __call__(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [], False, timeout)
+ _invocation.consume_requests(request_iterator, rpc_handler)
+ return _invocation.blocking_unary_response(rpc_handler)
+
+ def with_call(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [], False, timeout)
+ _invocation.consume_requests(request_iterator, rpc_handler)
+ return _invocation.blocking_unary_response_with_call(rpc_handler)
+
+ def future(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [], False, timeout)
+ _invocation.consume_requests(request_iterator, rpc_handler)
+ return _invocation.future_call(rpc_handler)
+
+
+class StreamStream(grpc.StreamStreamMultiCallable):
+
+ def __init__(self, method_full_rpc_name, channel_handler):
+ self._method_full_rpc_name = method_full_rpc_name
+ self._channel_handler = channel_handler
+
+ def __call__(self,
+ request_iterator,
+ timeout=None,
+ metadata=None,
+ credentials=None):
+ rpc_handler = self._channel_handler.invoke_rpc(
+ self._method_full_rpc_name, _common.fuss_with_metadata(metadata),
+ [], False, timeout)
+ _invocation.consume_requests(request_iterator, rpc_handler)
+ return _invocation.ResponseIteratorCall(rpc_handler)
+
+
+# pylint: enable=unused-argument
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_rpc_state.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_rpc_state.py
index a548ef0f12e..2d2bf5d81e9 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_rpc_state.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_rpc_state.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.
-
-import threading
-
-import grpc
-from grpc_testing import _common
-
-
-class State(_common.ChannelRpcHandler):
-
- def __init__(self, invocation_metadata, requests, requests_closed):
- self._condition = threading.Condition()
- self._invocation_metadata = invocation_metadata
- self._requests = requests
- self._requests_closed = requests_closed
- self._initial_metadata = None
- self._responses = []
- self._trailing_metadata = None
- self._code = None
- self._details = None
-
- def initial_metadata(self):
- with self._condition:
- while True:
- if self._initial_metadata is None:
- if self._code is None:
- self._condition.wait()
- else:
- return _common.FUSSED_EMPTY_METADATA
- else:
- return self._initial_metadata
-
- def add_request(self, request):
- with self._condition:
- if self._code is None and not self._requests_closed:
- self._requests.append(request)
- self._condition.notify_all()
- return True
- else:
- return False
-
- def close_requests(self):
- with self._condition:
- if self._code is None and not self._requests_closed:
- self._requests_closed = True
- self._condition.notify_all()
-
- def take_response(self):
- with self._condition:
- while True:
- if self._code is grpc.StatusCode.OK:
- if self._responses:
- response = self._responses.pop(0)
- return _common.ChannelRpcRead(response, None, None,
- None)
- else:
+# 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 threading
+
+import grpc
+from grpc_testing import _common
+
+
+class State(_common.ChannelRpcHandler):
+
+ def __init__(self, invocation_metadata, requests, requests_closed):
+ self._condition = threading.Condition()
+ self._invocation_metadata = invocation_metadata
+ self._requests = requests
+ self._requests_closed = requests_closed
+ self._initial_metadata = None
+ self._responses = []
+ self._trailing_metadata = None
+ self._code = None
+ self._details = None
+
+ def initial_metadata(self):
+ with self._condition:
+ while True:
+ if self._initial_metadata is None:
+ if self._code is None:
+ self._condition.wait()
+ else:
+ return _common.FUSSED_EMPTY_METADATA
+ else:
+ return self._initial_metadata
+
+ def add_request(self, request):
+ with self._condition:
+ if self._code is None and not self._requests_closed:
+ self._requests.append(request)
+ self._condition.notify_all()
+ return True
+ else:
+ return False
+
+ def close_requests(self):
+ with self._condition:
+ if self._code is None and not self._requests_closed:
+ self._requests_closed = True
+ self._condition.notify_all()
+
+ def take_response(self):
+ with self._condition:
+ while True:
+ if self._code is grpc.StatusCode.OK:
+ if self._responses:
+ response = self._responses.pop(0)
+ return _common.ChannelRpcRead(response, None, None,
+ None)
+ else:
return _common.ChannelRpcRead(None,
self._trailing_metadata,
grpc.StatusCode.OK,
self._details)
- elif self._code is None:
- if self._responses:
- response = self._responses.pop(0)
- return _common.ChannelRpcRead(response, None, None,
- None)
- else:
- self._condition.wait()
- else:
- return _common.ChannelRpcRead(None, self._trailing_metadata,
- self._code, self._details)
-
- def termination(self):
- with self._condition:
- while True:
- if self._code is None:
- self._condition.wait()
- else:
- return self._trailing_metadata, self._code, self._details
-
- def cancel(self, code, details):
- with self._condition:
- if self._code is None:
- if self._initial_metadata is None:
- self._initial_metadata = _common.FUSSED_EMPTY_METADATA
- self._trailing_metadata = _common.FUSSED_EMPTY_METADATA
- self._code = code
- self._details = details
- self._condition.notify_all()
- return True
- else:
- return False
-
- def take_invocation_metadata(self):
- with self._condition:
- if self._invocation_metadata is None:
- raise ValueError('Expected invocation metadata!')
- else:
- invocation_metadata = self._invocation_metadata
- self._invocation_metadata = None
- return invocation_metadata
-
- def take_invocation_metadata_and_request(self):
- with self._condition:
- if self._invocation_metadata is None:
- raise ValueError('Expected invocation metadata!')
- elif not self._requests:
- raise ValueError('Expected at least one request!')
- else:
- invocation_metadata = self._invocation_metadata
- self._invocation_metadata = None
- return invocation_metadata, self._requests.pop(0)
-
- def send_initial_metadata(self, initial_metadata):
- with self._condition:
- self._initial_metadata = _common.fuss_with_metadata(
- initial_metadata)
- self._condition.notify_all()
-
- def take_request(self):
- with self._condition:
- while True:
- if self._requests:
- return self._requests.pop(0)
- else:
- self._condition.wait()
-
- def requests_closed(self):
- with self._condition:
- while True:
- if self._requests_closed:
- return
- else:
- self._condition.wait()
-
- def send_response(self, response):
- with self._condition:
- if self._code is None:
- self._responses.append(response)
- self._condition.notify_all()
-
- def terminate_with_response(self, response, trailing_metadata, code,
- details):
- with self._condition:
- if self._initial_metadata is None:
- self._initial_metadata = _common.FUSSED_EMPTY_METADATA
- self._responses.append(response)
- self._trailing_metadata = _common.fuss_with_metadata(
- trailing_metadata)
- self._code = code
- self._details = details
- self._condition.notify_all()
-
- def terminate(self, trailing_metadata, code, details):
- with self._condition:
- if self._initial_metadata is None:
- self._initial_metadata = _common.FUSSED_EMPTY_METADATA
- self._trailing_metadata = _common.fuss_with_metadata(
- trailing_metadata)
- self._code = code
- self._details = details
- self._condition.notify_all()
-
- def cancelled(self):
- with self._condition:
- while True:
- if self._code is grpc.StatusCode.CANCELLED:
- return
- elif self._code is None:
- self._condition.wait()
- else:
- raise ValueError('Status code unexpectedly {}!'.format(
- self._code))
-
- def is_active(self):
- raise NotImplementedError()
-
- def time_remaining(self):
- raise NotImplementedError()
-
- def add_callback(self, callback):
- raise NotImplementedError()
+ elif self._code is None:
+ if self._responses:
+ response = self._responses.pop(0)
+ return _common.ChannelRpcRead(response, None, None,
+ None)
+ else:
+ self._condition.wait()
+ else:
+ return _common.ChannelRpcRead(None, self._trailing_metadata,
+ self._code, self._details)
+
+ def termination(self):
+ with self._condition:
+ while True:
+ if self._code is None:
+ self._condition.wait()
+ else:
+ return self._trailing_metadata, self._code, self._details
+
+ def cancel(self, code, details):
+ with self._condition:
+ if self._code is None:
+ if self._initial_metadata is None:
+ self._initial_metadata = _common.FUSSED_EMPTY_METADATA
+ self._trailing_metadata = _common.FUSSED_EMPTY_METADATA
+ self._code = code
+ self._details = details
+ self._condition.notify_all()
+ return True
+ else:
+ return False
+
+ def take_invocation_metadata(self):
+ with self._condition:
+ if self._invocation_metadata is None:
+ raise ValueError('Expected invocation metadata!')
+ else:
+ invocation_metadata = self._invocation_metadata
+ self._invocation_metadata = None
+ return invocation_metadata
+
+ def take_invocation_metadata_and_request(self):
+ with self._condition:
+ if self._invocation_metadata is None:
+ raise ValueError('Expected invocation metadata!')
+ elif not self._requests:
+ raise ValueError('Expected at least one request!')
+ else:
+ invocation_metadata = self._invocation_metadata
+ self._invocation_metadata = None
+ return invocation_metadata, self._requests.pop(0)
+
+ def send_initial_metadata(self, initial_metadata):
+ with self._condition:
+ self._initial_metadata = _common.fuss_with_metadata(
+ initial_metadata)
+ self._condition.notify_all()
+
+ def take_request(self):
+ with self._condition:
+ while True:
+ if self._requests:
+ return self._requests.pop(0)
+ else:
+ self._condition.wait()
+
+ def requests_closed(self):
+ with self._condition:
+ while True:
+ if self._requests_closed:
+ return
+ else:
+ self._condition.wait()
+
+ def send_response(self, response):
+ with self._condition:
+ if self._code is None:
+ self._responses.append(response)
+ self._condition.notify_all()
+
+ def terminate_with_response(self, response, trailing_metadata, code,
+ details):
+ with self._condition:
+ if self._initial_metadata is None:
+ self._initial_metadata = _common.FUSSED_EMPTY_METADATA
+ self._responses.append(response)
+ self._trailing_metadata = _common.fuss_with_metadata(
+ trailing_metadata)
+ self._code = code
+ self._details = details
+ self._condition.notify_all()
+
+ def terminate(self, trailing_metadata, code, details):
+ with self._condition:
+ if self._initial_metadata is None:
+ self._initial_metadata = _common.FUSSED_EMPTY_METADATA
+ self._trailing_metadata = _common.fuss_with_metadata(
+ trailing_metadata)
+ self._code = code
+ self._details = details
+ self._condition.notify_all()
+
+ def cancelled(self):
+ with self._condition:
+ while True:
+ if self._code is grpc.StatusCode.CANCELLED:
+ return
+ elif self._code is None:
+ self._condition.wait()
+ else:
+ raise ValueError('Status code unexpectedly {}!'.format(
+ self._code))
+
+ def is_active(self):
+ raise NotImplementedError()
+
+ def time_remaining(self):
+ raise NotImplementedError()
+
+ def add_callback(self, callback):
+ raise NotImplementedError()
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_common.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_common.py
index cebad31b5cc..8446044b0cb 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_common.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_common.py
@@ -1,162 +1,162 @@
-# 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 interfaces and implementation."""
-
-import abc
-import collections
-
-import six
-
-
-def _fuss(tuplified_metadata):
- return tuplified_metadata + ((
- 'grpc.metadata_added_by_runtime',
- 'gRPC is allowed to add metadata in transmission and does so.',
- ),)
-
-
-FUSSED_EMPTY_METADATA = _fuss(())
-
-
-def fuss_with_metadata(metadata):
- if metadata is None:
- return FUSSED_EMPTY_METADATA
- else:
- return _fuss(tuple(metadata))
-
-
-def rpc_names(service_descriptors):
- rpc_names_to_descriptors = {}
- for service_descriptor in service_descriptors:
- for method_descriptor in service_descriptor.methods_by_name.values():
- rpc_name = '/{}/{}'.format(service_descriptor.full_name,
- method_descriptor.name)
- rpc_names_to_descriptors[rpc_name] = method_descriptor
- return rpc_names_to_descriptors
-
-
-class ChannelRpcRead(
- collections.namedtuple('ChannelRpcRead', (
- 'response',
- 'trailing_metadata',
- 'code',
- 'details',
- ))):
- pass
-
-
-class ChannelRpcHandler(six.with_metaclass(abc.ABCMeta)):
-
- @abc.abstractmethod
- def initial_metadata(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def add_request(self, request):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def close_requests(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_response(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancel(self, code, details):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def termination(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def is_active(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def time_remaining(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def add_callback(self, callback):
- raise NotImplementedError()
-
-
-class ChannelHandler(six.with_metaclass(abc.ABCMeta)):
-
- @abc.abstractmethod
- def invoke_rpc(self, method_full_rpc_name, invocation_metadata, requests,
- requests_closed, timeout):
- raise NotImplementedError()
-
-
-class ServerRpcRead(
- collections.namedtuple('ServerRpcRead', (
- 'request',
- 'requests_closed',
- 'terminated',
- ))):
- pass
-
-
-REQUESTS_CLOSED = ServerRpcRead(None, True, False)
-TERMINATED = ServerRpcRead(None, False, True)
-
-
-class ServerRpcHandler(six.with_metaclass(abc.ABCMeta)):
-
- @abc.abstractmethod
- def send_initial_metadata(self, initial_metadata):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_request(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def add_response(self, response):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def send_termination(self, trailing_metadata, code, details):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def add_termination_callback(self, callback):
- raise NotImplementedError()
-
-
-class Serverish(six.with_metaclass(abc.ABCMeta)):
-
- @abc.abstractmethod
- def invoke_unary_unary(self, method_descriptor, handler,
- invocation_metadata, request, deadline):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def invoke_unary_stream(self, method_descriptor, handler,
- invocation_metadata, request, deadline):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def invoke_stream_unary(self, method_descriptor, handler,
- invocation_metadata, deadline):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def invoke_stream_stream(self, method_descriptor, handler,
- invocation_metadata, deadline):
- raise NotImplementedError()
+# 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 interfaces and implementation."""
+
+import abc
+import collections
+
+import six
+
+
+def _fuss(tuplified_metadata):
+ return tuplified_metadata + ((
+ 'grpc.metadata_added_by_runtime',
+ 'gRPC is allowed to add metadata in transmission and does so.',
+ ),)
+
+
+FUSSED_EMPTY_METADATA = _fuss(())
+
+
+def fuss_with_metadata(metadata):
+ if metadata is None:
+ return FUSSED_EMPTY_METADATA
+ else:
+ return _fuss(tuple(metadata))
+
+
+def rpc_names(service_descriptors):
+ rpc_names_to_descriptors = {}
+ for service_descriptor in service_descriptors:
+ for method_descriptor in service_descriptor.methods_by_name.values():
+ rpc_name = '/{}/{}'.format(service_descriptor.full_name,
+ method_descriptor.name)
+ rpc_names_to_descriptors[rpc_name] = method_descriptor
+ return rpc_names_to_descriptors
+
+
+class ChannelRpcRead(
+ collections.namedtuple('ChannelRpcRead', (
+ 'response',
+ 'trailing_metadata',
+ 'code',
+ 'details',
+ ))):
+ pass
+
+
+class ChannelRpcHandler(six.with_metaclass(abc.ABCMeta)):
+
+ @abc.abstractmethod
+ def initial_metadata(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def add_request(self, request):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def close_requests(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_response(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancel(self, code, details):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def termination(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def is_active(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def time_remaining(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def add_callback(self, callback):
+ raise NotImplementedError()
+
+
+class ChannelHandler(six.with_metaclass(abc.ABCMeta)):
+
+ @abc.abstractmethod
+ def invoke_rpc(self, method_full_rpc_name, invocation_metadata, requests,
+ requests_closed, timeout):
+ raise NotImplementedError()
+
+
+class ServerRpcRead(
+ collections.namedtuple('ServerRpcRead', (
+ 'request',
+ 'requests_closed',
+ 'terminated',
+ ))):
+ pass
+
+
+REQUESTS_CLOSED = ServerRpcRead(None, True, False)
+TERMINATED = ServerRpcRead(None, False, True)
+
+
+class ServerRpcHandler(six.with_metaclass(abc.ABCMeta)):
+
+ @abc.abstractmethod
+ def send_initial_metadata(self, initial_metadata):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_request(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def add_response(self, response):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def send_termination(self, trailing_metadata, code, details):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def add_termination_callback(self, callback):
+ raise NotImplementedError()
+
+
+class Serverish(six.with_metaclass(abc.ABCMeta)):
+
+ @abc.abstractmethod
+ def invoke_unary_unary(self, method_descriptor, handler,
+ invocation_metadata, request, deadline):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def invoke_unary_stream(self, method_descriptor, handler,
+ invocation_metadata, request, deadline):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def invoke_stream_unary(self, method_descriptor, handler,
+ invocation_metadata, deadline):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def invoke_stream_stream(self, method_descriptor, handler,
+ invocation_metadata, deadline):
+ raise NotImplementedError()
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/__init__.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/__init__.py
index 5f035a91cab..70f8955f4e8 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/__init__.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/__init__.py
@@ -1,20 +1,20 @@
-# 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 grpc_testing._server import _server
-
-
-def server_from_dictionary(descriptors_to_servicers, time):
- return _server.server_from_descriptor_to_servicers(descriptors_to_servicers,
- time)
+# 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 grpc_testing._server import _server
+
+
+def server_from_dictionary(descriptors_to_servicers, time):
+ return _server.server_from_descriptor_to_servicers(descriptors_to_servicers,
+ time)
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py
index 100d8195f62..3183656cfd1 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py
@@ -1,217 +1,217 @@
-# 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 abc
-import threading
-
-import grpc
-from grpc_testing import _common
-
-_CLIENT_INACTIVE = object()
-
-
-class Handler(_common.ServerRpcHandler):
-
- @abc.abstractmethod
- def initial_metadata(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def add_request(self, request):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def take_response(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def requests_closed(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def cancel(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def unary_response_termination(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def stream_response_termination(self):
- raise NotImplementedError()
-
-
-class _Handler(Handler):
-
- def __init__(self, requests_closed):
- self._condition = threading.Condition()
- self._requests = []
- self._requests_closed = requests_closed
- self._initial_metadata = None
- self._responses = []
- self._trailing_metadata = None
- self._code = None
- self._details = None
- self._unary_response = None
- self._expiration_future = None
- self._termination_callbacks = []
-
- def send_initial_metadata(self, initial_metadata):
- with self._condition:
- self._initial_metadata = initial_metadata
- self._condition.notify_all()
-
- def take_request(self):
- with self._condition:
- while True:
- if self._code is None:
- if self._requests:
- request = self._requests.pop(0)
- self._condition.notify_all()
- return _common.ServerRpcRead(request, False, False)
- elif self._requests_closed:
- return _common.REQUESTS_CLOSED
- else:
- self._condition.wait()
- else:
- return _common.TERMINATED
-
- def is_active(self):
- with self._condition:
- return self._code is None
-
- def add_response(self, response):
- with self._condition:
- self._responses.append(response)
- self._condition.notify_all()
-
- def send_termination(self, trailing_metadata, code, details):
- with self._condition:
- self._trailing_metadata = trailing_metadata
- self._code = code
- self._details = details
- if self._expiration_future is not None:
- self._expiration_future.cancel()
- self._condition.notify_all()
-
+# 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 abc
+import threading
+
+import grpc
+from grpc_testing import _common
+
+_CLIENT_INACTIVE = object()
+
+
+class Handler(_common.ServerRpcHandler):
+
+ @abc.abstractmethod
+ def initial_metadata(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def add_request(self, request):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def take_response(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def requests_closed(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def cancel(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def unary_response_termination(self):
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def stream_response_termination(self):
+ raise NotImplementedError()
+
+
+class _Handler(Handler):
+
+ def __init__(self, requests_closed):
+ self._condition = threading.Condition()
+ self._requests = []
+ self._requests_closed = requests_closed
+ self._initial_metadata = None
+ self._responses = []
+ self._trailing_metadata = None
+ self._code = None
+ self._details = None
+ self._unary_response = None
+ self._expiration_future = None
+ self._termination_callbacks = []
+
+ def send_initial_metadata(self, initial_metadata):
+ with self._condition:
+ self._initial_metadata = initial_metadata
+ self._condition.notify_all()
+
+ def take_request(self):
+ with self._condition:
+ while True:
+ if self._code is None:
+ if self._requests:
+ request = self._requests.pop(0)
+ self._condition.notify_all()
+ return _common.ServerRpcRead(request, False, False)
+ elif self._requests_closed:
+ return _common.REQUESTS_CLOSED
+ else:
+ self._condition.wait()
+ else:
+ return _common.TERMINATED
+
+ def is_active(self):
+ with self._condition:
+ return self._code is None
+
+ def add_response(self, response):
+ with self._condition:
+ self._responses.append(response)
+ self._condition.notify_all()
+
+ def send_termination(self, trailing_metadata, code, details):
+ with self._condition:
+ self._trailing_metadata = trailing_metadata
+ self._code = code
+ self._details = details
+ if self._expiration_future is not None:
+ self._expiration_future.cancel()
+ self._condition.notify_all()
+
def add_termination_callback(self, callback):
- with self._condition:
- if self._code is None:
+ with self._condition:
+ if self._code is None:
self._termination_callbacks.append(callback)
- return True
- else:
- return False
-
- def initial_metadata(self):
- with self._condition:
- while True:
- if self._initial_metadata is None:
- if self._code is None:
- self._condition.wait()
- else:
- raise ValueError(
- 'No initial metadata despite status code!')
- else:
- return self._initial_metadata
-
- def add_request(self, request):
- with self._condition:
- self._requests.append(request)
- self._condition.notify_all()
-
- def take_response(self):
- with self._condition:
- while True:
- if self._responses:
- response = self._responses.pop(0)
- self._condition.notify_all()
- return response
- elif self._code is None:
- self._condition.wait()
- else:
- raise ValueError('No more responses!')
-
- def requests_closed(self):
- with self._condition:
- self._requests_closed = True
- self._condition.notify_all()
-
- def cancel(self):
- with self._condition:
- if self._code is None:
- self._code = _CLIENT_INACTIVE
- termination_callbacks = self._termination_callbacks
- self._termination_callbacks = None
- if self._expiration_future is not None:
- self._expiration_future.cancel()
- self._condition.notify_all()
- for termination_callback in termination_callbacks:
- termination_callback()
-
- def unary_response_termination(self):
- with self._condition:
- while True:
- if self._code is _CLIENT_INACTIVE:
- raise ValueError('Huh? Cancelled but wanting status?')
- elif self._code is None:
- self._condition.wait()
- else:
- if self._unary_response is None:
- if self._responses:
- self._unary_response = self._responses.pop(0)
- return (
- self._unary_response,
- self._trailing_metadata,
- self._code,
- self._details,
- )
-
- def stream_response_termination(self):
- with self._condition:
- while True:
- if self._code is _CLIENT_INACTIVE:
- raise ValueError('Huh? Cancelled but wanting status?')
- elif self._code is None:
- self._condition.wait()
- else:
+ return True
+ else:
+ return False
+
+ def initial_metadata(self):
+ with self._condition:
+ while True:
+ if self._initial_metadata is None:
+ if self._code is None:
+ self._condition.wait()
+ else:
+ raise ValueError(
+ 'No initial metadata despite status code!')
+ else:
+ return self._initial_metadata
+
+ def add_request(self, request):
+ with self._condition:
+ self._requests.append(request)
+ self._condition.notify_all()
+
+ def take_response(self):
+ with self._condition:
+ while True:
+ if self._responses:
+ response = self._responses.pop(0)
+ self._condition.notify_all()
+ return response
+ elif self._code is None:
+ self._condition.wait()
+ else:
+ raise ValueError('No more responses!')
+
+ def requests_closed(self):
+ with self._condition:
+ self._requests_closed = True
+ self._condition.notify_all()
+
+ def cancel(self):
+ with self._condition:
+ if self._code is None:
+ self._code = _CLIENT_INACTIVE
+ termination_callbacks = self._termination_callbacks
+ self._termination_callbacks = None
+ if self._expiration_future is not None:
+ self._expiration_future.cancel()
+ self._condition.notify_all()
+ for termination_callback in termination_callbacks:
+ termination_callback()
+
+ def unary_response_termination(self):
+ with self._condition:
+ while True:
+ if self._code is _CLIENT_INACTIVE:
+ raise ValueError('Huh? Cancelled but wanting status?')
+ elif self._code is None:
+ self._condition.wait()
+ else:
+ if self._unary_response is None:
+ if self._responses:
+ self._unary_response = self._responses.pop(0)
+ return (
+ self._unary_response,
+ self._trailing_metadata,
+ self._code,
+ self._details,
+ )
+
+ def stream_response_termination(self):
+ with self._condition:
+ while True:
+ if self._code is _CLIENT_INACTIVE:
+ raise ValueError('Huh? Cancelled but wanting status?')
+ elif self._code is None:
+ self._condition.wait()
+ else:
return self._trailing_metadata, self._code, self._details
-
- def expire(self):
- with self._condition:
- if self._code is None:
- if self._initial_metadata is None:
- self._initial_metadata = _common.FUSSED_EMPTY_METADATA
- self._trailing_metadata = _common.FUSSED_EMPTY_METADATA
- self._code = grpc.StatusCode.DEADLINE_EXCEEDED
- self._details = 'Took too much time!'
- termination_callbacks = self._termination_callbacks
- self._termination_callbacks = None
- self._condition.notify_all()
- for termination_callback in termination_callbacks:
- termination_callback()
-
- def set_expiration_future(self, expiration_future):
- with self._condition:
- self._expiration_future = expiration_future
-
-
-def handler_without_deadline(requests_closed):
- return _Handler(requests_closed)
-
-
-def handler_with_deadline(requests_closed, time, deadline):
- handler = _Handler(requests_closed)
- expiration_future = time.call_at(handler.expire, deadline)
- handler.set_expiration_future(expiration_future)
- return handler
+
+ def expire(self):
+ with self._condition:
+ if self._code is None:
+ if self._initial_metadata is None:
+ self._initial_metadata = _common.FUSSED_EMPTY_METADATA
+ self._trailing_metadata = _common.FUSSED_EMPTY_METADATA
+ self._code = grpc.StatusCode.DEADLINE_EXCEEDED
+ self._details = 'Took too much time!'
+ termination_callbacks = self._termination_callbacks
+ self._termination_callbacks = None
+ self._condition.notify_all()
+ for termination_callback in termination_callbacks:
+ termination_callback()
+
+ def set_expiration_future(self, expiration_future):
+ with self._condition:
+ self._expiration_future = expiration_future
+
+
+def handler_without_deadline(requests_closed):
+ return _Handler(requests_closed)
+
+
+def handler_with_deadline(requests_closed, time, deadline):
+ handler = _Handler(requests_closed)
+ expiration_future = time.call_at(handler.expire, deadline)
+ handler.set_expiration_future(expiration_future)
+ return handler
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py
index 736b714dc6d..b2271dbcaef 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py
@@ -1,155 +1,155 @@
-# 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 logging
-import threading
-
-import grpc
-from grpc_testing import _common
-
+# 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 logging
+import threading
+
+import grpc
+from grpc_testing import _common
+
logging.basicConfig()
_LOGGER = logging.getLogger(__name__)
-
-
-class Rpc(object):
-
- def __init__(self, handler, invocation_metadata):
- self._condition = threading.Condition()
- self._handler = handler
- self._invocation_metadata = invocation_metadata
- self._initial_metadata_sent = False
- self._pending_trailing_metadata = None
- self._pending_code = None
- self._pending_details = None
- self._callbacks = []
- self._active = True
- self._rpc_errors = []
-
- def _ensure_initial_metadata_sent(self):
- if not self._initial_metadata_sent:
- self._handler.send_initial_metadata(_common.FUSSED_EMPTY_METADATA)
- self._initial_metadata_sent = True
-
- def _call_back(self):
- callbacks = tuple(self._callbacks)
- self._callbacks = None
-
- def call_back():
- for callback in callbacks:
- try:
- callback()
- except Exception: # pylint: disable=broad-except
+
+
+class Rpc(object):
+
+ def __init__(self, handler, invocation_metadata):
+ self._condition = threading.Condition()
+ self._handler = handler
+ self._invocation_metadata = invocation_metadata
+ self._initial_metadata_sent = False
+ self._pending_trailing_metadata = None
+ self._pending_code = None
+ self._pending_details = None
+ self._callbacks = []
+ self._active = True
+ self._rpc_errors = []
+
+ def _ensure_initial_metadata_sent(self):
+ if not self._initial_metadata_sent:
+ self._handler.send_initial_metadata(_common.FUSSED_EMPTY_METADATA)
+ self._initial_metadata_sent = True
+
+ def _call_back(self):
+ callbacks = tuple(self._callbacks)
+ self._callbacks = None
+
+ def call_back():
+ for callback in callbacks:
+ try:
+ callback()
+ except Exception: # pylint: disable=broad-except
_LOGGER.exception('Exception calling server-side callback!')
-
- callback_calling_thread = threading.Thread(target=call_back)
- callback_calling_thread.start()
-
- def _terminate(self, trailing_metadata, code, details):
- if self._active:
- self._active = False
- self._handler.send_termination(trailing_metadata, code, details)
- self._call_back()
- self._condition.notify_all()
-
- def _complete(self):
- if self._pending_trailing_metadata is None:
- trailing_metadata = _common.FUSSED_EMPTY_METADATA
- else:
- trailing_metadata = self._pending_trailing_metadata
- if self._pending_code is None:
- code = grpc.StatusCode.OK
- else:
- code = self._pending_code
- details = '' if self._pending_details is None else self._pending_details
- self._terminate(trailing_metadata, code, details)
-
- def _abort(self, code, details):
- self._terminate(_common.FUSSED_EMPTY_METADATA, code, details)
-
- def add_rpc_error(self, rpc_error):
- with self._condition:
- self._rpc_errors.append(rpc_error)
-
- def application_cancel(self):
- with self._condition:
- self._abort(grpc.StatusCode.CANCELLED,
- 'Cancelled by server-side application!')
-
- def application_exception_abort(self, exception):
- with self._condition:
- if exception not in self._rpc_errors:
+
+ callback_calling_thread = threading.Thread(target=call_back)
+ callback_calling_thread.start()
+
+ def _terminate(self, trailing_metadata, code, details):
+ if self._active:
+ self._active = False
+ self._handler.send_termination(trailing_metadata, code, details)
+ self._call_back()
+ self._condition.notify_all()
+
+ def _complete(self):
+ if self._pending_trailing_metadata is None:
+ trailing_metadata = _common.FUSSED_EMPTY_METADATA
+ else:
+ trailing_metadata = self._pending_trailing_metadata
+ if self._pending_code is None:
+ code = grpc.StatusCode.OK
+ else:
+ code = self._pending_code
+ details = '' if self._pending_details is None else self._pending_details
+ self._terminate(trailing_metadata, code, details)
+
+ def _abort(self, code, details):
+ self._terminate(_common.FUSSED_EMPTY_METADATA, code, details)
+
+ def add_rpc_error(self, rpc_error):
+ with self._condition:
+ self._rpc_errors.append(rpc_error)
+
+ def application_cancel(self):
+ with self._condition:
+ self._abort(grpc.StatusCode.CANCELLED,
+ 'Cancelled by server-side application!')
+
+ def application_exception_abort(self, exception):
+ with self._condition:
+ if exception not in self._rpc_errors:
_LOGGER.exception('Exception calling application!')
- self._abort(
- grpc.StatusCode.UNKNOWN,
- 'Exception calling application: {}'.format(exception))
-
- def extrinsic_abort(self):
- with self._condition:
- if self._active:
- self._active = False
- self._call_back()
- self._condition.notify_all()
-
- def unary_response_complete(self, response):
- with self._condition:
- self._ensure_initial_metadata_sent()
- self._handler.add_response(response)
- self._complete()
-
- def stream_response(self, response):
- with self._condition:
- self._ensure_initial_metadata_sent()
- self._handler.add_response(response)
-
- def stream_response_complete(self):
- with self._condition:
- self._ensure_initial_metadata_sent()
- self._complete()
-
- def send_initial_metadata(self, initial_metadata):
- with self._condition:
- if self._initial_metadata_sent:
- return False
- else:
- self._handler.send_initial_metadata(initial_metadata)
- self._initial_metadata_sent = True
- return True
-
- def is_active(self):
- with self._condition:
- return self._active
-
- def add_callback(self, callback):
- with self._condition:
- if self._callbacks is None:
- return False
- else:
- self._callbacks.append(callback)
- return True
-
- def invocation_metadata(self):
- with self._condition:
- return self._invocation_metadata
-
- def set_trailing_metadata(self, trailing_metadata):
- with self._condition:
- self._pending_trailing_metadata = trailing_metadata
-
- def set_code(self, code):
- with self._condition:
- self._pending_code = code
-
- def set_details(self, details):
- with self._condition:
- self._pending_details = details
+ self._abort(
+ grpc.StatusCode.UNKNOWN,
+ 'Exception calling application: {}'.format(exception))
+
+ def extrinsic_abort(self):
+ with self._condition:
+ if self._active:
+ self._active = False
+ self._call_back()
+ self._condition.notify_all()
+
+ def unary_response_complete(self, response):
+ with self._condition:
+ self._ensure_initial_metadata_sent()
+ self._handler.add_response(response)
+ self._complete()
+
+ def stream_response(self, response):
+ with self._condition:
+ self._ensure_initial_metadata_sent()
+ self._handler.add_response(response)
+
+ def stream_response_complete(self):
+ with self._condition:
+ self._ensure_initial_metadata_sent()
+ self._complete()
+
+ def send_initial_metadata(self, initial_metadata):
+ with self._condition:
+ if self._initial_metadata_sent:
+ return False
+ else:
+ self._handler.send_initial_metadata(initial_metadata)
+ self._initial_metadata_sent = True
+ return True
+
+ def is_active(self):
+ with self._condition:
+ return self._active
+
+ def add_callback(self, callback):
+ with self._condition:
+ if self._callbacks is None:
+ return False
+ else:
+ self._callbacks.append(callback)
+ return True
+
+ def invocation_metadata(self):
+ with self._condition:
+ return self._invocation_metadata
+
+ def set_trailing_metadata(self, trailing_metadata):
+ with self._condition:
+ self._pending_trailing_metadata = trailing_metadata
+
+ def set_code(self, code):
+ with self._condition:
+ self._pending_code = code
+
+ def set_details(self, details):
+ with self._condition:
+ self._pending_details = details
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server.py
index 6d256d848f7..7dc75510aaf 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server.py
@@ -1,154 +1,154 @@
-# 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 threading
-
-import grpc_testing
-from grpc_testing import _common
-from grpc_testing._server import _handler
-from grpc_testing._server import _rpc
-from grpc_testing._server import _server_rpc
-from grpc_testing._server import _service
-from grpc_testing._server import _servicer_context
-
-
-def _implementation(descriptors_to_servicers, method_descriptor):
- servicer = descriptors_to_servicers[method_descriptor.containing_service]
- return getattr(servicer, method_descriptor.name)
-
-
-def _unary_unary_service(request):
-
- def service(implementation, rpc, servicer_context):
- _service.unary_unary(implementation, rpc, request, servicer_context)
-
- return service
-
-
-def _unary_stream_service(request):
-
- def service(implementation, rpc, servicer_context):
- _service.unary_stream(implementation, rpc, request, servicer_context)
-
- return service
-
-
-def _stream_unary_service(handler):
-
- def service(implementation, rpc, servicer_context):
- _service.stream_unary(implementation, rpc, handler, servicer_context)
-
- return service
-
-
-def _stream_stream_service(handler):
-
- def service(implementation, rpc, servicer_context):
- _service.stream_stream(implementation, rpc, handler, servicer_context)
-
- return service
-
-
-class _Serverish(_common.Serverish):
-
- def __init__(self, descriptors_to_servicers, time):
- self._descriptors_to_servicers = descriptors_to_servicers
- self._time = time
-
- def _invoke(self, service_behavior, method_descriptor, handler,
- invocation_metadata, deadline):
- implementation = _implementation(self._descriptors_to_servicers,
- method_descriptor)
- rpc = _rpc.Rpc(handler, invocation_metadata)
- if handler.add_termination_callback(rpc.extrinsic_abort):
- servicer_context = _servicer_context.ServicerContext(
- rpc, self._time, deadline)
+# 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 threading
+
+import grpc_testing
+from grpc_testing import _common
+from grpc_testing._server import _handler
+from grpc_testing._server import _rpc
+from grpc_testing._server import _server_rpc
+from grpc_testing._server import _service
+from grpc_testing._server import _servicer_context
+
+
+def _implementation(descriptors_to_servicers, method_descriptor):
+ servicer = descriptors_to_servicers[method_descriptor.containing_service]
+ return getattr(servicer, method_descriptor.name)
+
+
+def _unary_unary_service(request):
+
+ def service(implementation, rpc, servicer_context):
+ _service.unary_unary(implementation, rpc, request, servicer_context)
+
+ return service
+
+
+def _unary_stream_service(request):
+
+ def service(implementation, rpc, servicer_context):
+ _service.unary_stream(implementation, rpc, request, servicer_context)
+
+ return service
+
+
+def _stream_unary_service(handler):
+
+ def service(implementation, rpc, servicer_context):
+ _service.stream_unary(implementation, rpc, handler, servicer_context)
+
+ return service
+
+
+def _stream_stream_service(handler):
+
+ def service(implementation, rpc, servicer_context):
+ _service.stream_stream(implementation, rpc, handler, servicer_context)
+
+ return service
+
+
+class _Serverish(_common.Serverish):
+
+ def __init__(self, descriptors_to_servicers, time):
+ self._descriptors_to_servicers = descriptors_to_servicers
+ self._time = time
+
+ def _invoke(self, service_behavior, method_descriptor, handler,
+ invocation_metadata, deadline):
+ implementation = _implementation(self._descriptors_to_servicers,
+ method_descriptor)
+ rpc = _rpc.Rpc(handler, invocation_metadata)
+ if handler.add_termination_callback(rpc.extrinsic_abort):
+ servicer_context = _servicer_context.ServicerContext(
+ rpc, self._time, deadline)
service_thread = threading.Thread(target=service_behavior,
args=(
implementation,
rpc,
servicer_context,
))
- service_thread.start()
-
- def invoke_unary_unary(self, method_descriptor, handler,
- invocation_metadata, request, deadline):
+ service_thread.start()
+
+ def invoke_unary_unary(self, method_descriptor, handler,
+ invocation_metadata, request, deadline):
self._invoke(_unary_unary_service(request), method_descriptor, handler,
invocation_metadata, deadline)
-
- def invoke_unary_stream(self, method_descriptor, handler,
- invocation_metadata, request, deadline):
+
+ def invoke_unary_stream(self, method_descriptor, handler,
+ invocation_metadata, request, deadline):
self._invoke(_unary_stream_service(request), method_descriptor, handler,
invocation_metadata, deadline)
-
- def invoke_stream_unary(self, method_descriptor, handler,
- invocation_metadata, deadline):
+
+ def invoke_stream_unary(self, method_descriptor, handler,
+ invocation_metadata, deadline):
self._invoke(_stream_unary_service(handler), method_descriptor, handler,
invocation_metadata, deadline)
-
- def invoke_stream_stream(self, method_descriptor, handler,
- invocation_metadata, deadline):
+
+ def invoke_stream_stream(self, method_descriptor, handler,
+ invocation_metadata, deadline):
self._invoke(_stream_stream_service(handler), method_descriptor,
handler, invocation_metadata, deadline)
-
-
-def _deadline_and_handler(requests_closed, time, timeout):
- if timeout is None:
- return None, _handler.handler_without_deadline(requests_closed)
- else:
- deadline = time.time() + timeout
- handler = _handler.handler_with_deadline(requests_closed, time,
- deadline)
- return deadline, handler
-
-
-class _Server(grpc_testing.Server):
-
- def __init__(self, serverish, time):
- self._serverish = serverish
- self._time = time
-
- def invoke_unary_unary(self, method_descriptor, invocation_metadata,
- request, timeout):
- deadline, handler = _deadline_and_handler(True, self._time, timeout)
+
+
+def _deadline_and_handler(requests_closed, time, timeout):
+ if timeout is None:
+ return None, _handler.handler_without_deadline(requests_closed)
+ else:
+ deadline = time.time() + timeout
+ handler = _handler.handler_with_deadline(requests_closed, time,
+ deadline)
+ return deadline, handler
+
+
+class _Server(grpc_testing.Server):
+
+ def __init__(self, serverish, time):
+ self._serverish = serverish
+ self._time = time
+
+ def invoke_unary_unary(self, method_descriptor, invocation_metadata,
+ request, timeout):
+ deadline, handler = _deadline_and_handler(True, self._time, timeout)
self._serverish.invoke_unary_unary(method_descriptor, handler,
invocation_metadata, request,
deadline)
- return _server_rpc.UnaryUnaryServerRpc(handler)
-
- def invoke_unary_stream(self, method_descriptor, invocation_metadata,
- request, timeout):
- deadline, handler = _deadline_and_handler(True, self._time, timeout)
+ return _server_rpc.UnaryUnaryServerRpc(handler)
+
+ def invoke_unary_stream(self, method_descriptor, invocation_metadata,
+ request, timeout):
+ deadline, handler = _deadline_and_handler(True, self._time, timeout)
self._serverish.invoke_unary_stream(method_descriptor, handler,
invocation_metadata, request,
deadline)
- return _server_rpc.UnaryStreamServerRpc(handler)
-
- def invoke_stream_unary(self, method_descriptor, invocation_metadata,
- timeout):
- deadline, handler = _deadline_and_handler(False, self._time, timeout)
- self._serverish.invoke_stream_unary(method_descriptor, handler,
- invocation_metadata, deadline)
- return _server_rpc.StreamUnaryServerRpc(handler)
-
- def invoke_stream_stream(self, method_descriptor, invocation_metadata,
- timeout):
- deadline, handler = _deadline_and_handler(False, self._time, timeout)
- self._serverish.invoke_stream_stream(method_descriptor, handler,
- invocation_metadata, deadline)
- return _server_rpc.StreamStreamServerRpc(handler)
-
-
-def server_from_descriptor_to_servicers(descriptors_to_servicers, time):
- return _Server(_Serverish(descriptors_to_servicers, time), time)
+ return _server_rpc.UnaryStreamServerRpc(handler)
+
+ def invoke_stream_unary(self, method_descriptor, invocation_metadata,
+ timeout):
+ deadline, handler = _deadline_and_handler(False, self._time, timeout)
+ self._serverish.invoke_stream_unary(method_descriptor, handler,
+ invocation_metadata, deadline)
+ return _server_rpc.StreamUnaryServerRpc(handler)
+
+ def invoke_stream_stream(self, method_descriptor, invocation_metadata,
+ timeout):
+ deadline, handler = _deadline_and_handler(False, self._time, timeout)
+ self._serverish.invoke_stream_stream(method_descriptor, handler,
+ invocation_metadata, deadline)
+ return _server_rpc.StreamStreamServerRpc(handler)
+
+
+def server_from_descriptor_to_servicers(descriptors_to_servicers, time):
+ return _Server(_Serverish(descriptors_to_servicers, time), time)
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server_rpc.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server_rpc.py
index 30de8ff0e2b..ef1ceea4703 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server_rpc.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_server_rpc.py
@@ -1,93 +1,93 @@
-# 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
-
-
-class UnaryUnaryServerRpc(grpc_testing.UnaryUnaryServerRpc):
-
- def __init__(self, handler):
- self._handler = handler
-
- def initial_metadata(self):
- return self._handler.initial_metadata()
-
- def cancel(self):
- self._handler.cancel()
-
- def termination(self):
- return self._handler.unary_response_termination()
-
-
-class UnaryStreamServerRpc(grpc_testing.UnaryStreamServerRpc):
-
- def __init__(self, handler):
- self._handler = handler
-
- def initial_metadata(self):
- return self._handler.initial_metadata()
-
- def take_response(self):
- return self._handler.take_response()
-
- def cancel(self):
- self._handler.cancel()
-
- def termination(self):
- return self._handler.stream_response_termination()
-
-
-class StreamUnaryServerRpc(grpc_testing.StreamUnaryServerRpc):
-
- def __init__(self, handler):
- self._handler = handler
-
- def initial_metadata(self):
- return self._handler.initial_metadata()
-
- def send_request(self, request):
- self._handler.add_request(request)
-
- def requests_closed(self):
- self._handler.requests_closed()
-
- def cancel(self):
- self._handler.cancel()
-
- def termination(self):
- return self._handler.unary_response_termination()
-
-
-class StreamStreamServerRpc(grpc_testing.StreamStreamServerRpc):
-
- def __init__(self, handler):
- self._handler = handler
-
- def initial_metadata(self):
- return self._handler.initial_metadata()
-
- def send_request(self, request):
- self._handler.add_request(request)
-
- def requests_closed(self):
- self._handler.requests_closed()
-
- def take_response(self):
- return self._handler.take_response()
-
- def cancel(self):
- self._handler.cancel()
-
- def termination(self):
- return self._handler.stream_response_termination()
+# 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
+
+
+class UnaryUnaryServerRpc(grpc_testing.UnaryUnaryServerRpc):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def initial_metadata(self):
+ return self._handler.initial_metadata()
+
+ def cancel(self):
+ self._handler.cancel()
+
+ def termination(self):
+ return self._handler.unary_response_termination()
+
+
+class UnaryStreamServerRpc(grpc_testing.UnaryStreamServerRpc):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def initial_metadata(self):
+ return self._handler.initial_metadata()
+
+ def take_response(self):
+ return self._handler.take_response()
+
+ def cancel(self):
+ self._handler.cancel()
+
+ def termination(self):
+ return self._handler.stream_response_termination()
+
+
+class StreamUnaryServerRpc(grpc_testing.StreamUnaryServerRpc):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def initial_metadata(self):
+ return self._handler.initial_metadata()
+
+ def send_request(self, request):
+ self._handler.add_request(request)
+
+ def requests_closed(self):
+ self._handler.requests_closed()
+
+ def cancel(self):
+ self._handler.cancel()
+
+ def termination(self):
+ return self._handler.unary_response_termination()
+
+
+class StreamStreamServerRpc(grpc_testing.StreamStreamServerRpc):
+
+ def __init__(self, handler):
+ self._handler = handler
+
+ def initial_metadata(self):
+ return self._handler.initial_metadata()
+
+ def send_request(self, request):
+ self._handler.add_request(request)
+
+ def requests_closed(self):
+ self._handler.requests_closed()
+
+ def take_response(self):
+ return self._handler.take_response()
+
+ def cancel(self):
+ self._handler.cancel()
+
+ def termination(self):
+ return self._handler.stream_response_termination()
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 a65628a1216..f87a70d7cd6 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
@@ -1,89 +1,89 @@
-# 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.
+
import copy
-import grpc
-
-
-class _RequestIterator(object):
-
- def __init__(self, rpc, handler):
- self._rpc = rpc
- self._handler = handler
-
- def _next(self):
- read = self._handler.take_request()
- if read.requests_closed:
- raise StopIteration()
- elif read.terminated:
- rpc_error = grpc.RpcError()
- self._rpc.add_rpc_error(rpc_error)
- raise rpc_error
- else:
- return read.request
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return self._next()
-
- def next(self):
- return self._next()
-
-
-def _unary_response(argument, implementation, rpc, servicer_context):
- try:
- response = implementation(argument, servicer_context)
- except Exception as exception: # pylint: disable=broad-except
- rpc.application_exception_abort(exception)
- else:
- rpc.unary_response_complete(response)
-
-
-def _stream_response(argument, implementation, rpc, servicer_context):
- try:
- response_iterator = implementation(argument, servicer_context)
- except Exception as exception: # pylint: disable=broad-except
- rpc.application_exception_abort(exception)
- else:
- while True:
- try:
+import grpc
+
+
+class _RequestIterator(object):
+
+ def __init__(self, rpc, handler):
+ self._rpc = rpc
+ self._handler = handler
+
+ def _next(self):
+ read = self._handler.take_request()
+ if read.requests_closed:
+ raise StopIteration()
+ elif read.terminated:
+ rpc_error = grpc.RpcError()
+ self._rpc.add_rpc_error(rpc_error)
+ raise rpc_error
+ else:
+ return read.request
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return self._next()
+
+ def next(self):
+ return self._next()
+
+
+def _unary_response(argument, implementation, rpc, servicer_context):
+ try:
+ response = implementation(argument, servicer_context)
+ except Exception as exception: # pylint: disable=broad-except
+ rpc.application_exception_abort(exception)
+ else:
+ rpc.unary_response_complete(response)
+
+
+def _stream_response(argument, implementation, rpc, servicer_context):
+ try:
+ response_iterator = implementation(argument, servicer_context)
+ except Exception as exception: # pylint: disable=broad-except
+ rpc.application_exception_abort(exception)
+ else:
+ while True:
+ try:
response = copy.deepcopy(next(response_iterator))
- except StopIteration:
- rpc.stream_response_complete()
- break
- except Exception as exception: # pylint: disable=broad-except
- rpc.application_exception_abort(exception)
- break
- else:
- rpc.stream_response(response)
-
-
-def unary_unary(implementation, rpc, request, servicer_context):
- _unary_response(request, implementation, rpc, servicer_context)
-
-
-def unary_stream(implementation, rpc, request, servicer_context):
- _stream_response(request, implementation, rpc, servicer_context)
-
-
-def stream_unary(implementation, rpc, handler, servicer_context):
+ except StopIteration:
+ rpc.stream_response_complete()
+ break
+ except Exception as exception: # pylint: disable=broad-except
+ rpc.application_exception_abort(exception)
+ break
+ else:
+ rpc.stream_response(response)
+
+
+def unary_unary(implementation, rpc, request, servicer_context):
+ _unary_response(request, implementation, rpc, servicer_context)
+
+
+def unary_stream(implementation, rpc, request, servicer_context):
+ _stream_response(request, implementation, rpc, servicer_context)
+
+
+def stream_unary(implementation, rpc, handler, servicer_context):
_unary_response(_RequestIterator(rpc, handler), implementation, rpc,
servicer_context)
-
-
-def stream_stream(implementation, rpc, handler, servicer_context):
+
+
+def stream_stream(implementation, rpc, handler, servicer_context):
_stream_response(_RequestIterator(rpc, handler), implementation, rpc,
servicer_context)
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 c63750f9785..c78ed804c32 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
@@ -1,88 +1,88 @@
-# 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
-from grpc_testing import _common
-
-
-class ServicerContext(grpc.ServicerContext):
-
- def __init__(self, rpc, time, deadline):
- self._rpc = rpc
- self._time = time
- self._deadline = deadline
-
- def is_active(self):
- return self._rpc.is_active()
-
- def time_remaining(self):
- if self._rpc.is_active():
- if self._deadline is None:
- return None
- else:
- return max(0.0, self._deadline - self._time.time())
- else:
- return 0.0
-
- def cancel(self):
- self._rpc.application_cancel()
-
- def add_callback(self, callback):
- return self._rpc.add_callback(callback)
-
- def invocation_metadata(self):
- return self._rpc.invocation_metadata()
-
- def peer(self):
- raise NotImplementedError()
-
- def peer_identities(self):
- raise NotImplementedError()
-
- def peer_identity_key(self):
- raise NotImplementedError()
-
- def auth_context(self):
- raise NotImplementedError()
-
+# 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
+from grpc_testing import _common
+
+
+class ServicerContext(grpc.ServicerContext):
+
+ def __init__(self, rpc, time, deadline):
+ self._rpc = rpc
+ self._time = time
+ self._deadline = deadline
+
+ def is_active(self):
+ return self._rpc.is_active()
+
+ def time_remaining(self):
+ if self._rpc.is_active():
+ if self._deadline is None:
+ return None
+ else:
+ return max(0.0, self._deadline - self._time.time())
+ else:
+ return 0.0
+
+ def cancel(self):
+ self._rpc.application_cancel()
+
+ def add_callback(self, callback):
+ return self._rpc.add_callback(callback)
+
+ def invocation_metadata(self):
+ return self._rpc.invocation_metadata()
+
+ def peer(self):
+ raise NotImplementedError()
+
+ def peer_identities(self):
+ raise NotImplementedError()
+
+ def peer_identity_key(self):
+ raise NotImplementedError()
+
+ def auth_context(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))
- if not initial_metadata_sent:
- raise ValueError(
- 'ServicerContext.send_initial_metadata called too late!')
-
+ def send_initial_metadata(self, initial_metadata):
+ initial_metadata_sent = self._rpc.send_initial_metadata(
+ _common.fuss_with_metadata(initial_metadata))
+ if not initial_metadata_sent:
+ raise ValueError(
+ 'ServicerContext.send_initial_metadata called too late!')
+
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):
+ 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()
-
+
def abort_with_status(self, status):
raise NotImplementedError()
- def set_code(self, code):
- self._rpc.set_code(code)
-
- def set_details(self, details):
- self._rpc.set_details(details)
+ def set_code(self, code):
+ self._rpc.set_code(code)
+
+ def set_details(self, details):
+ self._rpc.set_details(details)
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py
index 9692c34e6f3..a02b80bee1b 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py
@@ -1,229 +1,229 @@
-# 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 times."""
-
-import collections
-import logging
-import threading
-import time as _time
-
-import grpc
-import grpc_testing
-
+# 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 times."""
+
+import collections
+import logging
+import threading
+import time as _time
+
+import grpc
+import grpc_testing
+
logging.basicConfig()
_LOGGER = logging.getLogger(__name__)
+
-
-def _call(behaviors):
- for behavior in behaviors:
- try:
- behavior()
- except Exception: # pylint: disable=broad-except
+def _call(behaviors):
+ for behavior in behaviors:
+ try:
+ behavior()
+ except Exception: # pylint: disable=broad-except
_LOGGER.exception('Exception calling behavior "%r"!', behavior)
-
-
-def _call_in_thread(behaviors):
- calling = threading.Thread(target=_call, args=(behaviors,))
- calling.start()
- # NOTE(nathaniel): Because this function is called from "strict" Time
- # implementations, it blocks until after all behaviors have terminated.
- calling.join()
-
-
-class _State(object):
-
- def __init__(self):
- self.condition = threading.Condition()
- self.times_to_behaviors = collections.defaultdict(list)
-
-
-class _Delta(
- collections.namedtuple('_Delta', (
- 'mature_behaviors',
- 'earliest_mature_time',
- 'earliest_immature_time',
- ))):
- pass
-
-
-def _process(state, now):
- mature_behaviors = []
- earliest_mature_time = None
- while state.times_to_behaviors:
- earliest_time = min(state.times_to_behaviors)
- if earliest_time <= now:
- if earliest_mature_time is None:
- earliest_mature_time = earliest_time
- earliest_mature_behaviors = state.times_to_behaviors.pop(
- earliest_time)
- mature_behaviors.extend(earliest_mature_behaviors)
- else:
- earliest_immature_time = earliest_time
- break
- else:
- earliest_immature_time = None
- return _Delta(mature_behaviors, earliest_mature_time,
- earliest_immature_time)
-
-
-class _Future(grpc.Future):
-
- def __init__(self, state, behavior, time):
- self._state = state
- self._behavior = behavior
- self._time = time
- self._cancelled = False
-
- def cancel(self):
- with self._state.condition:
- if self._cancelled:
- return True
- else:
- behaviors_at_time = self._state.times_to_behaviors.get(
- self._time)
- if behaviors_at_time is None:
- return False
- else:
- behaviors_at_time.remove(self._behavior)
- if not behaviors_at_time:
- self._state.times_to_behaviors.pop(self._time)
- self._state.condition.notify_all()
- self._cancelled = True
- return True
-
- def cancelled(self):
- with self._state.condition:
- return self._cancelled
-
- def running(self):
- raise NotImplementedError()
-
- def done(self):
- raise NotImplementedError()
-
- def result(self, timeout=None):
- raise NotImplementedError()
-
- def exception(self, timeout=None):
- raise NotImplementedError()
-
- def traceback(self, timeout=None):
- raise NotImplementedError()
-
- def add_done_callback(self, fn):
- raise NotImplementedError()
-
-
-class StrictRealTime(grpc_testing.Time):
-
- def __init__(self):
- self._state = _State()
- self._active = False
- self._calling = None
-
- def _activity(self):
- while True:
- with self._state.condition:
- while True:
- now = _time.time()
- delta = _process(self._state, now)
- self._state.condition.notify_all()
- if delta.mature_behaviors:
- self._calling = delta.earliest_mature_time
- break
- self._calling = None
- if delta.earliest_immature_time is None:
- self._active = False
- return
- else:
- timeout = max(0, delta.earliest_immature_time - now)
- self._state.condition.wait(timeout=timeout)
- _call(delta.mature_behaviors)
-
- def _ensure_called_through(self, time):
- with self._state.condition:
- while ((self._state.times_to_behaviors and
- min(self._state.times_to_behaviors) < time) or
- (self._calling is not None and self._calling < time)):
- self._state.condition.wait()
-
- def _call_at(self, behavior, time):
- with self._state.condition:
- self._state.times_to_behaviors[time].append(behavior)
- if self._active:
- self._state.condition.notify_all()
- else:
- activity = threading.Thread(target=self._activity)
- activity.start()
- self._active = True
- return _Future(self._state, behavior, time)
-
- def time(self):
- return _time.time()
-
- def call_in(self, behavior, delay):
- return self._call_at(behavior, _time.time() + delay)
-
- def call_at(self, behavior, time):
- return self._call_at(behavior, time)
-
- def sleep_for(self, duration):
- time = _time.time() + duration
- _time.sleep(duration)
- self._ensure_called_through(time)
-
- def sleep_until(self, time):
- _time.sleep(max(0, time - _time.time()))
- self._ensure_called_through(time)
-
-
-class StrictFakeTime(grpc_testing.Time):
-
- def __init__(self, time):
- self._state = _State()
- self._time = time
-
- def time(self):
- return self._time
-
- def call_in(self, behavior, delay):
- if delay <= 0:
- _call_in_thread((behavior,))
- else:
- with self._state.condition:
- time = self._time + delay
- self._state.times_to_behaviors[time].append(behavior)
- return _Future(self._state, behavior, time)
-
- def call_at(self, behavior, time):
- with self._state.condition:
- if time <= self._time:
- _call_in_thread((behavior,))
- else:
- self._state.times_to_behaviors[time].append(behavior)
- return _Future(self._state, behavior, time)
-
- def sleep_for(self, duration):
- if 0 < duration:
- with self._state.condition:
- self._time += duration
- delta = _process(self._state, self._time)
- _call_in_thread(delta.mature_behaviors)
-
- def sleep_until(self, time):
- with self._state.condition:
- if self._time < time:
- self._time = time
- delta = _process(self._state, self._time)
- _call_in_thread(delta.mature_behaviors)
+
+
+def _call_in_thread(behaviors):
+ calling = threading.Thread(target=_call, args=(behaviors,))
+ calling.start()
+ # NOTE(nathaniel): Because this function is called from "strict" Time
+ # implementations, it blocks until after all behaviors have terminated.
+ calling.join()
+
+
+class _State(object):
+
+ def __init__(self):
+ self.condition = threading.Condition()
+ self.times_to_behaviors = collections.defaultdict(list)
+
+
+class _Delta(
+ collections.namedtuple('_Delta', (
+ 'mature_behaviors',
+ 'earliest_mature_time',
+ 'earliest_immature_time',
+ ))):
+ pass
+
+
+def _process(state, now):
+ mature_behaviors = []
+ earliest_mature_time = None
+ while state.times_to_behaviors:
+ earliest_time = min(state.times_to_behaviors)
+ if earliest_time <= now:
+ if earliest_mature_time is None:
+ earliest_mature_time = earliest_time
+ earliest_mature_behaviors = state.times_to_behaviors.pop(
+ earliest_time)
+ mature_behaviors.extend(earliest_mature_behaviors)
+ else:
+ earliest_immature_time = earliest_time
+ break
+ else:
+ earliest_immature_time = None
+ return _Delta(mature_behaviors, earliest_mature_time,
+ earliest_immature_time)
+
+
+class _Future(grpc.Future):
+
+ def __init__(self, state, behavior, time):
+ self._state = state
+ self._behavior = behavior
+ self._time = time
+ self._cancelled = False
+
+ def cancel(self):
+ with self._state.condition:
+ if self._cancelled:
+ return True
+ else:
+ behaviors_at_time = self._state.times_to_behaviors.get(
+ self._time)
+ if behaviors_at_time is None:
+ return False
+ else:
+ behaviors_at_time.remove(self._behavior)
+ if not behaviors_at_time:
+ self._state.times_to_behaviors.pop(self._time)
+ self._state.condition.notify_all()
+ self._cancelled = True
+ return True
+
+ def cancelled(self):
+ with self._state.condition:
+ return self._cancelled
+
+ def running(self):
+ raise NotImplementedError()
+
+ def done(self):
+ raise NotImplementedError()
+
+ def result(self, timeout=None):
+ raise NotImplementedError()
+
+ def exception(self, timeout=None):
+ raise NotImplementedError()
+
+ def traceback(self, timeout=None):
+ raise NotImplementedError()
+
+ def add_done_callback(self, fn):
+ raise NotImplementedError()
+
+
+class StrictRealTime(grpc_testing.Time):
+
+ def __init__(self):
+ self._state = _State()
+ self._active = False
+ self._calling = None
+
+ def _activity(self):
+ while True:
+ with self._state.condition:
+ while True:
+ now = _time.time()
+ delta = _process(self._state, now)
+ self._state.condition.notify_all()
+ if delta.mature_behaviors:
+ self._calling = delta.earliest_mature_time
+ break
+ self._calling = None
+ if delta.earliest_immature_time is None:
+ self._active = False
+ return
+ else:
+ timeout = max(0, delta.earliest_immature_time - now)
+ self._state.condition.wait(timeout=timeout)
+ _call(delta.mature_behaviors)
+
+ def _ensure_called_through(self, time):
+ with self._state.condition:
+ while ((self._state.times_to_behaviors and
+ min(self._state.times_to_behaviors) < time) or
+ (self._calling is not None and self._calling < time)):
+ self._state.condition.wait()
+
+ def _call_at(self, behavior, time):
+ with self._state.condition:
+ self._state.times_to_behaviors[time].append(behavior)
+ if self._active:
+ self._state.condition.notify_all()
+ else:
+ activity = threading.Thread(target=self._activity)
+ activity.start()
+ self._active = True
+ return _Future(self._state, behavior, time)
+
+ def time(self):
+ return _time.time()
+
+ def call_in(self, behavior, delay):
+ return self._call_at(behavior, _time.time() + delay)
+
+ def call_at(self, behavior, time):
+ return self._call_at(behavior, time)
+
+ def sleep_for(self, duration):
+ time = _time.time() + duration
+ _time.sleep(duration)
+ self._ensure_called_through(time)
+
+ def sleep_until(self, time):
+ _time.sleep(max(0, time - _time.time()))
+ self._ensure_called_through(time)
+
+
+class StrictFakeTime(grpc_testing.Time):
+
+ def __init__(self, time):
+ self._state = _State()
+ self._time = time
+
+ def time(self):
+ return self._time
+
+ def call_in(self, behavior, delay):
+ if delay <= 0:
+ _call_in_thread((behavior,))
+ else:
+ with self._state.condition:
+ time = self._time + delay
+ self._state.times_to_behaviors[time].append(behavior)
+ return _Future(self._state, behavior, time)
+
+ def call_at(self, behavior, time):
+ with self._state.condition:
+ if time <= self._time:
+ _call_in_thread((behavior,))
+ else:
+ self._state.times_to_behaviors[time].append(behavior)
+ return _Future(self._state, behavior, time)
+
+ def sleep_for(self, duration):
+ if 0 < duration:
+ with self._state.condition:
+ self._time += duration
+ delta = _process(self._state, self._time)
+ _call_in_thread(delta.mature_behaviors)
+
+ def sleep_until(self, time):
+ with self._state.condition:
+ if self._time < time:
+ self._time = time
+ delta = _process(self._state, self._time)
+ _call_in_thread(delta.mature_behaviors)
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_version.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_version.py
index c042934ba35..0054b1442b0 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_version.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_version.py
@@ -1,17 +1,17 @@
-# 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.
-
-# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_testing/grpc_version.py.template`!!!
-
+# 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.
+
+# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_testing/grpc_version.py.template`!!!
+
VERSION = '1.33.2'
diff --git a/contrib/libs/grpc/src/python/grpcio_testing/setup.py b/contrib/libs/grpc/src/python/grpcio_testing/setup.py
index 1946793fe62..955801a4811 100644
--- a/contrib/libs/grpc/src/python/grpcio_testing/setup.py
+++ b/contrib/libs/grpc/src/python/grpcio_testing/setup.py
@@ -1,32 +1,32 @@
-# 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.
-"""Setup module for gRPC Python's testing package."""
-
-import os
-import sys
-
-import setuptools
-
+# 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.
+"""Setup module for gRPC Python's testing package."""
+
+import os
+import sys
+
+import setuptools
+
_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__)))
-
-# Break import style to ensure that we can find same-directory modules.
-import grpc_version
-
+# 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 that we can find same-directory modules.
+import grpc_version
+
class _NoOpCommand(setuptools.Command):
"""No-op command."""
@@ -44,15 +44,15 @@ class _NoOpCommand(setuptools.Command):
pass
-PACKAGE_DIRECTORIES = {
- '': '.',
-}
-
-INSTALL_REQUIRES = (
+PACKAGE_DIRECTORIES = {
+ '': '.',
+}
+
+INSTALL_REQUIRES = (
'protobuf>=3.6.0',
- 'grpcio>={version}'.format(version=grpc_version.VERSION),
-)
-
+ 'grpcio>={version}'.format(version=grpc_version.VERSION),
+)
+
try:
import testing_commands as _testing_commands
# we are in the build environment, otherwise the above import fails